Archived
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1b3b709ba5 | ||
|
|
26c5f6f06b | ||
|
|
22ded87250 | ||
|
|
84c0497f21 | ||
|
|
724eae1142 | ||
|
|
654cfec147 |
+25
@@ -1,4 +1,29 @@
|
|||||||
node_modules
|
node_modules
|
||||||
|
dist
|
||||||
|
frontend/dist
|
||||||
|
frontend/dist/assets
|
||||||
|
frontend/dist/assets/index.html
|
||||||
|
frontend/dist/assets/index.html.gz
|
||||||
|
frontend/dist/assets/index.html.br
|
||||||
|
frontend/dist/assets/index.html.brotli
|
||||||
|
frontend/dist/assets/index.html.gzip
|
||||||
|
frontend/dist/assets/index.html.br
|
||||||
|
frontend/dist/assets/index.html.brotli
|
||||||
|
frontend/dist/assets/index.html.gzip
|
||||||
|
frontend/dist/assets/index.html.br
|
||||||
|
frontend/dist/assets/index.html.brotli
|
||||||
|
frontend/dist/assets/index.html.gzip
|
||||||
|
frontend/dist/assets/index.html.br
|
||||||
|
frontend/dist/assets/index.html.brotli
|
||||||
|
frontend/dist/assets/index.html.gzip
|
||||||
|
frontend/dist/assets/index.html.br
|
||||||
|
frontend/dist/assets/index.html.brotli
|
||||||
|
frontend/dist/assets/index.html.gzip
|
||||||
|
mobile/dist
|
||||||
|
backend/media
|
||||||
|
backend/staticfiles
|
||||||
|
backend/media
|
||||||
|
backend/staticfiles
|
||||||
.pycache__
|
.pycache__
|
||||||
__pycache__
|
__pycache__
|
||||||
*.pyc
|
*.pyc
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
from apps.groups.models import (
|
||||||
|
GroupBook,
|
||||||
|
MemberProgress,
|
||||||
|
ReadingGroup,
|
||||||
|
ReadingGroupMembership,
|
||||||
|
ReadingSchedule,
|
||||||
|
Section,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(ReadingGroup)
|
||||||
|
class ReadingGroupAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ["name", "admin", "created_at"]
|
||||||
|
search_fields = ["name", "admin__email"]
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(ReadingGroupMembership)
|
||||||
|
class ReadingGroupMembershipAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ["user", "group", "role", "joined_at"]
|
||||||
|
list_filter = ["role", "group"]
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(GroupBook)
|
||||||
|
class GroupBookAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ["title", "group", "status", "uploaded_by", "created_at"]
|
||||||
|
list_filter = ["status"]
|
||||||
|
search_fields = ["title", "group__name"]
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(Section)
|
||||||
|
class SectionAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ["title", "group_book", "order", "estimated_reading_minutes"]
|
||||||
|
ordering = ["group_book", "order"]
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(ReadingSchedule)
|
||||||
|
class ReadingScheduleAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ["group_book", "meeting_number", "week_date"]
|
||||||
|
ordering = ["group_book", "meeting_number"]
|
||||||
|
|
||||||
|
|
||||||
|
@admin.register(MemberProgress)
|
||||||
|
class MemberProgressAdmin(admin.ModelAdmin):
|
||||||
|
list_display = ["user", "group_book", "current_section", "updated_at"]
|
||||||
@@ -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,154 @@
|
|||||||
|
# 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)),
|
||||||
|
('admin', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='administered_groups', to=settings.AUTH_USER_MODEL)),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'Reading Group',
|
||||||
|
'verbose_name_plural': 'Reading Groups',
|
||||||
|
'db_table': 'groups_reading_group',
|
||||||
|
'ordering': ['-created_at'],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='GroupBook',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('title', models.CharField(db_index=True, max_length=512)),
|
||||||
|
('status', models.CharField(choices=[('active', 'Active'), ('replaced', 'Replaced')], db_index=True, default='active', max_length=16)),
|
||||||
|
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('updated_at', models.DateTimeField(auto_now=True)),
|
||||||
|
('ebook', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='group_books', to='books.ebook')),
|
||||||
|
('uploaded_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='uploaded_group_books', to=settings.AUTH_USER_MODEL)),
|
||||||
|
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='group_books', to='groups.readinggroup')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'Group Book',
|
||||||
|
'verbose_name_plural': 'Group Books',
|
||||||
|
'db_table': 'groups_group_book',
|
||||||
|
'ordering': ['-created_at'],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='ReadingGroupMembership',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('role', models.CharField(choices=[('admin', 'Admin'), ('member', 'Member')], default='member', max_length=16)),
|
||||||
|
('joined_at', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='memberships', to='groups.readinggroup')),
|
||||||
|
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'Reading Group Membership',
|
||||||
|
'verbose_name_plural': 'Reading Group Memberships',
|
||||||
|
'db_table': 'groups_membership',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='readinggroup',
|
||||||
|
name='members',
|
||||||
|
field=models.ManyToManyField(related_name='reading_groups', through='groups.ReadingGroupMembership', to=settings.AUTH_USER_MODEL),
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='ReadingSchedule',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('meeting_number', models.PositiveIntegerField()),
|
||||||
|
('week_date', models.DateField()),
|
||||||
|
('section_ids', models.JSONField(default=list, help_text='Ordered list of Section IDs for this meeting')),
|
||||||
|
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('group_book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='schedules', to='groups.groupbook')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'Reading Schedule',
|
||||||
|
'verbose_name_plural': 'Reading Schedules',
|
||||||
|
'db_table': 'groups_reading_schedule',
|
||||||
|
'ordering': ['meeting_number'],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='Section',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('title', models.CharField(max_length=512)),
|
||||||
|
('order', models.PositiveIntegerField(db_index=True)),
|
||||||
|
('start_chapter_index', models.PositiveIntegerField(default=0)),
|
||||||
|
('end_chapter_index', models.PositiveIntegerField(default=0)),
|
||||||
|
('estimated_reading_minutes', models.PositiveIntegerField(default=0)),
|
||||||
|
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('group_book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sections', to='groups.groupbook')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'Section',
|
||||||
|
'verbose_name_plural': 'Sections',
|
||||||
|
'db_table': 'groups_section',
|
||||||
|
'ordering': ['order'],
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='MemberProgress',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('completed_sections', models.JSONField(default=list, help_text='Ordered list of completed Section IDs')),
|
||||||
|
('updated_at', models.DateTimeField(auto_now=True)),
|
||||||
|
('group_book', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='member_progress', to='groups.groupbook')),
|
||||||
|
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='group_progress', to=settings.AUTH_USER_MODEL)),
|
||||||
|
('current_section', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='current_readers', to='groups.section')),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
'verbose_name': 'Member Progress',
|
||||||
|
'verbose_name_plural': 'Member Progress',
|
||||||
|
'db_table': 'groups_member_progress',
|
||||||
|
},
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name='groupbook',
|
||||||
|
index=models.Index(fields=['group', 'status'], name='groups_grou_group_i_afdbf7_idx'),
|
||||||
|
),
|
||||||
|
migrations.AlterUniqueTogether(
|
||||||
|
name='readinggroupmembership',
|
||||||
|
unique_together={('user', 'group')},
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name='readingschedule',
|
||||||
|
index=models.Index(fields=['group_book', 'meeting_number'], name='groups_read_group_b_2fc416_idx'),
|
||||||
|
),
|
||||||
|
migrations.AlterUniqueTogether(
|
||||||
|
name='readingschedule',
|
||||||
|
unique_together={('group_book', 'meeting_number')},
|
||||||
|
),
|
||||||
|
migrations.AddIndex(
|
||||||
|
model_name='section',
|
||||||
|
index=models.Index(fields=['group_book', 'order'], name='groups_sect_group_b_e2810a_idx'),
|
||||||
|
),
|
||||||
|
migrations.AlterUniqueTogether(
|
||||||
|
name='section',
|
||||||
|
unique_together={('group_book', 'order')},
|
||||||
|
),
|
||||||
|
migrations.AlterUniqueTogether(
|
||||||
|
name='memberprogress',
|
||||||
|
unique_together={('user', 'group_book')},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
from django.conf import settings
|
||||||
|
from django.db import models
|
||||||
|
|
||||||
|
from apps.books.models import EBook
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroup(models.Model):
|
||||||
|
"""A reading group with an admin and members."""
|
||||||
|
|
||||||
|
name = models.CharField(max_length=256, db_index=True)
|
||||||
|
description = models.TextField(blank=True, default="")
|
||||||
|
admin = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
on_delete=models.CASCADE,
|
||||||
|
related_name="administered_groups",
|
||||||
|
)
|
||||||
|
members = models.ManyToManyField(
|
||||||
|
settings.AUTH_USER_MODEL,
|
||||||
|
through="ReadingGroupMembership",
|
||||||
|
related_name="reading_groups",
|
||||||
|
)
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupMembership(models.Model):
|
||||||
|
class Role(models.TextChoices):
|
||||||
|
ADMIN = "admin", "Admin"
|
||||||
|
MEMBER = "member", "Member"
|
||||||
|
|
||||||
|
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||||
|
group = models.ForeignKey(ReadingGroup, on_delete=models.CASCADE, related_name="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"
|
||||||
|
unique_together = [("user", "group")]
|
||||||
|
verbose_name = "Reading Group Membership"
|
||||||
|
verbose_name_plural = "Reading Group Memberships"
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"{self.user} in {self.group.name} ({self.role})"
|
||||||
|
|
||||||
|
|
||||||
|
class GroupBook(models.Model):
|
||||||
|
"""Links an uploaded EBook to a reading group."""
|
||||||
|
|
||||||
|
class Status(models.TextChoices):
|
||||||
|
ACTIVE = "active", "Active"
|
||||||
|
REPLACED = "replaced", "Replaced"
|
||||||
|
|
||||||
|
group = models.ForeignKey(
|
||||||
|
ReadingGroup, on_delete=models.CASCADE, related_name="group_books"
|
||||||
|
)
|
||||||
|
ebook = models.ForeignKey(
|
||||||
|
EBook, on_delete=models.CASCADE, related_name="group_books"
|
||||||
|
)
|
||||||
|
uploaded_by = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="uploaded_group_books"
|
||||||
|
)
|
||||||
|
title = models.CharField(max_length=512, db_index=True)
|
||||||
|
status = models.CharField(
|
||||||
|
max_length=16, choices=Status.choices, default=Status.ACTIVE, db_index=True
|
||||||
|
)
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
updated_at = models.DateTimeField(auto_now=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
db_table = "groups_group_book"
|
||||||
|
verbose_name = "Group Book"
|
||||||
|
verbose_name_plural = "Group Books"
|
||||||
|
ordering = ["-created_at"]
|
||||||
|
indexes = [models.Index(fields=["group", "status"])]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"{self.group.name} — {self.title}"
|
||||||
|
|
||||||
|
|
||||||
|
class Section(models.Model):
|
||||||
|
"""A section/chunk of a GroupBook for group reading."""
|
||||||
|
|
||||||
|
group_book = models.ForeignKey(
|
||||||
|
GroupBook, on_delete=models.CASCADE, related_name="sections"
|
||||||
|
)
|
||||||
|
title = models.CharField(max_length=512)
|
||||||
|
order = models.PositiveIntegerField(db_index=True)
|
||||||
|
start_chapter_index = models.PositiveIntegerField(default=0)
|
||||||
|
end_chapter_index = models.PositiveIntegerField(default=0)
|
||||||
|
estimated_reading_minutes = models.PositiveIntegerField(default=0)
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
db_table = "groups_section"
|
||||||
|
verbose_name = "Section"
|
||||||
|
verbose_name_plural = "Sections"
|
||||||
|
ordering = ["order"]
|
||||||
|
unique_together = [("group_book", "order")]
|
||||||
|
indexes = [models.Index(fields=["group_book", "order"])]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"{self.group_book.title} — Section {self.order}: {self.title}"
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingSchedule(models.Model):
|
||||||
|
"""Reading schedule mapping sections to weekly meetings."""
|
||||||
|
|
||||||
|
group_book = models.ForeignKey(
|
||||||
|
GroupBook, on_delete=models.CASCADE, related_name="schedules"
|
||||||
|
)
|
||||||
|
meeting_number = models.PositiveIntegerField()
|
||||||
|
week_date = models.DateField()
|
||||||
|
section_ids = models.JSONField(default=list, help_text="Ordered list of Section IDs for this meeting")
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
db_table = "groups_reading_schedule"
|
||||||
|
verbose_name = "Reading Schedule"
|
||||||
|
verbose_name_plural = "Reading Schedules"
|
||||||
|
ordering = ["meeting_number"]
|
||||||
|
unique_together = [("group_book", "meeting_number")]
|
||||||
|
indexes = [models.Index(fields=["group_book", "meeting_number"])]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"{self.group_book.title} — Meeting {self.meeting_number}"
|
||||||
|
|
||||||
|
|
||||||
|
class MemberProgress(models.Model):
|
||||||
|
"""Tracks a member's progress through sections of a group book."""
|
||||||
|
|
||||||
|
user = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="group_progress"
|
||||||
|
)
|
||||||
|
group_book = models.ForeignKey(
|
||||||
|
GroupBook, on_delete=models.CASCADE, related_name="member_progress"
|
||||||
|
)
|
||||||
|
current_section = models.ForeignKey(
|
||||||
|
Section, on_delete=models.SET_NULL, null=True, blank=True, related_name="current_readers"
|
||||||
|
)
|
||||||
|
completed_sections = models.JSONField(
|
||||||
|
default=list, help_text="Ordered list of completed Section IDs"
|
||||||
|
)
|
||||||
|
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 = [("user", "group_book")]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return f"{self.user} — {self.group_book.title}"
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from rest_framework import serializers
|
||||||
|
|
||||||
|
from apps.groups.models import (
|
||||||
|
GroupBook,
|
||||||
|
MemberProgress,
|
||||||
|
ReadingGroup,
|
||||||
|
ReadingGroupMembership,
|
||||||
|
ReadingSchedule,
|
||||||
|
Section,
|
||||||
|
)
|
||||||
|
from apps.books.serializers import EBookListSerializer
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupMembershipSerializer(serializers.ModelSerializer):
|
||||||
|
user_email = serializers.CharField(source="user.email", read_only=True)
|
||||||
|
user_username = serializers.CharField(source="user.username", read_only=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = ReadingGroupMembership
|
||||||
|
fields = [
|
||||||
|
"id", "user", "user_email", "user_username",
|
||||||
|
"role", "joined_at",
|
||||||
|
]
|
||||||
|
read_only_fields = ["id", "joined_at"]
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupListSerializer(serializers.ModelSerializer):
|
||||||
|
member_count = serializers.SerializerMethodField()
|
||||||
|
admin_email = serializers.CharField(source="admin.email", read_only=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = ReadingGroup
|
||||||
|
fields = [
|
||||||
|
"id", "name", "description", "admin", "admin_email",
|
||||||
|
"member_count", "created_at", "updated_at",
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_member_count(self, obj: ReadingGroup) -> int:
|
||||||
|
return obj.memberships.count()
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupDetailSerializer(serializers.ModelSerializer):
|
||||||
|
admin_email = serializers.CharField(source="admin.email", read_only=True)
|
||||||
|
members = ReadingGroupMembershipSerializer(source="memberships", many=True, read_only=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = ReadingGroup
|
||||||
|
fields = [
|
||||||
|
"id", "name", "description", "admin", "admin_email",
|
||||||
|
"members", "created_at", "updated_at",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupCreateSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = ReadingGroup
|
||||||
|
fields = ["name", "description"]
|
||||||
|
|
||||||
|
|
||||||
|
class AddMemberSerializer(serializers.Serializer):
|
||||||
|
user_id = serializers.IntegerField()
|
||||||
|
|
||||||
|
def validate_user_id(self, value: int) -> int:
|
||||||
|
from django.conf import settings
|
||||||
|
User = settings.AUTH_USER_MODEL
|
||||||
|
if not User.objects.filter(id=value).exists():
|
||||||
|
raise serializers.ValidationError("User not found.")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class SectionSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Section
|
||||||
|
fields = [
|
||||||
|
"id", "title", "order", "start_chapter_index",
|
||||||
|
"end_chapter_index", "estimated_reading_minutes", "created_at",
|
||||||
|
]
|
||||||
|
read_only_fields = ["id", "created_at"]
|
||||||
|
|
||||||
|
|
||||||
|
class SectionAdjustSerializer(serializers.Serializer):
|
||||||
|
"""Payload for manual section adjustments (merge/split)."""
|
||||||
|
operation = serializers.ChoiceField(choices=["merge", "split"])
|
||||||
|
section_ids = serializers.ListField(
|
||||||
|
child=serializers.IntegerField(), min_length=1,
|
||||||
|
help_text="For merge: list of section IDs to merge. For split: [section_id] to split."
|
||||||
|
)
|
||||||
|
split_at = serializers.IntegerField(
|
||||||
|
required=False, default=2, min_value=2,
|
||||||
|
help_text="Number of new sections when splitting"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingScheduleSerializer(serializers.ModelSerializer):
|
||||||
|
section_details = serializers.SerializerMethodField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = ReadingSchedule
|
||||||
|
fields = [
|
||||||
|
"id", "meeting_number", "week_date", "section_ids",
|
||||||
|
"section_details", "created_at",
|
||||||
|
]
|
||||||
|
read_only_fields = ["id", "created_at"]
|
||||||
|
|
||||||
|
def get_section_details(self, obj: ReadingSchedule) -> list[dict]:
|
||||||
|
sections = Section.objects.filter(
|
||||||
|
id__in=obj.section_ids, group_book=obj.group_book
|
||||||
|
).order_by("order")
|
||||||
|
return SectionSerializer(sections, many=True).data
|
||||||
|
|
||||||
|
|
||||||
|
class MemberProgressSerializer(serializers.ModelSerializer):
|
||||||
|
user_email = serializers.CharField(source="user.email", read_only=True)
|
||||||
|
user_username = serializers.CharField(source="user.username", read_only=True)
|
||||||
|
current_section_title = serializers.SerializerMethodField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = MemberProgress
|
||||||
|
fields = [
|
||||||
|
"id", "user", "user_email", "user_username",
|
||||||
|
"current_section", "current_section_title",
|
||||||
|
"completed_sections", "updated_at",
|
||||||
|
]
|
||||||
|
read_only_fields = ["id", "updated_at"]
|
||||||
|
|
||||||
|
def get_current_section_title(self, obj: MemberProgress) -> str | None:
|
||||||
|
if obj.current_section:
|
||||||
|
return obj.current_section.title
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class GroupBookListSerializer(serializers.ModelSerializer):
|
||||||
|
ebook = EBookListSerializer(read_only=True)
|
||||||
|
uploaded_by_email = serializers.CharField(source="uploaded_by.email", read_only=True)
|
||||||
|
section_count = serializers.SerializerMethodField()
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = GroupBook
|
||||||
|
fields = [
|
||||||
|
"id", "title", "status", "ebook", "uploaded_by",
|
||||||
|
"uploaded_by_email", "section_count", "created_at", "updated_at",
|
||||||
|
]
|
||||||
|
|
||||||
|
def get_section_count(self, obj: GroupBook) -> int:
|
||||||
|
return obj.sections.count()
|
||||||
|
|
||||||
|
|
||||||
|
class GroupBookDetailSerializer(serializers.ModelSerializer):
|
||||||
|
ebook = EBookListSerializer(read_only=True)
|
||||||
|
uploaded_by_email = serializers.CharField(source="uploaded_by.email", read_only=True)
|
||||||
|
sections = SectionSerializer(many=True, read_only=True)
|
||||||
|
schedules = ReadingScheduleSerializer(source="schedules", many=True, read_only=True)
|
||||||
|
|
||||||
|
class Meta:
|
||||||
|
model = GroupBook
|
||||||
|
fields = [
|
||||||
|
"id", "group", "title", "status", "ebook",
|
||||||
|
"uploaded_by", "uploaded_by_email",
|
||||||
|
"sections", "schedules", "created_at", "updated_at",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class GroupBookCreateSerializer(serializers.Serializer):
|
||||||
|
ebook_id = serializers.IntegerField()
|
||||||
|
title = serializers.CharField(max_length=512, required=False)
|
||||||
|
|
||||||
|
def validate_ebook_id(self, value: int) -> int:
|
||||||
|
from apps.books.models import EBook
|
||||||
|
if not EBook.objects.filter(id=value).exists():
|
||||||
|
raise serializers.ValidationError("EBook not found.")
|
||||||
|
# Check format is EPUB
|
||||||
|
ebook = EBook.objects.get(id=value)
|
||||||
|
if ebook.format != "epub":
|
||||||
|
raise serializers.ValidationError("Only EPUB format is supported for group books.")
|
||||||
|
return value
|
||||||
|
|
||||||
|
def validate(self, data: dict) -> dict:
|
||||||
|
request = self.context.get("request")
|
||||||
|
if request and not data.get("title"):
|
||||||
|
from apps.books.models import EBook
|
||||||
|
ebook = EBook.objects.get(id=data["ebook_id"])
|
||||||
|
data["title"] = ebook.title
|
||||||
|
return data
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
"""Automatic section detection and meeting recommendation for group books."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from datetime import date, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.db.models import QuerySet
|
||||||
|
|
||||||
|
from apps.books.models import BookChapter, EBook
|
||||||
|
from apps.groups.models import GroupBook, ReadingSchedule, Section
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
WORDS_PER_MINUTE = 250 # Average reading speed
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_chapter_text(ebook: EBook, chapter: BookChapter) -> str:
|
||||||
|
"""Extract plain text from a chapter for word counting."""
|
||||||
|
try:
|
||||||
|
from ebooklib import epub
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
except ImportError:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
book = epub.read_epub(ebook.file.path)
|
||||||
|
href = chapter.href or ""
|
||||||
|
for item in book.get_items():
|
||||||
|
item_name = item.get_name() or ""
|
||||||
|
if href and (item_name.endswith(href) or href.endswith(item_name)):
|
||||||
|
content = item.get_content()
|
||||||
|
soup = BeautifulSoup(content, "html.parser")
|
||||||
|
body = soup.find("body")
|
||||||
|
if body:
|
||||||
|
return body.get_text(separator=" ", strip=True)
|
||||||
|
return soup.get_text(separator=" ", strip=True)
|
||||||
|
return ""
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Failed to extract text for chapter %s", chapter.id)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _estimate_reading_minutes(text: str) -> int:
|
||||||
|
"""Estimate reading time based on word count at WORDS_PER_MINUTE."""
|
||||||
|
word_count = len(text.split())
|
||||||
|
if word_count == 0:
|
||||||
|
return 1
|
||||||
|
return max(1, round(word_count / WORDS_PER_MINUTE))
|
||||||
|
|
||||||
|
|
||||||
|
def detect_sections(group_book: GroupBook) -> list[dict[str, Any]]:
|
||||||
|
"""Auto-detect sections from a GroupBook's chapters.
|
||||||
|
|
||||||
|
Groups consecutive chapters into logical sections based on TOC structure.
|
||||||
|
Top-level TOC entries become sections; if there are very few (< 3),
|
||||||
|
groups of ~5 chapters become sections instead.
|
||||||
|
"""
|
||||||
|
ebook = group_book.ebook
|
||||||
|
chapters = list(
|
||||||
|
BookChapter.objects.filter(ebook=ebook).order_by("index").select_related("ebook")
|
||||||
|
)
|
||||||
|
|
||||||
|
if not chapters:
|
||||||
|
return []
|
||||||
|
|
||||||
|
top_level = [ch for ch in chapters if not ch.children or len(ch.children) == 0]
|
||||||
|
has_children = [ch for ch in chapters if ch.children and len(ch.children) > 0]
|
||||||
|
|
||||||
|
sections: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
if len(has_children) >= 3:
|
||||||
|
# Use TOC structure: each top-level chapter (with children) is a section
|
||||||
|
for idx, ch in enumerate(has_children):
|
||||||
|
# Find all child chapters belonging to this parent
|
||||||
|
child_indices = _collect_child_indices(chapters, ch, idx)
|
||||||
|
start_idx = ch.index
|
||||||
|
end_idx = child_indices[-1] if child_indices else start_idx
|
||||||
|
|
||||||
|
section_chapters = [c for c in chapters if start_idx <= c.index <= end_idx]
|
||||||
|
total_text = ""
|
||||||
|
for sc in section_chapters:
|
||||||
|
total_text += " " + _fetch_chapter_text(ebook, sc)
|
||||||
|
|
||||||
|
sections.append({
|
||||||
|
"title": ch.title,
|
||||||
|
"order": idx + 1,
|
||||||
|
"start_chapter_index": start_idx,
|
||||||
|
"end_chapter_index": end_idx + 1,
|
||||||
|
"estimated_reading_minutes": _estimate_reading_minutes(total_text),
|
||||||
|
})
|
||||||
|
else:
|
||||||
|
# Group chapters into chunks of ~5
|
||||||
|
chunk_size = max(1, len(top_level) // 6 if len(top_level) > 6 else 5)
|
||||||
|
chunk_size = max(3, min(chunk_size, 10))
|
||||||
|
|
||||||
|
group_start = 0
|
||||||
|
section_order = 1
|
||||||
|
total = len(top_level) or len(chapters)
|
||||||
|
source = top_level or chapters
|
||||||
|
|
||||||
|
while group_start < total:
|
||||||
|
group_end = min(group_start + chunk_size, total)
|
||||||
|
chunk = source[group_start:group_end]
|
||||||
|
|
||||||
|
total_text = ""
|
||||||
|
for ch in chunk:
|
||||||
|
total_text += " " + _fetch_chapter_text(ebook, ch)
|
||||||
|
|
||||||
|
first_title = chunk[0].title if chunk else "Section"
|
||||||
|
last_title = chunk[-1].title if len(chunk) > 1 else ""
|
||||||
|
title = f"{first_title}" if not last_title or first_title == last_title else f"{first_title} — {last_title}"
|
||||||
|
|
||||||
|
sections.append({
|
||||||
|
"title": title,
|
||||||
|
"order": section_order,
|
||||||
|
"start_chapter_index": chunk[0].index,
|
||||||
|
"end_chapter_index": chunk[-1].index + 1,
|
||||||
|
"estimated_reading_minutes": _estimate_reading_minutes(total_text),
|
||||||
|
})
|
||||||
|
group_start = group_end
|
||||||
|
section_order += 1
|
||||||
|
|
||||||
|
return sections
|
||||||
|
|
||||||
|
|
||||||
|
def _collect_child_indices(chapters: list[BookChapter], parent: BookChapter, parent_idx: int) -> list[int]:
|
||||||
|
"""Collect indices of all chapters that are children of the given parent TOC entry."""
|
||||||
|
indices: list[int] = [parent.index]
|
||||||
|
child_hrefs: set[str] = set()
|
||||||
|
for child in parent.children:
|
||||||
|
if isinstance(child, dict):
|
||||||
|
child_hrefs.add(child.get("href", ""))
|
||||||
|
elif hasattr(child, "href"):
|
||||||
|
child_hrefs.add(getattr(child, "href", ""))
|
||||||
|
|
||||||
|
for ch in chapters:
|
||||||
|
if ch.index == parent.index:
|
||||||
|
continue
|
||||||
|
if ch.href in child_hrefs or any(
|
||||||
|
ch.href.endswith(h) or h.endswith(ch.href) for h in child_hrefs
|
||||||
|
):
|
||||||
|
indices.append(ch.index)
|
||||||
|
|
||||||
|
# Also include chapters between this parent and the next parent
|
||||||
|
if parent_idx + 1 < len(chapters):
|
||||||
|
next_parent = chapters[parent_idx + 1]
|
||||||
|
for ch in chapters:
|
||||||
|
if parent.index < ch.index < next_parent.index:
|
||||||
|
indices.append(ch.index)
|
||||||
|
|
||||||
|
return sorted(set(indices))
|
||||||
|
|
||||||
|
|
||||||
|
def apply_sections(group_book: GroupBook) -> list[Section]:
|
||||||
|
"""Detect sections and persist them to the database, replacing existing ones."""
|
||||||
|
Section.objects.filter(group_book=group_book).delete()
|
||||||
|
sections_data = detect_sections(group_book)
|
||||||
|
created: list[Section] = []
|
||||||
|
for data in sections_data:
|
||||||
|
section = Section.objects.create(
|
||||||
|
group_book=group_book,
|
||||||
|
title=data["title"],
|
||||||
|
order=data["order"],
|
||||||
|
start_chapter_index=data["start_chapter_index"],
|
||||||
|
end_chapter_index=data["end_chapter_index"],
|
||||||
|
estimated_reading_minutes=data["estimated_reading_minutes"],
|
||||||
|
)
|
||||||
|
created.append(section)
|
||||||
|
return created
|
||||||
|
|
||||||
|
|
||||||
|
def recommend_meetings(group_book: GroupBook, num_meetings: int = 4) -> list[dict[str, Any]]:
|
||||||
|
"""Recommend which sections to assign to each weekly meeting.
|
||||||
|
|
||||||
|
Distributes sections across meetings, trying to balance total reading time.
|
||||||
|
Returns a list of meeting assignments ready for schedule creation.
|
||||||
|
"""
|
||||||
|
sections = list(
|
||||||
|
Section.objects.filter(group_book=group_book).order_by("order")
|
||||||
|
)
|
||||||
|
|
||||||
|
if not sections:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Calculate total minutes to distribute
|
||||||
|
total_minutes = sum(s.estimated_reading_minutes for s in sections)
|
||||||
|
target_per_meeting = total_minutes / num_meetings
|
||||||
|
|
||||||
|
meetings: list[dict[str, Any]] = []
|
||||||
|
current_meeting: list[int] = []
|
||||||
|
current_minutes = 0
|
||||||
|
|
||||||
|
for section in sections:
|
||||||
|
if current_meeting and current_minutes + section.estimated_reading_minutes > target_per_meeting * 1.4:
|
||||||
|
# Start new meeting if adding this section would overshoot too much
|
||||||
|
if len(meetings) < num_meetings - 1:
|
||||||
|
meetings.append({
|
||||||
|
"meeting_number": len(meetings) + 1,
|
||||||
|
"section_ids": current_meeting,
|
||||||
|
"total_minutes": current_minutes,
|
||||||
|
})
|
||||||
|
current_meeting = []
|
||||||
|
current_minutes = 0
|
||||||
|
|
||||||
|
current_meeting.append(section.id)
|
||||||
|
current_minutes += section.estimated_reading_minutes
|
||||||
|
|
||||||
|
# Add the last meeting
|
||||||
|
if current_meeting:
|
||||||
|
meetings.append({
|
||||||
|
"meeting_number": len(meetings) + 1,
|
||||||
|
"section_ids": current_meeting,
|
||||||
|
"total_minutes": current_minutes,
|
||||||
|
})
|
||||||
|
|
||||||
|
# If we have fewer than num_meetings, we could split the largest one
|
||||||
|
# For now, just return what we have
|
||||||
|
return meetings
|
||||||
|
|
||||||
|
|
||||||
|
def apply_schedule(group_book: GroupBook, num_meetings: int = 4) -> list[ReadingSchedule]:
|
||||||
|
"""Generate and persist a reading schedule."""
|
||||||
|
ReadingSchedule.objects.filter(group_book=group_book).delete()
|
||||||
|
|
||||||
|
recommendations = recommend_meetings(group_book, num_meetings)
|
||||||
|
today = date.today()
|
||||||
|
|
||||||
|
created: list[ReadingSchedule] = []
|
||||||
|
for rec in recommendations:
|
||||||
|
week_date = today + timedelta(weeks=rec["meeting_number"] - 1)
|
||||||
|
schedule = ReadingSchedule.objects.create(
|
||||||
|
group_book=group_book,
|
||||||
|
meeting_number=rec["meeting_number"],
|
||||||
|
week_date=week_date,
|
||||||
|
section_ids=rec["section_ids"],
|
||||||
|
)
|
||||||
|
created.append(schedule)
|
||||||
|
|
||||||
|
return created
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
from django.urls import include, path
|
||||||
|
from rest_framework.routers import DefaultRouter
|
||||||
|
|
||||||
|
from apps.groups.views import GroupBookViewSet, ReadingGroupViewSet
|
||||||
|
|
||||||
|
# ReadingGroup routes (standard ViewSet)
|
||||||
|
router = DefaultRouter()
|
||||||
|
router.register(r"", ReadingGroupViewSet, basename="group")
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path("", include(router.urls)),
|
||||||
|
# Nested GroupBook routes under a group
|
||||||
|
path(
|
||||||
|
"<int:group_pk>/books/",
|
||||||
|
GroupBookViewSet.as_view({"get": "list", "post": "create"}),
|
||||||
|
name="group-book-list",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"<int:group_pk>/books/<int:pk>/",
|
||||||
|
GroupBookViewSet.as_view({"get": "retrieve", "delete": "destroy"}),
|
||||||
|
name="group-book-detail",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"<int:group_pk>/books/<int:pk>/detect-sections/",
|
||||||
|
GroupBookViewSet.as_view({"post": "detect_sections_action"}),
|
||||||
|
name="group-book-detect-sections",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"<int:group_pk>/books/<int:pk>/adjust-sections/",
|
||||||
|
GroupBookViewSet.as_view({"post": "adjust_sections"}),
|
||||||
|
name="group-book-adjust-sections",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"<int:group_pk>/books/<int:pk>/schedule/",
|
||||||
|
GroupBookViewSet.as_view({"get": "schedule", "post": "schedule", "delete": "schedule"}),
|
||||||
|
name="group-book-schedule",
|
||||||
|
),
|
||||||
|
path(
|
||||||
|
"<int:group_pk>/books/<int:pk>/progress/",
|
||||||
|
GroupBookViewSet.as_view({"get": "progress", "patch": "progress"}),
|
||||||
|
name="group-book-progress",
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,349 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from django.db.models import QuerySet
|
||||||
|
from django.shortcuts import get_object_or_404
|
||||||
|
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.books.models import EBook
|
||||||
|
from apps.groups.models import (
|
||||||
|
GroupBook,
|
||||||
|
MemberProgress,
|
||||||
|
ReadingGroup,
|
||||||
|
ReadingGroupMembership,
|
||||||
|
ReadingSchedule,
|
||||||
|
Section,
|
||||||
|
)
|
||||||
|
from apps.groups.serializers import (
|
||||||
|
AddMemberSerializer,
|
||||||
|
GroupBookCreateSerializer,
|
||||||
|
GroupBookDetailSerializer,
|
||||||
|
GroupBookListSerializer,
|
||||||
|
MemberProgressSerializer,
|
||||||
|
ReadingGroupCreateSerializer,
|
||||||
|
ReadingGroupDetailSerializer,
|
||||||
|
ReadingGroupListSerializer,
|
||||||
|
ReadingScheduleSerializer,
|
||||||
|
SectionAdjustSerializer,
|
||||||
|
SectionSerializer,
|
||||||
|
)
|
||||||
|
from apps.groups.services.section_splitting import (
|
||||||
|
apply_schedule,
|
||||||
|
apply_sections,
|
||||||
|
detect_sections,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class IsGroupAdmin(permissions.BasePermission):
|
||||||
|
"""Only the group admin can modify group resources."""
|
||||||
|
|
||||||
|
def has_permission(self, request: Request, view: object) -> bool:
|
||||||
|
if not request.user.is_authenticated:
|
||||||
|
return False
|
||||||
|
if view.action in ("list", "retrieve"):
|
||||||
|
return True
|
||||||
|
group_id = view.kwargs.get("pk") or view.kwargs.get("group_pk")
|
||||||
|
if group_id:
|
||||||
|
return ReadingGroup.objects.filter(id=group_id, admin=request.user).exists()
|
||||||
|
return True
|
||||||
|
|
||||||
|
def has_object_permission(self, request: Request, view: object, obj: ReadingGroup) -> bool:
|
||||||
|
if request.method in permissions.SAFE_METHODS:
|
||||||
|
return True
|
||||||
|
return obj.admin == request.user
|
||||||
|
|
||||||
|
|
||||||
|
class IsGroupMember(permissions.BasePermission):
|
||||||
|
"""Only group members (including admin) can view group content."""
|
||||||
|
|
||||||
|
def has_permission(self, request: Request, view: object) -> bool:
|
||||||
|
if not request.user.is_authenticated:
|
||||||
|
return False
|
||||||
|
group_id = view.kwargs.get("pk") or view.kwargs.get("group_pk")
|
||||||
|
if group_id:
|
||||||
|
return ReadingGroupMembership.objects.filter(
|
||||||
|
group_id=group_id, user=request.user
|
||||||
|
).exists()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
class ReadingGroupViewSet(viewsets.ModelViewSet):
|
||||||
|
permission_classes = [permissions.IsAuthenticated, IsGroupAdmin]
|
||||||
|
queryset = ReadingGroup.objects.prefetch_related("memberships__user")
|
||||||
|
|
||||||
|
def get_serializer_class(self):
|
||||||
|
if self.action == "create":
|
||||||
|
return ReadingGroupCreateSerializer
|
||||||
|
if self.action == "retrieve":
|
||||||
|
return ReadingGroupDetailSerializer
|
||||||
|
return ReadingGroupListSerializer
|
||||||
|
|
||||||
|
def get_queryset(self) -> QuerySet[ReadingGroup]:
|
||||||
|
user = self.request.user
|
||||||
|
return ReadingGroup.objects.filter(
|
||||||
|
memberships__user=user
|
||||||
|
).prefetch_related("memberships__user").distinct()
|
||||||
|
|
||||||
|
def perform_create(self, serializer: ReadingGroupCreateSerializer) -> ReadingGroup:
|
||||||
|
group = serializer.save(admin=self.request.user)
|
||||||
|
ReadingGroupMembership.objects.create(
|
||||||
|
user=self.request.user, group=group, role=ReadingGroupMembership.Role.ADMIN
|
||||||
|
)
|
||||||
|
return group
|
||||||
|
|
||||||
|
@action(detail=True, methods=["post"], permission_classes=[IsGroupAdmin])
|
||||||
|
def add_member(self, request: Request, pk: int | None = None) -> Response:
|
||||||
|
group = self.get_object()
|
||||||
|
member_serializer = AddMemberSerializer(data=request.data)
|
||||||
|
member_serializer.is_valid(raise_exception=True)
|
||||||
|
|
||||||
|
user_id = member_serializer.validated_data["user_id"]
|
||||||
|
from django.conf import settings
|
||||||
|
User = settings.AUTH_USER_MODEL
|
||||||
|
new_member = get_object_or_404(User, id=user_id)
|
||||||
|
|
||||||
|
if ReadingGroupMembership.objects.filter(group=group, user=new_member).exists():
|
||||||
|
return Response(
|
||||||
|
{"detail": "User is already a member of this group."},
|
||||||
|
status=status.HTTP_409_CONFLICT,
|
||||||
|
)
|
||||||
|
|
||||||
|
membership = ReadingGroupMembership.objects.create(
|
||||||
|
user=new_member, group=group, role=ReadingGroupMembership.Role.MEMBER
|
||||||
|
)
|
||||||
|
from apps.groups.serializers import ReadingGroupMembershipSerializer
|
||||||
|
return Response(
|
||||||
|
ReadingGroupMembershipSerializer(membership).data,
|
||||||
|
status=status.HTTP_201_CREATED,
|
||||||
|
)
|
||||||
|
|
||||||
|
@action(detail=True, methods=["post"], permission_classes=[IsGroupAdmin])
|
||||||
|
def remove_member(self, request: Request, pk: int | None = None) -> Response:
|
||||||
|
group = self.get_object()
|
||||||
|
member_serializer = AddMemberSerializer(data=request.data)
|
||||||
|
member_serializer.is_valid(raise_exception=True)
|
||||||
|
|
||||||
|
user_id = member_serializer.validated_data["user_id"]
|
||||||
|
if user_id == group.admin_id:
|
||||||
|
return Response(
|
||||||
|
{"detail": "Cannot remove the group admin."},
|
||||||
|
status=status.HTTP_400_BAD_REQUEST,
|
||||||
|
)
|
||||||
|
|
||||||
|
deleted, _ = ReadingGroupMembership.objects.filter(
|
||||||
|
group=group, user_id=user_id
|
||||||
|
).delete()
|
||||||
|
if not deleted:
|
||||||
|
return Response(
|
||||||
|
{"detail": "User is not a member of this group."},
|
||||||
|
status=status.HTTP_404_NOT_FOUND,
|
||||||
|
)
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
|
||||||
|
class GroupBookViewSet(viewsets.ModelViewSet):
|
||||||
|
permission_classes = [permissions.IsAuthenticated, IsGroupAdmin]
|
||||||
|
|
||||||
|
def get_serializer_class(self):
|
||||||
|
if self.action == "create":
|
||||||
|
return GroupBookCreateSerializer
|
||||||
|
if self.action == "retrieve":
|
||||||
|
return GroupBookDetailSerializer
|
||||||
|
return GroupBookListSerializer
|
||||||
|
|
||||||
|
def get_queryset(self) -> QuerySet[GroupBook]:
|
||||||
|
group_id = self.kwargs.get("group_pk")
|
||||||
|
return GroupBook.objects.filter(
|
||||||
|
group_id=group_id
|
||||||
|
).select_related("ebook", "ebook__user", "uploaded_by").prefetch_related(
|
||||||
|
"sections", "schedules"
|
||||||
|
)
|
||||||
|
|
||||||
|
def perform_create(self, serializer: GroupBookCreateSerializer) -> GroupBook:
|
||||||
|
group = get_object_or_404(ReadingGroup, id=self.kwargs["group_pk"])
|
||||||
|
ebook = get_object_or_404(EBook, id=serializer.validated_data["ebook_id"])
|
||||||
|
title = serializer.validated_data.get("title") or ebook.title
|
||||||
|
|
||||||
|
# Mark existing active books as replaced
|
||||||
|
GroupBook.objects.filter(group=group, status=GroupBook.Status.ACTIVE).update(
|
||||||
|
status=GroupBook.Status.REPLACED
|
||||||
|
)
|
||||||
|
|
||||||
|
group_book = GroupBook.objects.create(
|
||||||
|
group=group,
|
||||||
|
ebook=ebook,
|
||||||
|
uploaded_by=self.request.user,
|
||||||
|
title=title,
|
||||||
|
status=GroupBook.Status.ACTIVE,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Auto-detect sections
|
||||||
|
try:
|
||||||
|
apply_sections(group_book)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Auto-section detection failed for group_book %s", group_book.id)
|
||||||
|
|
||||||
|
# Auto-generate schedule
|
||||||
|
try:
|
||||||
|
apply_schedule(group_book)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Schedule generation failed for group_book %s", group_book.id)
|
||||||
|
|
||||||
|
return group_book
|
||||||
|
|
||||||
|
@action(detail=True, methods=["post"], url_path="detect-sections")
|
||||||
|
def detect_sections_action(self, request: Request, group_pk: int | None = None, pk: int | None = None) -> Response:
|
||||||
|
group_book = self.get_object()
|
||||||
|
try:
|
||||||
|
sections = apply_sections(group_book)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Section detection failed for group_book %s", group_book.id)
|
||||||
|
return Response({"error": str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||||
|
return Response(SectionSerializer(sections, many=True).data)
|
||||||
|
|
||||||
|
@action(detail=True, methods=["post"], url_path="adjust-sections")
|
||||||
|
def adjust_sections(self, request: Request, group_pk: int | None = None, pk: int | None = None) -> Response:
|
||||||
|
group_book = self.get_object()
|
||||||
|
adjust_serializer = SectionAdjustSerializer(data=request.data)
|
||||||
|
adjust_serializer.is_valid(raise_exception=True)
|
||||||
|
|
||||||
|
operation = adjust_serializer.validated_data["operation"]
|
||||||
|
section_ids: list[int] = adjust_serializer.validated_data["section_ids"]
|
||||||
|
|
||||||
|
if operation == "merge":
|
||||||
|
if len(section_ids) < 2:
|
||||||
|
return Response(
|
||||||
|
{"error": "At least 2 section IDs required for merge."},
|
||||||
|
status=status.HTTP_400_BAD_REQUEST,
|
||||||
|
)
|
||||||
|
sections = list(
|
||||||
|
Section.objects.filter(id__in=section_ids, group_book=group_book).order_by("order")
|
||||||
|
)
|
||||||
|
if len(sections) < 2:
|
||||||
|
return Response(
|
||||||
|
{"error": "Not enough valid sections found."},
|
||||||
|
status=status.HTTP_400_BAD_REQUEST,
|
||||||
|
)
|
||||||
|
merged_title = " — ".join(s.title for s in sections)
|
||||||
|
merged_minutes = sum(s.estimated_reading_minutes for s in sections)
|
||||||
|
merged_start = sections[0].start_chapter_index
|
||||||
|
merged_end = sections[-1].end_chapter_index
|
||||||
|
merged_order = sections[0].order
|
||||||
|
|
||||||
|
# Delete old sections
|
||||||
|
Section.objects.filter(id__in=section_ids, group_book=group_book).delete()
|
||||||
|
|
||||||
|
# Create merged section
|
||||||
|
merged = Section.objects.create(
|
||||||
|
group_book=group_book,
|
||||||
|
title=merged_title,
|
||||||
|
order=merged_order,
|
||||||
|
start_chapter_index=merged_start,
|
||||||
|
end_chapter_index=merged_end,
|
||||||
|
estimated_reading_minutes=merged_minutes,
|
||||||
|
)
|
||||||
|
# Reorder remaining sections
|
||||||
|
_renumber_sections(group_book)
|
||||||
|
return Response(SectionSerializer(merged).data)
|
||||||
|
|
||||||
|
if operation == "split":
|
||||||
|
if len(section_ids) != 1:
|
||||||
|
return Response(
|
||||||
|
{"error": "Exactly 1 section ID required for split."},
|
||||||
|
status=status.HTTP_400_BAD_REQUEST,
|
||||||
|
)
|
||||||
|
split_at = adjust_serializer.validated_data.get("split_at", 2)
|
||||||
|
section = get_object_or_404(Section, id=section_ids[0], group_book=group_book)
|
||||||
|
chapters = section.end_chapter_index - section.start_chapter_index
|
||||||
|
if chapters < split_at:
|
||||||
|
return Response(
|
||||||
|
{"error": f"Section only has {chapters} chapters, cannot split into {split_at}."},
|
||||||
|
status=status.HTTP_400_BAD_REQUEST,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Delete original
|
||||||
|
orig_order = section.order
|
||||||
|
orig_title = section.title
|
||||||
|
section.delete()
|
||||||
|
|
||||||
|
# Create split sections
|
||||||
|
chunk_size = max(1, chapters // split_at)
|
||||||
|
new_sections: list[Section] = []
|
||||||
|
for i in range(split_at):
|
||||||
|
start_idx = section.start_chapter_index + i * chunk_size
|
||||||
|
end_idx = start_idx + chunk_size if i < split_at - 1 else section.end_chapter_index
|
||||||
|
minutes_each = max(1, section.estimated_reading_minutes // split_at)
|
||||||
|
new_sec = Section.objects.create(
|
||||||
|
group_book=group_book,
|
||||||
|
title=f"{orig_title} (Part {i + 1})",
|
||||||
|
order=orig_order + i,
|
||||||
|
start_chapter_index=start_idx,
|
||||||
|
end_chapter_index=end_idx,
|
||||||
|
estimated_reading_minutes=minutes_each,
|
||||||
|
)
|
||||||
|
new_sections.append(new_sec)
|
||||||
|
|
||||||
|
_renumber_sections(group_book)
|
||||||
|
return Response(SectionSerializer(new_sections, many=True).data)
|
||||||
|
|
||||||
|
return Response({"error": "Invalid operation."}, status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
@action(detail=True, methods=["get", "post", "delete"], url_path="schedule")
|
||||||
|
def schedule(self, request: Request, group_pk: int | None = None, pk: int | None = None) -> Response:
|
||||||
|
group_book = self.get_object()
|
||||||
|
|
||||||
|
if request.method == "GET":
|
||||||
|
schedules = ReadingSchedule.objects.filter(group_book=group_book).order_by("meeting_number")
|
||||||
|
return Response(ReadingScheduleSerializer(schedules, many=True).data)
|
||||||
|
|
||||||
|
if request.method == "POST":
|
||||||
|
ReadingSchedule.objects.filter(group_book=group_book).delete()
|
||||||
|
num_meetings = int(request.data.get("num_meetings", 4))
|
||||||
|
try:
|
||||||
|
schedules = apply_schedule(group_book, num_meetings=num_meetings)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Schedule generation failed for group_book %s", group_book.id)
|
||||||
|
return Response({"error": str(exc)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
||||||
|
return Response(
|
||||||
|
ReadingScheduleSerializer(schedules, many=True).data,
|
||||||
|
status=status.HTTP_201_CREATED,
|
||||||
|
)
|
||||||
|
|
||||||
|
if request.method == "DELETE":
|
||||||
|
ReadingSchedule.objects.filter(group_book=group_book).delete()
|
||||||
|
return Response(status=status.HTTP_204_NO_CONTENT)
|
||||||
|
|
||||||
|
@action(detail=True, methods=["get", "patch"], url_path="progress")
|
||||||
|
def progress(self, request: Request, group_pk: int | None = None, pk: int | None = None) -> Response:
|
||||||
|
group_book = self.get_object()
|
||||||
|
|
||||||
|
if request.method == "GET":
|
||||||
|
progress_records = MemberProgress.objects.filter(
|
||||||
|
group_book=group_book
|
||||||
|
).select_related("user", "current_section")
|
||||||
|
return Response(MemberProgressSerializer(progress_records, many=True).data)
|
||||||
|
|
||||||
|
# PATCH: update own progress
|
||||||
|
progress_obj, _created = MemberProgress.objects.get_or_create(
|
||||||
|
user=request.user, group_book=group_book,
|
||||||
|
)
|
||||||
|
serializer = MemberProgressSerializer(progress_obj, data=request.data, partial=True)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
serializer.save()
|
||||||
|
return Response(serializer.data)
|
||||||
|
|
||||||
|
|
||||||
|
def _renumber_sections(group_book: GroupBook) -> None:
|
||||||
|
"""Re-number sections sequentially by their current order."""
|
||||||
|
sections = list(Section.objects.filter(group_book=group_book).order_by("order"))
|
||||||
|
for idx, section in enumerate(sections):
|
||||||
|
if section.order != idx + 1:
|
||||||
|
section.order = idx + 1
|
||||||
|
section.save(update_fields=["order"])
|
||||||
@@ -39,6 +39,7 @@ INSTALLED_APPS = [
|
|||||||
# Local apps
|
# Local apps
|
||||||
"apps.users",
|
"apps.users",
|
||||||
"apps.books",
|
"apps.books",
|
||||||
|
"apps.groups",
|
||||||
"apps.annotations",
|
"apps.annotations",
|
||||||
"apps.reader",
|
"apps.reader",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ urlpatterns = [
|
|||||||
path("admin/", admin.site.urls),
|
path("admin/", admin.site.urls),
|
||||||
path("api/auth/", include("apps.users.urls")),
|
path("api/auth/", include("apps.users.urls")),
|
||||||
path("api/books/", include("apps.books.urls")),
|
path("api/books/", include("apps.books.urls")),
|
||||||
|
path("api/groups/", include("apps.groups.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")),
|
||||||
]
|
]
|
||||||
|
|||||||
Binary file not shown.
|
Before Width: | Height: | Size: 24 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 29 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 66 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1 +0,0 @@
|
|||||||
x
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
fake
|
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# 010 — Mobile EPUB Reader
|
||||||
|
|
||||||
|
**Status:** Implemented
|
||||||
|
**Created:** 2026-06-04
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Mirror the web reading experience (`frontend/src/pages/ReadingPage.tsx` and
|
||||||
|
`frontend/src/components/reader/*`) inside the Expo app so users can open their
|
||||||
|
uploaded library, read EPUBs with persisted progress and typography settings,
|
||||||
|
and manage bookmarks/highlights — reusing the same Django REST API as the web
|
||||||
|
client.
|
||||||
|
|
||||||
|
The web EPUB renderer (`react-reader` / epub.js) is DOM-only, so mobile renders
|
||||||
|
EPUBs with `@epubjs-react-native/core`, which runs epub.js inside a
|
||||||
|
`react-native-webview`. This keeps behavior (CFI locations, themes, font
|
||||||
|
controls, TOC, annotations) close to web while staying inside the managed Expo
|
||||||
|
workflow.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
### Mirrored from web
|
||||||
|
|
||||||
|
- EPUB rendering with swipe pagination (`flow: "paginated"`).
|
||||||
|
- Resume position and debounced progress save (CFI + percentage).
|
||||||
|
- Table of contents drawer with jump-to-chapter.
|
||||||
|
- Reading settings: theme presets (light/sepia/paper/dark), font family, font
|
||||||
|
size, line spacing — persisted to `/api/reader/settings/`.
|
||||||
|
- Bookmarks: bookmark the current page, list/jump/delete, and create highlights
|
||||||
|
from a text selection. Highlights are re-applied on open (best-effort).
|
||||||
|
|
||||||
|
### Deferred (not in this pass)
|
||||||
|
|
||||||
|
- PDF reading. PDF books show a placeholder pointing to the web reader.
|
||||||
|
- Brightness and orientation-lock controls.
|
||||||
|
- Per-highlight color picker (highlights use a single default color).
|
||||||
|
- App-wide internationalization (web uses `react-i18n-lite`).
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
LibraryScreen (EBook list)
|
||||||
|
| navigate("BookDetail", { ebookId })
|
||||||
|
v
|
||||||
|
BookDetailScreen ----------------> ReaderScreen ({ ebookId })
|
||||||
|
|
|
||||||
|
GET /api/books/ebooks/:id/ (format guard)
|
||||||
|
|
|
||||||
|
epub? --------------------- pdf? -> placeholder
|
||||||
|
|
|
||||||
|
EpubReaderView (ReaderProvider)
|
||||||
|
|
|
||||||
|
expo-file-system downloadAsync(file/, Bearer token) -> file:// uri
|
||||||
|
|
|
||||||
|
<Reader src=file:// fileSystem=useFileSystem flow="paginated" />
|
||||||
|
|
|
||||||
|
onLocationChange -> debounce 800ms -> PATCH progress/
|
||||||
|
onSelected -> POST bookmarks/ (+ highlight annotation)
|
||||||
|
useReader().toc -> goToLocation(href)
|
||||||
|
settings change -> changeTheme / changeFontSize / changeFontFamily
|
||||||
|
+ PATCH /api/reader/settings/ (debounced)
|
||||||
|
```
|
||||||
|
|
||||||
|
The ebook file is downloaded to the app cache with an `Authorization` header
|
||||||
|
(the `/file/` endpoint is JWT-protected) and the local `file://` URI is handed
|
||||||
|
to the renderer — mirroring how the web client downloads a blob rather than
|
||||||
|
using a public/signed URL.
|
||||||
|
|
||||||
|
## Mobile changes
|
||||||
|
|
||||||
|
| File | Role |
|
||||||
|
|------|------|
|
||||||
|
| `mobile/src/api/client.ts` | Adds `apiClient`, `saveTokens`, `loadTokens`, `getApiBaseUrl` |
|
||||||
|
| `mobile/src/api/ebooks.ts` | `/api/books/ebooks/` list/detail/toc + `getFileUrl(id)` |
|
||||||
|
| `mobile/src/api/reader.ts` | Reader settings + per-book progress (mirrors web `api/reader.ts`) |
|
||||||
|
| `mobile/src/api/annotations.ts` | Bookmarks CRUD against `/api/annotations/bookmarks/` |
|
||||||
|
| `mobile/src/types/reader.ts` | `ReadingSettings`, `ReadingProgress` (full reader shapes) |
|
||||||
|
| `mobile/src/types/index.ts` | `AppStackParamList`, `Bookmark`, `CreateMarkerPayload` |
|
||||||
|
| `mobile/src/hooks/useReadingSettings.ts` | Loads + debounced-saves reader settings |
|
||||||
|
| `mobile/src/utils/epubTheme.ts` | Font stacks, theme palettes, `buildEpubTheme()` |
|
||||||
|
| `mobile/src/navigation/AppStack.tsx` | Native stack: Tabs / BookDetail / Reader |
|
||||||
|
| `mobile/src/screens/LibraryScreen.tsx` | Lists user EBooks (`ebooksApi.list`) |
|
||||||
|
| `mobile/src/screens/BookDetailScreen.tsx` | Metadata + start/resume button |
|
||||||
|
| `mobile/src/screens/ReaderScreen.tsx` | Format guard: EPUB view vs PDF placeholder |
|
||||||
|
| `mobile/src/components/reader/EpubReaderView.tsx` | Reader, progress, bookmarks, settings wiring |
|
||||||
|
| `mobile/src/components/reader/ReaderToolbar.tsx` | Title, chapter, progress bar, action buttons |
|
||||||
|
| `mobile/src/components/reader/TocModal.tsx` | Table of contents sheet |
|
||||||
|
| `mobile/src/components/reader/ReadingSettingsModal.tsx` | Theme/font/size/spacing controls |
|
||||||
|
| `mobile/src/components/reader/BookmarksModal.tsx` | Bookmarks & highlights list |
|
||||||
|
| `mobile/App.tsx` | Wraps the tree in `GestureHandlerRootView` |
|
||||||
|
|
||||||
|
Removed unused scaffolding: `mobile/src/navigation/AppNavigator.tsx`,
|
||||||
|
`mobile/src/navigation/MainTabs.tsx`.
|
||||||
|
|
||||||
|
## API contracts (consumed)
|
||||||
|
|
||||||
|
| Method | Path | Purpose |
|
||||||
|
|--------|------|---------|
|
||||||
|
| GET | `/api/books/ebooks/` | User library list |
|
||||||
|
| GET | `/api/books/ebooks/:id/` | EBook detail (format, progress, cover) |
|
||||||
|
| GET | `/api/books/ebooks/:id/file/` | Stream EPUB bytes (JWT, owner) |
|
||||||
|
| GET/PATCH | `/api/books/ebooks/:id/progress/` | Reading progress (`current_position`, `last_page`, `epub_location`) |
|
||||||
|
| GET/PATCH | `/api/reader/settings/` | Reader typography/theme settings |
|
||||||
|
| GET/POST/DELETE | `/api/annotations/bookmarks/` | Bookmarks & highlights (`ebook`, `epub_cfi`, `chapter_index`, ...) |
|
||||||
|
|
||||||
|
## Settings mapping (web -> mobile)
|
||||||
|
|
||||||
|
| Reader setting | Web (epub.js) | Mobile (`@epubjs-react-native/core`) |
|
||||||
|
|----------------|---------------|--------------------------------------|
|
||||||
|
| `theme` / colors | `themes.register/select` | `changeTheme(buildEpubTheme())` + `defaultTheme` |
|
||||||
|
| `font_size` | `themes.fontSize` | `changeFontSize("Npx")` |
|
||||||
|
| `font_family` | body font-family | `changeFontFamily(stack)` |
|
||||||
|
| `line_height` | body line-height | `buildEpubTheme()` CSS rule |
|
||||||
|
| `margin_width` | gap-based padding | not applied (deferred) |
|
||||||
|
| `brightness` / `orientation_lock` | applied on web | deferred |
|
||||||
|
|
||||||
|
## Dependencies added
|
||||||
|
|
||||||
|
- `@epubjs-react-native/core@1.4.7`
|
||||||
|
- `@epubjs-react-native/expo-file-system@1.1.4`
|
||||||
|
- `react-native-webview@13.12.5`
|
||||||
|
|
||||||
|
(`react-native-gesture-handler`, `react-native-reanimated`, and
|
||||||
|
`expo-file-system` were already present.)
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
| Env var | Purpose |
|
||||||
|
|---------|---------|
|
||||||
|
| `EXPO_PUBLIC_API_URL` | Backend base URL (e.g. `http://10.0.2.2:8000` on Android emulator, LAN IP on a device) |
|
||||||
|
|
||||||
|
## Compatibility notes
|
||||||
|
|
||||||
|
- The Expo file-system adapter (`@epubjs-react-native/expo-file-system`) depends
|
||||||
|
only on `expo-file-system`, so the reader runs in Expo Go. (The library's
|
||||||
|
bare adapter pulls native `@dr.pogodin/react-native-fs`; that path is not
|
||||||
|
used here.)
|
||||||
|
- React 19 / Expo SDK 52 may surface peer-dependency warnings for the
|
||||||
|
`@epubjs-react-native/*` packages.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
- [ ] Log in; Library lists the user's uploaded EBooks with covers/progress.
|
||||||
|
- [ ] Open an EPUB; it renders and paginates by swipe.
|
||||||
|
- [ ] Reopen a book; it resumes at the last position.
|
||||||
|
- [ ] Change theme/font/size/spacing; the page updates and persists across reopen.
|
||||||
|
- [ ] Open the TOC and jump to a chapter.
|
||||||
|
- [ ] Bookmark the current page; it appears in the bookmarks list and can be re-opened/deleted.
|
||||||
|
- [ ] Select text to create a highlight; it persists and re-renders on reopen.
|
||||||
|
- [ ] Open a PDF book; the placeholder is shown instead of a crash.
|
||||||
@@ -1 +0,0 @@
|
|||||||
import{X as c,j as e}from"./index-BQiEVoRj.js";function h({bookTitle:s,chapterTitle:l,progress:a,onBack:t,onToggleToc:n,onToggleSettings:o,onToggleMarkers:i}){const{t:r}=c(),d=(a==null?void 0:a.percentage)??0;return e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"reader-top-bar",children:[t?e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:t,"aria-label":r("reader.backToLibraryAria"),children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M20 12H4M10 18l-6-6 6-6"})})}):e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:n,"aria-label":r("reader.tocAria"),children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),e.jsxs("div",{className:"reader-bar-title",children:[e.jsx("span",{className:"reader-bar-book",children:s}),e.jsx("span",{className:"reader-bar-chapter",children:l})]}),e.jsxs("div",{className:"reader-bar-actions",children:[t&&e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:n,"aria-label":r("reader.tocAria"),children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"3",y1:"6",x2:"21",y2:"6"}),e.jsx("line",{x1:"3",y1:"12",x2:"21",y2:"12"}),e.jsx("line",{x1:"3",y1:"18",x2:"21",y2:"18"})]})}),i&&e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:i,"aria-label":r("annotations.inBookPanel"),children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})}),e.jsx("button",{type:"button",className:"reader-bar-btn",onClick:o,"aria-label":r("reader.settingsAria"),children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"})]})})]})]}),e.jsx("div",{className:"reader-progress-bar",children:e.jsx("div",{className:"reader-progress-fill",style:{width:`${Math.min(d,100)}%`}})})]})}export{h as default};
|
|
||||||
File diff suppressed because one or more lines are too long
@@ -1 +0,0 @@
|
|||||||
import{X as m,j as e}from"./index-BQiEVoRj.js";const g=[{value:"sepia",labelKey:"reader.themeSepia"},{value:"dark",labelKey:"reader.themeDark"},{value:"light",labelKey:"reader.themeLight"},{value:"paper",labelKey:"reader.themePaper"}],u=[{value:"sans-serif",labelKey:"reader.fontSans"},{value:"serif",labelKey:"reader.fontSerif"},{value:"monospace",labelKey:"reader.fontMonospace"}],x=[{value:"auto",labelKey:"reader.orientationAuto"},{value:"portrait",labelKey:"reader.orientationPortrait"},{value:"landscape",labelKey:"reader.orientationLandscape"}];function v({settings:t,isOpen:c,onClose:d,onUpdate:o,onFlush:h}){const{t:s}=m(),n=()=>{h(),d()},i=(a,r)=>{o({[a]:r},"debounced")},l=(a,r)=>{o({[a]:r},"immediate")};return e.jsxs(e.Fragment,{children:[c&&e.jsx("div",{className:"settings-overlay",onClick:n,onKeyDown:a=>{a.key==="Escape"&&n()},role:"presentation"}),e.jsxs("aside",{className:`settings-drawer ${c?"settings-drawer--open":""}`,children:[e.jsxs("div",{className:"settings-header",children:[e.jsx("h2",{className:"settings-title",children:s("reader.settingsTitle")}),e.jsx("button",{type:"button",className:"settings-close-btn",onClick:n,"aria-label":s("reader.closeSettingsAria"),children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsxs("div",{className:"settings-body",children:[e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.theme")}),e.jsx("div",{className:"theme-grid",children:g.map(a=>e.jsx("button",{type:"button",className:`theme-btn ${t.theme===a.value?"theme-btn--active":""}`,onClick:()=>l("theme",a.value),children:s(a.labelKey)},a.value))})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.font")}),e.jsx("div",{className:"font-grid",children:u.map(a=>e.jsx("button",{type:"button",className:`font-btn ${t.font_family===a.value?"font-btn--active":""}`,onClick:()=>l("font_family",a.value),children:s(a.labelKey)},a.value))})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.fontSize",{size:String(t.font_size)})}),e.jsx("input",{type:"range",min:"12",max:"32",value:t.font_size,onChange:a=>i("font_size",Number(a.target.value)),className:"settings-slider","aria-label":s("reader.fontSizeAria")})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.lineHeight",{value:t.line_height.toFixed(1)})}),e.jsx("input",{type:"range",min:"1.2",max:"2.0",step:"0.1",value:t.line_height,onChange:a=>i("line_height",Number(a.target.value)),className:"settings-slider","aria-label":s("reader.lineHeightAria")})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.margins",{value:String(t.margin_width)})}),e.jsx("input",{type:"range",min:"8",max:"48",value:t.margin_width,onChange:a=>i("margin_width",Number(a.target.value)),className:"settings-slider","aria-label":s("reader.marginWidthAria")})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.brightness",{value:String(t.brightness)})}),e.jsx("input",{type:"range",min:"0",max:"100",value:t.brightness,onChange:a=>i("brightness",Number(a.target.value)),className:"settings-slider","aria-label":s("reader.brightnessAria")})]}),e.jsxs("section",{className:"settings-section",children:[e.jsx("h3",{className:"settings-section-title",children:s("reader.orientation")}),e.jsx("div",{className:"orientation-grid",children:x.map(a=>e.jsx("button",{type:"button",className:`orientation-btn ${t.orientation_lock===a.value?"orientation-btn--active":""}`,onClick:()=>l("orientation_lock",a.value),children:s(a.labelKey)},a.value))})]})]})]})]})}export{v as default};
|
|
||||||
@@ -12,13 +12,12 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.7.9",
|
"axios": "^1.7.9",
|
||||||
"dompurify": "^3.4.7",
|
"react-router-dom": "^7.1.0",
|
||||||
"pdfjs-dist": "^4.10.38",
|
"pdfjs-dist": "^4.10.38",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"react-i18n-lite": "^1.0.10",
|
"react-i18n-lite": "^1.0.10",
|
||||||
"react-reader": "^2.0.15",
|
"react-reader": "^2.0.15"
|
||||||
"react-router-dom": "^7.1.0"
|
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@testing-library/jest-dom": "^6.6.3",
|
"@testing-library/jest-dom": "^6.6.3",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { lazy, Suspense, useState } from "react";
|
import React, { lazy, Suspense } from "react";
|
||||||
import { BrowserRouter, Navigate, Route, Routes, useParams } from "react-router-dom";
|
import { BrowserRouter, Navigate, Route, Routes, useParams } from "react-router-dom";
|
||||||
import { AuthProvider, useAuth } from "./context/AuthContext";
|
import { AuthProvider, useAuth } from "./context/AuthContext";
|
||||||
import { I18nProvider } from "./i18n/I18nProvider";
|
import { I18nProvider } from "./i18n/I18nProvider";
|
||||||
@@ -12,15 +12,11 @@ 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 GroupsPage = lazy(() => import("./pages/GroupsPage").then((m) => ({ default: m.GroupsPage })));
|
||||||
|
const GroupDetailPage = lazy(() => import("./pages/GroupDetailPage").then((m) => ({ default: m.GroupDetailPage })));
|
||||||
|
const GroupBookPage = lazy(() => import("./pages/GroupBookPage").then((m) => ({ default: m.GroupBookPage })));
|
||||||
|
|
||||||
const AuthPage = lazy(() =>
|
const AuthPage = lazy(() => import("./pages/AuthPage"));
|
||||||
import("./pages/AuthPage").then((m) => ({
|
|
||||||
default: () => {
|
|
||||||
const [isLogin, setIsLogin] = useState(true);
|
|
||||||
return isLogin ? <m.LoginPage onToggle={() => setIsLogin(false)} /> : <m.RegisterPage onToggle={() => setIsLogin(true)} />;
|
|
||||||
},
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
|
|
||||||
function LoadingFallback() {
|
function LoadingFallback() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -51,6 +47,9 @@ function AppRoutes() {
|
|||||||
<Route path="/reader/:id" element={<ProtectedRoute><ReaderRedirect /></ProtectedRoute>} />
|
<Route path="/reader/:id" element={<ProtectedRoute><ReaderRedirect /></ProtectedRoute>} />
|
||||||
<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="/groups" element={<ProtectedRoute><GroupsPage /></ProtectedRoute>} />
|
||||||
|
<Route path="/groups/:groupId" element={<ProtectedRoute><GroupDetailPage /></ProtectedRoute>} />
|
||||||
|
<Route path="/groups/:groupId/books/:bookId" element={<ProtectedRoute><GroupBookPage /></ProtectedRoute>} />
|
||||||
<Route path="/bookmarks-notes/:bookId?" element={<ProtectedRoute><BookmarksNotesPage /></ProtectedRoute>} />
|
<Route path="/bookmarks-notes/:bookId?" element={<ProtectedRoute><BookmarksNotesPage /></ProtectedRoute>} />
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="*" element={<Navigate to="/" replace />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
|
|||||||
@@ -27,6 +27,3 @@ export async function createMarker(
|
|||||||
export async function deleteBookmark(id: string): Promise<void> {
|
export async function deleteBookmark(id: string): Promise<void> {
|
||||||
await api.delete(`/annotations/bookmarks/${id}/`);
|
await api.delete(`/annotations/bookmarks/${id}/`);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @deprecated Use createMarker */
|
|
||||||
export const createBookmark = createMarker;
|
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import api from "./client";
|
||||||
|
import type {
|
||||||
|
AddMemberPayload,
|
||||||
|
AdjustSectionsPayload,
|
||||||
|
CreateGroupBookPayload,
|
||||||
|
CreateGroupPayload,
|
||||||
|
GroupBook,
|
||||||
|
GroupBookDetail,
|
||||||
|
MemberProgress,
|
||||||
|
ReadingGroup,
|
||||||
|
ReadingGroupDetail,
|
||||||
|
ReadingSchedule,
|
||||||
|
Section,
|
||||||
|
} from "../types/group";
|
||||||
|
|
||||||
|
export const groupsApi = {
|
||||||
|
// ---- Reading Groups ----
|
||||||
|
|
||||||
|
async listGroups(): Promise<ReadingGroup[]> {
|
||||||
|
const { data } = await api.get<{ count: number; results: ReadingGroup[] } | ReadingGroup[]>(
|
||||||
|
"/groups/"
|
||||||
|
);
|
||||||
|
if (Array.isArray(data)) return data;
|
||||||
|
return data.results ?? [];
|
||||||
|
},
|
||||||
|
|
||||||
|
async getGroup(id: number): Promise<ReadingGroupDetail> {
|
||||||
|
const { data } = await api.get<ReadingGroupDetail>(`/groups/${id}/`);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async createGroup(payload: CreateGroupPayload): Promise<ReadingGroup> {
|
||||||
|
const { data } = await api.post<ReadingGroup>("/groups/", payload);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async deleteGroup(id: number): Promise<void> {
|
||||||
|
await api.delete(`/groups/${id}/`);
|
||||||
|
},
|
||||||
|
|
||||||
|
async addMember(groupId: number, payload: AddMemberPayload): Promise<void> {
|
||||||
|
await api.post(`/groups/${groupId}/add_member/`, payload);
|
||||||
|
},
|
||||||
|
|
||||||
|
async removeMember(groupId: number, payload: AddMemberPayload): Promise<void> {
|
||||||
|
await api.post(`/groups/${groupId}/remove_member/`, payload);
|
||||||
|
},
|
||||||
|
|
||||||
|
// ---- Group Books ----
|
||||||
|
|
||||||
|
async listGroupBooks(groupId: number): Promise<GroupBook[]> {
|
||||||
|
const { data } = await api.get<GroupBook[]>(`/groups/${groupId}/books/`);
|
||||||
|
return Array.isArray(data) ? data : (data as { results: GroupBook[] }).results ?? [];
|
||||||
|
},
|
||||||
|
|
||||||
|
async getGroupBook(groupId: number, bookId: number): Promise<GroupBookDetail> {
|
||||||
|
const { data } = await api.get<GroupBookDetail>(`/groups/${groupId}/books/${bookId}/`);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async createGroupBook(
|
||||||
|
groupId: number,
|
||||||
|
payload: CreateGroupBookPayload
|
||||||
|
): Promise<GroupBookDetail> {
|
||||||
|
const { data } = await api.post<GroupBookDetail>(
|
||||||
|
`/groups/${groupId}/books/`,
|
||||||
|
payload
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async deleteGroupBook(groupId: number, bookId: number): Promise<void> {
|
||||||
|
await api.delete(`/groups/${groupId}/books/${bookId}/`);
|
||||||
|
},
|
||||||
|
|
||||||
|
// ---- Sections ----
|
||||||
|
|
||||||
|
async detectSections(
|
||||||
|
groupId: number,
|
||||||
|
bookId: number
|
||||||
|
): Promise<Section[]> {
|
||||||
|
const { data } = await api.post<Section[]>(
|
||||||
|
`/groups/${groupId}/books/${bookId}/detect-sections/`
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async adjustSections(
|
||||||
|
groupId: number,
|
||||||
|
bookId: number,
|
||||||
|
payload: AdjustSectionsPayload
|
||||||
|
): Promise<Section | Section[]> {
|
||||||
|
const { data } = await api.post<Section | Section[]>(
|
||||||
|
`/groups/${groupId}/books/${bookId}/adjust-sections/`,
|
||||||
|
payload
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
// ---- Schedule ----
|
||||||
|
|
||||||
|
async getSchedule(
|
||||||
|
groupId: number,
|
||||||
|
bookId: number
|
||||||
|
): Promise<ReadingSchedule[]> {
|
||||||
|
const { data } = await api.get<ReadingSchedule[]>(
|
||||||
|
`/groups/${groupId}/books/${bookId}/schedule/`
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async generateSchedule(
|
||||||
|
groupId: number,
|
||||||
|
bookId: number,
|
||||||
|
numMeetings: number = 4
|
||||||
|
): Promise<ReadingSchedule[]> {
|
||||||
|
const { data } = await api.post<ReadingSchedule[]>(
|
||||||
|
`/groups/${groupId}/books/${bookId}/schedule/`,
|
||||||
|
{ num_meetings: numMeetings }
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async deleteSchedule(groupId: number, bookId: number): Promise<void> {
|
||||||
|
await api.delete(`/groups/${groupId}/books/${bookId}/schedule/`);
|
||||||
|
},
|
||||||
|
|
||||||
|
// ---- Progress ----
|
||||||
|
|
||||||
|
async getProgress(
|
||||||
|
groupId: number,
|
||||||
|
bookId: number
|
||||||
|
): Promise<MemberProgress[]> {
|
||||||
|
const { data } = await api.get<MemberProgress[]>(
|
||||||
|
`/groups/${groupId}/books/${bookId}/progress/`
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
|
||||||
|
async updateProgress(
|
||||||
|
groupId: number,
|
||||||
|
bookId: number,
|
||||||
|
payload: { current_section?: number; completed_sections?: number[] }
|
||||||
|
): Promise<MemberProgress> {
|
||||||
|
const { data } = await api.patch<MemberProgress>(
|
||||||
|
`/groups/${groupId}/books/${bookId}/progress/`,
|
||||||
|
payload
|
||||||
|
);
|
||||||
|
return data;
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { booksApi } from "@/api/books";
|
||||||
|
import { getReadingProgress } from "@/api/reader";
|
||||||
|
import type { ReadingProgress } from "@/types/reader";
|
||||||
|
|
||||||
|
export async function loadEbookWithProgress(bookId: number): Promise<{
|
||||||
|
progressData: ReadingProgress | null;
|
||||||
|
blob: Blob;
|
||||||
|
}> {
|
||||||
|
const [progressData, blob] = await Promise.all([
|
||||||
|
getReadingProgress(bookId).catch(() => null),
|
||||||
|
booksApi.getEbookFile(bookId),
|
||||||
|
]);
|
||||||
|
return { progressData, blob };
|
||||||
|
}
|
||||||
@@ -1,22 +1,10 @@
|
|||||||
/**
|
/**
|
||||||
* API client for the reader module — reading settings, chapters, and progress.
|
* API client for the reader module — reading settings and progress.
|
||||||
* Uses the shared axios client so JWT auth is attached automatically.
|
* Uses the shared axios client so JWT auth is attached automatically.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import api from "./client";
|
import api from "./client";
|
||||||
import type {
|
import type { ReadingProgress, ReadingSettings } from "../types/reader";
|
||||||
ChapterDetail,
|
|
||||||
ChapterSummary,
|
|
||||||
ReadingProgress,
|
|
||||||
ReadingSettings,
|
|
||||||
} from "../types/reader";
|
|
||||||
|
|
||||||
interface TocChapter {
|
|
||||||
id: number;
|
|
||||||
title: string;
|
|
||||||
index: number;
|
|
||||||
href?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getReadingSettings(): Promise<ReadingSettings> {
|
export async function getReadingSettings(): Promise<ReadingSettings> {
|
||||||
const { data } = await api.get<ReadingSettings>("/reader/settings/");
|
const { data } = await api.get<ReadingSettings>("/reader/settings/");
|
||||||
@@ -30,39 +18,6 @@ export async function updateReadingSettings(
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getChapters(bookId: number): Promise<ChapterSummary[]> {
|
|
||||||
const { data } = await api.get<{ chapters: TocChapter[] }>(
|
|
||||||
`/books/ebooks/${bookId}/toc/`,
|
|
||||||
);
|
|
||||||
const chapters = data.chapters ?? [];
|
|
||||||
return chapters.map((ch) => ({
|
|
||||||
id: ch.id,
|
|
||||||
book: bookId,
|
|
||||||
title: ch.title,
|
|
||||||
number: ch.index + 1,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getChapterContent(
|
|
||||||
bookId: number,
|
|
||||||
chapterNumber: number,
|
|
||||||
): Promise<ChapterDetail> {
|
|
||||||
const { data } = await api.get<{
|
|
||||||
page: number;
|
|
||||||
chapter_title: string;
|
|
||||||
content: string;
|
|
||||||
}>(`/books/ebooks/${bookId}/content/`, { params: { page: chapterNumber } });
|
|
||||||
return {
|
|
||||||
id: chapterNumber,
|
|
||||||
book: bookId,
|
|
||||||
title: data.chapter_title ?? "",
|
|
||||||
number: data.page ?? chapterNumber,
|
|
||||||
content: data.content ?? "",
|
|
||||||
created_at: "",
|
|
||||||
updated_at: "",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getReadingProgress(
|
export async function getReadingProgress(
|
||||||
bookId: number,
|
bookId: number,
|
||||||
): Promise<ReadingProgress> {
|
): Promise<ReadingProgress> {
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { useTranslation } from "react-i18n-lite";
|
||||||
|
|
||||||
|
interface MarkerPassageActionsProps {
|
||||||
|
onGoToPassage: () => void;
|
||||||
|
onDelete: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MarkerPassageActions({ onGoToPassage, onDelete }: MarkerPassageActionsProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<div className="annotation-actions">
|
||||||
|
<button type="button" className="btn btn-sm" onClick={onGoToPassage}>
|
||||||
|
{t("annotations.goToPassage")}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn btn-sm btn-danger" onClick={onDelete}>
|
||||||
|
{t("common.delete")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
CollapsibleMarkerPassage,
|
CollapsibleMarkerPassage,
|
||||||
CollapsibleMarkerThought,
|
CollapsibleMarkerThought,
|
||||||
} from "@/components/annotations/CollapsibleMarkerText";
|
} from "@/components/annotations/CollapsibleMarkerText";
|
||||||
|
import { MarkerPassageActions } from "@/components/annotations/MarkerPassageActions";
|
||||||
|
|
||||||
interface MarkerThreadsViewProps {
|
interface MarkerThreadsViewProps {
|
||||||
ebookIdFilter?: string;
|
ebookIdFilter?: string;
|
||||||
@@ -91,22 +92,10 @@ export function MarkerThreadsView({
|
|||||||
) : (
|
) : (
|
||||||
<span className="annotation-kind-badge bookmark-badge">{t("annotations.bookmarkOnly")}</span>
|
<span className="annotation-kind-badge bookmark-badge">{t("annotations.bookmarkOnly")}</span>
|
||||||
)}
|
)}
|
||||||
<div className="annotation-actions">
|
<MarkerPassageActions
|
||||||
<button
|
onGoToPassage={() => onGoToPassage(m.ebook_id, m.epub_cfi)}
|
||||||
type="button"
|
onDelete={() => removeBookmark(m.id)}
|
||||||
className="btn btn-sm"
|
/>
|
||||||
onClick={() => onGoToPassage(m.ebook_id, m.epub_cfi)}
|
|
||||||
>
|
|
||||||
{t("annotations.goToPassage")}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="btn btn-sm btn-danger"
|
|
||||||
onClick={() => removeBookmark(m.id)}
|
|
||||||
>
|
|
||||||
{t("common.delete")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
export { BookmarksNotesPage } from "./BookmarksNotesPage";
|
|
||||||
export { MarkerThreadsView } from "./MarkerThreadsView";
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
import React from "react";
|
|
||||||
import { useTranslation } from "react-i18n-lite";
|
|
||||||
|
|
||||||
interface LayoutProps {
|
|
||||||
children: React.ReactNode;
|
|
||||||
title?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Layout({
|
|
||||||
children,
|
|
||||||
title,
|
|
||||||
}: LayoutProps): React.ReactElement {
|
|
||||||
const { t } = useTranslation();
|
|
||||||
const pageTitle = title ?? t("common.appName");
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="app-container">
|
|
||||||
<header className="app-header">
|
|
||||||
<h1 className="app-title">{pageTitle}</h1>
|
|
||||||
<nav className="app-nav">
|
|
||||||
<a href="/" className="nav-link">{t("annotations.home")}</a>
|
|
||||||
<a href="/bookmarks-notes" className="nav-link">{t("annotations.bookmarksNotes")}</a>
|
|
||||||
</nav>
|
|
||||||
</header>
|
|
||||||
<main className="app-main">{children}</main>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { useTranslation } from "react-i18n-lite";
|
||||||
|
|
||||||
|
interface SimpleFormPageLayoutProps {
|
||||||
|
title: string;
|
||||||
|
onBack: () => void;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SimpleFormPageLayout({ title, onBack, children }: SimpleFormPageLayoutProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||||
|
<header style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24, padding: "16px 0", borderBottom: "1px solid #eee" }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={onBack}
|
||||||
|
style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}
|
||||||
|
>
|
||||||
|
← {t("common.back")}
|
||||||
|
</button>
|
||||||
|
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>{title}</h1>
|
||||||
|
</header>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1 +0,0 @@
|
|||||||
export { Layout } from "./Layout";
|
|
||||||
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
|
|||||||
import { useTranslation } from "react-i18n-lite";
|
import { useTranslation } from "react-i18n-lite";
|
||||||
import styles from "./FinishedBooksShelf.module.css";
|
import styles from "./FinishedBooksShelf.module.css";
|
||||||
|
|
||||||
export interface ShelfBook {
|
interface ShelfBook {
|
||||||
id: number;
|
id: number;
|
||||||
title: string;
|
title: string;
|
||||||
author: string;
|
author: string;
|
||||||
|
|||||||
@@ -2,14 +2,14 @@ import { useTranslation } from "react-i18n-lite";
|
|||||||
import { readingStatusKey } from "@/locales";
|
import { readingStatusKey } from "@/locales";
|
||||||
import styles from "../../pages/Library.module.css";
|
import styles from "../../pages/Library.module.css";
|
||||||
|
|
||||||
export const LIBRARY_STATUS_COLORS: Record<string, { bg: string; text: string }> = {
|
const LIBRARY_STATUS_COLORS: Record<string, { bg: string; text: string }> = {
|
||||||
want_to_read: { bg: "#dbeafe", text: "#1d4ed8" },
|
want_to_read: { bg: "#dbeafe", text: "#1d4ed8" },
|
||||||
reading: { bg: "#dcfce7", text: "#16a34a" },
|
reading: { bg: "#dcfce7", text: "#16a34a" },
|
||||||
finished: { bg: "#f3e8ff", text: "#9333ea" },
|
finished: { bg: "#f3e8ff", text: "#9333ea" },
|
||||||
dnf: { bg: "#fef3c7", text: "#b45309" },
|
dnf: { bg: "#fef3c7", text: "#b45309" },
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface LibraryBookCardData {
|
interface LibraryBookCardData {
|
||||||
id: number;
|
id: number;
|
||||||
title: string;
|
title: string;
|
||||||
author: string;
|
author: string;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
CollapsibleMarkerPassage,
|
CollapsibleMarkerPassage,
|
||||||
CollapsibleMarkerThought,
|
CollapsibleMarkerThought,
|
||||||
} from "@/components/annotations/CollapsibleMarkerText";
|
} from "@/components/annotations/CollapsibleMarkerText";
|
||||||
|
import { MarkerPassageActions } from "@/components/annotations/MarkerPassageActions";
|
||||||
|
|
||||||
interface BookMarkersPanelProps {
|
interface BookMarkersPanelProps {
|
||||||
ebookId: number;
|
ebookId: number;
|
||||||
@@ -67,18 +68,10 @@ export function BookMarkersPanel({
|
|||||||
) : (
|
) : (
|
||||||
<span className="annotation-kind-badge bookmark-badge">{t("annotations.bookmarkOnly")}</span>
|
<span className="annotation-kind-badge bookmark-badge">{t("annotations.bookmarkOnly")}</span>
|
||||||
)}
|
)}
|
||||||
<div className="annotation-actions">
|
<MarkerPassageActions
|
||||||
<button type="button" className="btn btn-sm" onClick={() => onGoToPassage(m)}>
|
onGoToPassage={() => onGoToPassage(m)}
|
||||||
{t("annotations.goToPassage")}
|
onDelete={() => removeBookmark(m.id)}
|
||||||
</button>
|
/>
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="btn btn-sm btn-danger"
|
|
||||||
onClick={() => removeBookmark(m.id)}
|
|
||||||
>
|
|
||||||
{t("common.delete")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
* EpubReadingView — full-screen EPUB reading powered by react-reader (epub.js).
|
* EpubReadingView — full-screen EPUB reading powered by react-reader (epub.js).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from "react";
|
import { lazy, useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18n-lite";
|
import { useTranslation } from "react-i18n-lite";
|
||||||
import { EpubView, EpubViewStyle } from "react-reader";
|
import { EpubView, EpubViewStyle } from "react-reader";
|
||||||
@@ -12,6 +12,10 @@ import { useEpubHighlights } from "../../hooks/useEpubHighlights";
|
|||||||
import { useEpubReader } from "../../hooks/useEpubReader";
|
import { useEpubReader } from "../../hooks/useEpubReader";
|
||||||
import { useEpubSelection } from "../../hooks/useEpubSelection";
|
import { useEpubSelection } from "../../hooks/useEpubSelection";
|
||||||
import { useReadingSettings } from "../../hooks/useReadingSettings";
|
import { useReadingSettings } from "../../hooks/useReadingSettings";
|
||||||
|
import { useReaderOrientationCss } from "../../hooks/useReaderOrientationCss";
|
||||||
|
import { ReaderErrorScreen } from "./ReaderErrorScreen";
|
||||||
|
import { ReaderLoadingScreen } from "./ReaderLoadingScreen";
|
||||||
|
import { ReaderSuspenseShell } from "./ReaderSuspenseShell";
|
||||||
import type { EBookDetail } from "../../types/book";
|
import type { EBookDetail } from "../../types/book";
|
||||||
import type { EpubTocItem } from "./TableOfContents";
|
import type { EpubTocItem } from "./TableOfContents";
|
||||||
import { SelectionPopover } from "./SelectionPopover";
|
import { SelectionPopover } from "./SelectionPopover";
|
||||||
@@ -82,17 +86,7 @@ export function EpubReadingView({ book, bookId, initialEpubLocation }: EpubReadi
|
|||||||
applySettings(settings);
|
applySettings(settings);
|
||||||
}, [settings, applySettings]);
|
}, [settings, applySettings]);
|
||||||
|
|
||||||
useEffect(() => {
|
useReaderOrientationCss(settings.orientation_lock);
|
||||||
const root = document.documentElement;
|
|
||||||
if (settings.orientation_lock !== "auto") {
|
|
||||||
root.style.setProperty(
|
|
||||||
"--reader-orientation",
|
|
||||||
settings.orientation_lock === "portrait" ? "portrait" : "landscape",
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
root.style.removeProperty("--reader-orientation");
|
|
||||||
}
|
|
||||||
}, [settings.orientation_lock]);
|
|
||||||
|
|
||||||
const handleTocChanged = useCallback((toc: EpubTocItem[]) => {
|
const handleTocChanged = useCallback((toc: EpubTocItem[]) => {
|
||||||
setTocItems(toc);
|
setTocItems(toc);
|
||||||
@@ -122,34 +116,20 @@ export function EpubReadingView({ book, bookId, initialEpubLocation }: EpubReadi
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (epubLoading) {
|
if (epubLoading) {
|
||||||
return (
|
return <ReaderLoadingScreen />;
|
||||||
<div className="reader-loading">
|
|
||||||
<div className="spinner" />
|
|
||||||
<p>{t("reader.loading")}</p>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (epubError || !epubUrl) {
|
if (epubError || !epubUrl) {
|
||||||
return (
|
return (
|
||||||
<div className="reader-loading">
|
<ReaderErrorScreen
|
||||||
<p className="reader-error">{epubError ?? t("reader.unableToOpen")}</p>
|
message={epubError ?? t("reader.unableToOpen")}
|
||||||
<button type="button" className="back-button" onClick={() => navigate("/")}>
|
onBack={() => navigate("/")}
|
||||||
{t("reader.backToLibrary")}
|
/>
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Suspense
|
<ReaderSuspenseShell theme={settings.theme}>
|
||||||
fallback={
|
|
||||||
<div className="reader-loading">
|
|
||||||
<div className="spinner" />
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<div className="reader-container" data-theme={settings.theme}>
|
|
||||||
<ReaderToolbar
|
<ReaderToolbar
|
||||||
bookTitle={book.title}
|
bookTitle={book.title}
|
||||||
chapterTitle={chapterTitle || t("reader.reading")}
|
chapterTitle={chapterTitle || t("reader.reading")}
|
||||||
@@ -235,7 +215,6 @@ export function EpubReadingView({ book, bookId, initialEpubLocation }: EpubReadi
|
|||||||
›
|
›
|
||||||
</button>
|
</button>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</ReaderSuspenseShell>
|
||||||
</Suspense>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
interface PanelCloseButtonProps {
|
||||||
|
className: string;
|
||||||
|
onClick: () => void;
|
||||||
|
ariaLabel: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PanelCloseButton({ className, onClick, ariaLabel }: PanelCloseButtonProps) {
|
||||||
|
return (
|
||||||
|
<button type="button" className={className} onClick={onClick} aria-label={ariaLabel}>
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||||
|
<line x1="18" y1="6" x2="6" y2="18" />
|
||||||
|
<line x1="6" y1="6" x2="18" y2="18" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,13 +2,17 @@
|
|||||||
* PdfReadingView — full-screen PDF reading powered by PDF.js.
|
* PdfReadingView — full-screen PDF reading powered by PDF.js.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from "react";
|
import { lazy, useCallback, useEffect, useMemo, useState } from "react";
|
||||||
import { useNavigate } from "react-router-dom";
|
import { useNavigate } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18n-lite";
|
import { useTranslation } from "react-i18n-lite";
|
||||||
import { useAnnotations } from "@/context/AnnotationsContext";
|
import { useAnnotations } from "@/context/AnnotationsContext";
|
||||||
import { useBookmarkRailLayout } from "../../hooks/useBookmarkRailLayout";
|
import { useBookmarkRailLayout } from "../../hooks/useBookmarkRailLayout";
|
||||||
import { usePdfReader } from "../../hooks/usePdfReader";
|
import { usePdfReader } from "../../hooks/usePdfReader";
|
||||||
import { useReadingSettings } from "../../hooks/useReadingSettings";
|
import { useReadingSettings } from "../../hooks/useReadingSettings";
|
||||||
|
import { useReaderOrientationCss } from "../../hooks/useReaderOrientationCss";
|
||||||
|
import { ReaderErrorScreen } from "./ReaderErrorScreen";
|
||||||
|
import { ReaderLoadingScreen } from "./ReaderLoadingScreen";
|
||||||
|
import { ReaderSuspenseShell } from "./ReaderSuspenseShell";
|
||||||
import { useToast } from "../../hooks/useToast";
|
import { useToast } from "../../hooks/useToast";
|
||||||
import { booksApi } from "../../api/books";
|
import { booksApi } from "../../api/books";
|
||||||
import type { EBookDetail } from "../../types/book";
|
import type { EBookDetail } from "../../types/book";
|
||||||
@@ -96,17 +100,7 @@ export function PdfReadingView({ book, bookId, initialAnchor }: PdfReadingViewPr
|
|||||||
);
|
);
|
||||||
}, [bookId, pageCount, t]);
|
}, [bookId, pageCount, t]);
|
||||||
|
|
||||||
useEffect(() => {
|
useReaderOrientationCss(settings.orientation_lock);
|
||||||
const root = document.documentElement;
|
|
||||||
if (settings.orientation_lock !== "auto") {
|
|
||||||
root.style.setProperty(
|
|
||||||
"--reader-orientation",
|
|
||||||
settings.orientation_lock === "portrait" ? "portrait" : "landscape",
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
root.style.removeProperty("--reader-orientation");
|
|
||||||
}
|
|
||||||
}, [settings.orientation_lock]);
|
|
||||||
|
|
||||||
const handleTocNavigate = useCallback(
|
const handleTocNavigate = useCallback(
|
||||||
(href: string) => {
|
(href: string) => {
|
||||||
@@ -165,36 +159,17 @@ export function PdfReadingView({ book, bookId, initialAnchor }: PdfReadingViewPr
|
|||||||
}, [bookMarkers, currentPage]);
|
}, [bookMarkers, currentPage]);
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return <ReaderLoadingScreen />;
|
||||||
<div className="reader-loading">
|
|
||||||
<div className="spinner" />
|
|
||||||
<p>{t("reader.loading")}</p>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (error || !pdfDocument) {
|
if (error || !pdfDocument) {
|
||||||
const message =
|
const message =
|
||||||
error === "PDF_PASSWORD" ? t("reader.pdfPassword") : (error ?? t("reader.unableToOpen"));
|
error === "PDF_PASSWORD" ? t("reader.pdfPassword") : (error ?? t("reader.unableToOpen"));
|
||||||
return (
|
return <ReaderErrorScreen message={message} onBack={() => navigate("/")} />;
|
||||||
<div className="reader-loading">
|
|
||||||
<p className="reader-error">{message}</p>
|
|
||||||
<button type="button" className="back-button" onClick={() => navigate("/")}>
|
|
||||||
{t("reader.backToLibrary")}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Suspense
|
<ReaderSuspenseShell theme={settings.theme}>
|
||||||
fallback={
|
|
||||||
<div className="reader-loading">
|
|
||||||
<div className="spinner" />
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<div className="reader-container" data-theme={settings.theme}>
|
|
||||||
<ReaderToolbar
|
<ReaderToolbar
|
||||||
bookTitle={book.title}
|
bookTitle={book.title}
|
||||||
chapterTitle={chapterTitle || t("reader.reading")}
|
chapterTitle={chapterTitle || t("reader.reading")}
|
||||||
@@ -270,7 +245,6 @@ export function PdfReadingView({ book, bookId, initialAnchor }: PdfReadingViewPr
|
|||||||
›
|
›
|
||||||
</button>
|
</button>
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</ReaderSuspenseShell>
|
||||||
</Suspense>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { useTranslation } from "react-i18n-lite";
|
||||||
|
|
||||||
|
interface ReaderErrorScreenProps {
|
||||||
|
message: string;
|
||||||
|
onBack: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReaderErrorScreen({ message, onBack }: ReaderErrorScreenProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<div className="reader-loading">
|
||||||
|
<p className="reader-error">{message}</p>
|
||||||
|
<button type="button" className="back-button" onClick={onBack}>
|
||||||
|
{t("reader.backToLibrary")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { useTranslation } from "react-i18n-lite";
|
||||||
|
|
||||||
|
interface ReaderLoadingScreenProps {
|
||||||
|
showMessage?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReaderLoadingScreen({ showMessage = true }: ReaderLoadingScreenProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<div className="reader-loading">
|
||||||
|
<div className="spinner" />
|
||||||
|
{showMessage && <p>{t("reader.loading")}</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { Suspense, type ReactNode } from "react";
|
||||||
|
import { ReaderLoadingScreen } from "./ReaderLoadingScreen";
|
||||||
|
|
||||||
|
interface ReaderSuspenseShellProps {
|
||||||
|
theme: string;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReaderSuspenseShell({ theme, children }: ReaderSuspenseShellProps) {
|
||||||
|
return (
|
||||||
|
<Suspense fallback={<ReaderLoadingScreen showMessage={false} />}>
|
||||||
|
<div className="reader-container" data-theme={theme}>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</Suspense>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { useTranslation } from "react-i18n-lite";
|
||||||
|
|
||||||
|
interface ReaderTocButtonProps {
|
||||||
|
onClick: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ReaderTocButton({ onClick }: ReaderTocButtonProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="reader-bar-btn"
|
||||||
|
onClick={onClick}
|
||||||
|
aria-label={t("reader.tocAria")}
|
||||||
|
>
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||||
|
<line x1="3" y1="6" x2="21" y2="6" />
|
||||||
|
<line x1="3" y1="12" x2="21" y2="12" />
|
||||||
|
<line x1="3" y1="18" x2="21" y2="18" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
import { useTranslation } from "react-i18n-lite";
|
import { useTranslation } from "react-i18n-lite";
|
||||||
import type { ReadingProgress } from "../../types/reader";
|
import type { ReadingProgress } from "../../types/reader";
|
||||||
|
import { ReaderTocButton } from "./ReaderTocButton";
|
||||||
|
|
||||||
interface ReaderToolbarProps {
|
interface ReaderToolbarProps {
|
||||||
bookTitle: string;
|
bookTitle: string;
|
||||||
@@ -47,38 +48,14 @@ export default function ReaderToolbar({
|
|||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
) : (
|
) : (
|
||||||
<button
|
<ReaderTocButton onClick={onToggleToc} />
|
||||||
type="button"
|
|
||||||
className="reader-bar-btn"
|
|
||||||
onClick={onToggleToc}
|
|
||||||
aria-label={t("reader.tocAria")}
|
|
||||||
>
|
|
||||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<line x1="3" y1="6" x2="21" y2="6" />
|
|
||||||
<line x1="3" y1="12" x2="21" y2="12" />
|
|
||||||
<line x1="3" y1="18" x2="21" y2="18" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
)}
|
)}
|
||||||
<div className="reader-bar-title">
|
<div className="reader-bar-title">
|
||||||
<span className="reader-bar-book">{bookTitle}</span>
|
<span className="reader-bar-book">{bookTitle}</span>
|
||||||
<span className="reader-bar-chapter">{chapterTitle}</span>
|
<span className="reader-bar-chapter">{chapterTitle}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="reader-bar-actions">
|
<div className="reader-bar-actions">
|
||||||
{onBack && (
|
{onBack && <ReaderTocButton onClick={onToggleToc} />}
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="reader-bar-btn"
|
|
||||||
onClick={onToggleToc}
|
|
||||||
aria-label={t("reader.tocAria")}
|
|
||||||
>
|
|
||||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<line x1="3" y1="6" x2="21" y2="6" />
|
|
||||||
<line x1="3" y1="12" x2="21" y2="12" />
|
|
||||||
<line x1="3" y1="18" x2="21" y2="18" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
{onBookmarkPage && (
|
{onBookmarkPage && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import type {
|
|||||||
ThemePreset,
|
ThemePreset,
|
||||||
} from "../../types/reader";
|
} from "../../types/reader";
|
||||||
import type { SettingsPersistMode } from "../../hooks/useReadingSettings";
|
import type { SettingsPersistMode } from "../../hooks/useReadingSettings";
|
||||||
|
import { PanelCloseButton } from "./PanelCloseButton";
|
||||||
|
|
||||||
interface ReadingSettingsPanelProps {
|
interface ReadingSettingsPanelProps {
|
||||||
format?: "epub" | "pdf";
|
format?: "epub" | "pdf";
|
||||||
@@ -89,17 +90,11 @@ export default function ReadingSettingsPanel({
|
|||||||
>
|
>
|
||||||
<div className="settings-header">
|
<div className="settings-header">
|
||||||
<h2 className="settings-title">{t("reader.settingsTitle")}</h2>
|
<h2 className="settings-title">{t("reader.settingsTitle")}</h2>
|
||||||
<button
|
<PanelCloseButton
|
||||||
type="button"
|
|
||||||
className="settings-close-btn"
|
className="settings-close-btn"
|
||||||
onClick={handleClose}
|
onClick={handleClose}
|
||||||
aria-label={t("reader.closeSettingsAria")}
|
ariaLabel={t("reader.closeSettingsAria")}
|
||||||
>
|
/>
|
||||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<line x1="18" y1="6" x2="6" y2="18" />
|
|
||||||
<line x1="6" y1="6" x2="18" y2="18" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="settings-body">
|
<div className="settings-body">
|
||||||
@@ -124,7 +119,7 @@ export default function ReadingSettingsPanel({
|
|||||||
{format === "pdf" && onPdfScaleChange && (
|
{format === "pdf" && onPdfScaleChange && (
|
||||||
<section className="settings-section">
|
<section className="settings-section">
|
||||||
<h3 className="settings-section-title">
|
<h3 className="settings-section-title">
|
||||||
{t("reader.pdfZoom", { value: Math.round(pdfScale * 100) })}
|
{t("reader.pdfZoom", { value: String(Math.round(pdfScale * 100)) })}
|
||||||
</h3>
|
</h3>
|
||||||
<input
|
<input
|
||||||
type="range"
|
type="range"
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
|
|
||||||
import type { KeyboardEvent } from "react";
|
import type { KeyboardEvent } from "react";
|
||||||
import { useTranslation } from "react-i18n-lite";
|
import { useTranslation } from "react-i18n-lite";
|
||||||
|
import { PanelCloseButton } from "./PanelCloseButton";
|
||||||
|
|
||||||
export interface EpubTocItem {
|
export interface EpubTocItem {
|
||||||
label: string;
|
label: string;
|
||||||
@@ -73,17 +74,11 @@ export default function TableOfContents({
|
|||||||
<aside className={`toc-drawer ${isOpen ? "toc-drawer--open" : ""}`}>
|
<aside className={`toc-drawer ${isOpen ? "toc-drawer--open" : ""}`}>
|
||||||
<div className="toc-header">
|
<div className="toc-header">
|
||||||
<h2 className="toc-title">{t("reader.tocTitle")}</h2>
|
<h2 className="toc-title">{t("reader.tocTitle")}</h2>
|
||||||
<button
|
<PanelCloseButton
|
||||||
type="button"
|
|
||||||
className="toc-close-btn"
|
className="toc-close-btn"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
aria-label={t("reader.closeTocAria")}
|
ariaLabel={t("reader.closeTocAria")}
|
||||||
>
|
/>
|
||||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
|
||||||
<line x1="18" y1="6" x2="6" y2="18" />
|
|
||||||
<line x1="6" y1="6" x2="18" y2="18" />
|
|
||||||
</svg>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<nav className="toc-list">
|
<nav className="toc-list">
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export function highlightBackgroundStyle(color: string): {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export const BOOKMARK_COLOR_STORAGE_KEY = "cloud-reader:lastBookmarkHighlightColor";
|
const BOOKMARK_COLOR_STORAGE_KEY = "cloud-reader:lastBookmarkHighlightColor";
|
||||||
|
|
||||||
export function loadLastHighlightColor(): string {
|
export function loadLastHighlightColor(): string {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import {
|
|||||||
} from "react";
|
} from "react";
|
||||||
import type { Bookmark, CreateMarkerPayload, MarkerEntry, MarkersByBook } from "@/types";
|
import type { Bookmark, CreateMarkerPayload, MarkerEntry, MarkersByBook } from "@/types";
|
||||||
import * as annotationsApi from "@/api/annotations";
|
import * as annotationsApi from "@/api/annotations";
|
||||||
import { bookmarkToMarkerEntry, groupMarkersByBook, sortMarkers } from "@/utils/markers";
|
import { bookmarkToMarkerEntry, groupMarkersByBook, sortBookmarks } from "@/utils/markers";
|
||||||
|
|
||||||
interface AnnotationsState {
|
interface AnnotationsState {
|
||||||
bookmarks: Bookmark[];
|
bookmarks: Bookmark[];
|
||||||
@@ -37,10 +37,7 @@ function annotationsReducer(
|
|||||||
case "FETCH_BOOKMARKS_START":
|
case "FETCH_BOOKMARKS_START":
|
||||||
return { ...state, bookmarksLoading: true, error: null };
|
return { ...state, bookmarksLoading: true, error: null };
|
||||||
case "FETCH_BOOKMARKS_SUCCESS": {
|
case "FETCH_BOOKMARKS_SUCCESS": {
|
||||||
const sorted = [...action.payload].sort((a, b) => {
|
const sorted = [...action.payload].sort(sortBookmarks);
|
||||||
if (a.chapter_index !== b.chapter_index) return a.chapter_index - b.chapter_index;
|
|
||||||
return a.epub_cfi.localeCompare(b.epub_cfi);
|
|
||||||
});
|
|
||||||
return { ...state, bookmarks: sorted, bookmarksLoading: false };
|
return { ...state, bookmarks: sorted, bookmarksLoading: false };
|
||||||
}
|
}
|
||||||
case "SET_ERROR":
|
case "SET_ERROR":
|
||||||
@@ -51,10 +48,7 @@ function annotationsReducer(
|
|||||||
bookmarks: state.bookmarks.filter((b) => b.id !== action.payload),
|
bookmarks: state.bookmarks.filter((b) => b.id !== action.payload),
|
||||||
};
|
};
|
||||||
case "ADD_BOOKMARK": {
|
case "ADD_BOOKMARK": {
|
||||||
const next = [...state.bookmarks, action.payload].sort((a, b) => {
|
const next = [...state.bookmarks, action.payload].sort(sortBookmarks);
|
||||||
if (a.chapter_index !== b.chapter_index) return a.chapter_index - b.chapter_index;
|
|
||||||
return a.epub_cfi.localeCompare(b.epub_cfi);
|
|
||||||
});
|
|
||||||
return { ...state, bookmarks: next };
|
return { ...state, bookmarks: next };
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -105,7 +99,7 @@ export function AnnotationsProvider({
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const markers = useMemo(
|
const markers = useMemo(
|
||||||
() => state.bookmarks.map(bookmarkToMarkerEntry).sort(sortMarkers),
|
() => [...state.bookmarks].sort(sortBookmarks).map(bookmarkToMarkerEntry),
|
||||||
[state.bookmarks],
|
[state.bookmarks],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +0,0 @@
|
|||||||
export { usePaginatedQuery } from "./usePaginatedQuery";
|
|
||||||
export { useDebounce } from "./useDebounce";
|
|
||||||
export { useVoiceSearch } from "./useVoiceSearch";
|
|
||||||
export { useMediaQuery } from "./useMediaQuery";
|
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { booksApi } from "../api/books";
|
import { loadEbookWithProgress } from "../api/loadEbookWithProgress";
|
||||||
import { getReadingProgress, updateReadingProgress } from "../api/reader";
|
import { updateReadingProgress } from "../api/reader";
|
||||||
import type { ReadingProgress, ReadingSettings } from "../types/reader";
|
import type { ReadingProgress, ReadingSettings } from "../types/reader";
|
||||||
import {
|
import {
|
||||||
applyRenditionSettings,
|
applyRenditionSettings,
|
||||||
@@ -197,10 +197,7 @@ export function useEpubReader(
|
|||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const [progressData, blob] = await Promise.all([
|
const { progressData, blob } = await loadEbookWithProgress(bookId);
|
||||||
getReadingProgress(bookId).catch(() => null),
|
|
||||||
booksApi.getEbookFile(bookId),
|
|
||||||
]);
|
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
|
|
||||||
blobUrl = URL.createObjectURL(blob);
|
blobUrl = URL.createObjectURL(blob);
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
import { useState, useCallback, useRef, useEffect } from "react";
|
|
||||||
import type { PaginatedResponse } from "@/types";
|
|
||||||
|
|
||||||
interface UsePaginatedQueryOptions<T> {
|
|
||||||
fetchFn: (cursor?: string) => Promise<PaginatedResponse<T>>;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UsePaginatedQueryResult<T> {
|
|
||||||
items: T[];
|
|
||||||
loading: boolean;
|
|
||||||
error: string | null;
|
|
||||||
hasMore: boolean;
|
|
||||||
loadMore: () => Promise<void>;
|
|
||||||
refresh: () => Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hook for paginated list fetching with infinite scroll support.
|
|
||||||
*/
|
|
||||||
export function usePaginatedQuery<T>({
|
|
||||||
fetchFn,
|
|
||||||
}: UsePaginatedQueryOptions<T>): UsePaginatedQueryResult<T> {
|
|
||||||
const [items, setItems] = useState<T[]>([]);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
const [nextCursor, setNextCursor] = useState<string | null>(null);
|
|
||||||
const loadingRef = useRef(false);
|
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
|
||||||
setLoading(true);
|
|
||||||
setError(null);
|
|
||||||
try {
|
|
||||||
const response = await fetchFn();
|
|
||||||
setItems(response.results);
|
|
||||||
setNextCursor(response.next);
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : "Failed to fetch data");
|
|
||||||
} finally {
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
}, [fetchFn]);
|
|
||||||
|
|
||||||
const loadMore = useCallback(async () => {
|
|
||||||
if (!nextCursor || loadingRef.current) return;
|
|
||||||
loadingRef.current = true;
|
|
||||||
try {
|
|
||||||
const response = await fetchFn(nextCursor);
|
|
||||||
setItems((prev) => [...prev, ...response.results]);
|
|
||||||
setNextCursor(response.next);
|
|
||||||
} catch (err) {
|
|
||||||
setError(err instanceof Error ? err.message : "Failed to load more");
|
|
||||||
} finally {
|
|
||||||
loadingRef.current = false;
|
|
||||||
}
|
|
||||||
}, [nextCursor, fetchFn]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
refresh();
|
|
||||||
}, [refresh]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
items,
|
|
||||||
loading,
|
|
||||||
error,
|
|
||||||
hasMore: nextCursor !== null,
|
|
||||||
loadMore,
|
|
||||||
refresh,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { booksApi } from "../api/books";
|
import { loadEbookWithProgress } from "../api/loadEbookWithProgress";
|
||||||
import { getReadingProgress, updateReadingProgress } from "../api/reader";
|
import { updateReadingProgress } from "../api/reader";
|
||||||
import type { ReadingProgress } from "../types/reader";
|
import type { ReadingProgress } from "../types/reader";
|
||||||
import { parsePdfAnchor } from "../utils/pdfAnchor";
|
import { parsePdfAnchor } from "../utils/pdfAnchor";
|
||||||
import { pdfjs, type PdfDocumentProxy } from "../utils/pdfjsSetup";
|
import { pdfjs, type PdfDocumentProxy } from "../utils/pdfjsSetup";
|
||||||
@@ -175,10 +175,7 @@ export function usePdfReader(
|
|||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const [progressData, blob] = await Promise.all([
|
const { progressData, blob } = await loadEbookWithProgress(bookId);
|
||||||
getReadingProgress(bookId).catch(() => null),
|
|
||||||
booksApi.getEbookFile(bookId),
|
|
||||||
]);
|
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
|
|
||||||
const loadingTask = pdfjs.getDocument({ data: await blob.arrayBuffer() });
|
const loadingTask = pdfjs.getDocument({ data: await blob.arrayBuffer() });
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
|
import type { ReadingSettings } from "@/types/reader";
|
||||||
|
|
||||||
|
export function useReaderOrientationCss(orientationLock: ReadingSettings["orientation_lock"]): void {
|
||||||
|
useEffect(() => {
|
||||||
|
const root = document.documentElement;
|
||||||
|
if (orientationLock !== "auto") {
|
||||||
|
root.style.setProperty(
|
||||||
|
"--reader-orientation",
|
||||||
|
orientationLock === "portrait" ? "portrait" : "landscape",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
root.style.removeProperty("--reader-orientation");
|
||||||
|
}
|
||||||
|
}, [orientationLock]);
|
||||||
|
}
|
||||||
@@ -36,7 +36,7 @@ const DEFAULT_SETTINGS: ReadingSettings = {
|
|||||||
|
|
||||||
const SAVE_DEBOUNCE_MS = 600;
|
const SAVE_DEBOUNCE_MS = 600;
|
||||||
|
|
||||||
export function applyReadingCssVariables(settings: ReadingSettings): void {
|
function applyReadingCssVariables(settings: ReadingSettings): void {
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
root.style.setProperty("--reader-bg", settings.background_color);
|
root.style.setProperty("--reader-bg", settings.background_color);
|
||||||
root.style.setProperty("--reader-text", settings.text_color);
|
root.style.setProperty("--reader-text", settings.text_color);
|
||||||
|
|||||||
@@ -245,6 +245,54 @@ const enUS = {
|
|||||||
home: "Home",
|
home: "Home",
|
||||||
bookmarksNotes: "Bookmarks & Notes",
|
bookmarksNotes: "Bookmarks & Notes",
|
||||||
},
|
},
|
||||||
|
groups: {
|
||||||
|
title: "Reading Groups",
|
||||||
|
createGroup: "Create Group",
|
||||||
|
create: "Create",
|
||||||
|
cancel: "Cancel",
|
||||||
|
groupName: "Group Name",
|
||||||
|
groupNamePlaceholder: "Enter group name",
|
||||||
|
description: "Description",
|
||||||
|
descriptionPlaceholder: "What is this group about?",
|
||||||
|
optional: "Optional",
|
||||||
|
noGroups: "No groups yet",
|
||||||
|
noGroupsHint: "Create a reading group to start reading together!",
|
||||||
|
members: "Members",
|
||||||
|
admin: "Admin",
|
||||||
|
addMember: "Add Member",
|
||||||
|
memberIdPlaceholder: "Enter user ID",
|
||||||
|
add: "Add",
|
||||||
|
remove: "Remove",
|
||||||
|
books: "Group Books",
|
||||||
|
uploadEpub: "Upload EPUB",
|
||||||
|
selectEbook: "Select an EPUB to share with the group",
|
||||||
|
noEpubBooks: "No EPUB files uploaded yet",
|
||||||
|
uploadFirst: "Upload an EPUB first",
|
||||||
|
confirmUpload: "Confirm Upload",
|
||||||
|
noBooks: "No books in this group yet",
|
||||||
|
sections: "Sections",
|
||||||
|
schedule: "Schedule",
|
||||||
|
progress: "Progress",
|
||||||
|
detectSections: "Auto-Detect Sections",
|
||||||
|
mergeSections: "Merge Sections",
|
||||||
|
selectSectionsHint: "Click sections to select for merging",
|
||||||
|
merge: "Merge",
|
||||||
|
clear: "Clear",
|
||||||
|
split: "Split",
|
||||||
|
splitInto: "Split into",
|
||||||
|
parts: "parts",
|
||||||
|
splitBtn: "Split",
|
||||||
|
noSections: "No sections detected yet",
|
||||||
|
noSectionsHint: 'Click "Auto-Detect Sections" to parse the EPUB chapters into reading sections.',
|
||||||
|
readingSchedule: "Reading Schedule",
|
||||||
|
generateSchedule: "Generate Schedule",
|
||||||
|
noSchedule: "No schedule generated yet",
|
||||||
|
noScheduleHint: "Detect sections first, then generate a reading schedule for your group.",
|
||||||
|
meeting: "Meeting",
|
||||||
|
memberProgress: "Member Progress",
|
||||||
|
noProgress: "No progress data yet",
|
||||||
|
noProgressHint: "Members will show progress once they start reading.",
|
||||||
|
},
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export default enUS;
|
export default enUS;
|
||||||
|
|||||||
@@ -247,6 +247,54 @@ const esES: Locale = {
|
|||||||
home: "Inicio",
|
home: "Inicio",
|
||||||
bookmarksNotes: "Marcadores y notas",
|
bookmarksNotes: "Marcadores y notas",
|
||||||
},
|
},
|
||||||
|
groups: {
|
||||||
|
title: "Grupos de Lectura",
|
||||||
|
createGroup: "Crear Grupo",
|
||||||
|
create: "Crear",
|
||||||
|
cancel: "Cancelar",
|
||||||
|
groupName: "Nombre del Grupo",
|
||||||
|
groupNamePlaceholder: "Ingresa el nombre del grupo",
|
||||||
|
description: "Descripción",
|
||||||
|
descriptionPlaceholder: "¿De qué trata este grupo?",
|
||||||
|
optional: "Opcional",
|
||||||
|
noGroups: "Aún no hay grupos",
|
||||||
|
noGroupsHint: "¡Crea un grupo de lectura para leer juntos!",
|
||||||
|
members: "Miembros",
|
||||||
|
admin: "Admin",
|
||||||
|
addMember: "Agregar Miembro",
|
||||||
|
memberIdPlaceholder: "Ingresa ID de usuario",
|
||||||
|
add: "Agregar",
|
||||||
|
remove: "Eliminar",
|
||||||
|
books: "Libros del Grupo",
|
||||||
|
uploadEpub: "Subir EPUB",
|
||||||
|
selectEbook: "Selecciona un EPUB para compartir con el grupo",
|
||||||
|
noEpubBooks: "No hay archivos EPUB subidos aún",
|
||||||
|
uploadFirst: "Sube un EPUB primero",
|
||||||
|
confirmUpload: "Confirmar Subida",
|
||||||
|
noBooks: "No hay libros en este grupo aún",
|
||||||
|
sections: "Secciones",
|
||||||
|
schedule: "Calendario",
|
||||||
|
progress: "Progreso",
|
||||||
|
detectSections: "Auto-Detectar Secciones",
|
||||||
|
mergeSections: "Fusionar Secciones",
|
||||||
|
selectSectionsHint: "Haz clic en las secciones para seleccionar y fusionar",
|
||||||
|
merge: "Fusionar",
|
||||||
|
clear: "Limpiar",
|
||||||
|
split: "Dividir",
|
||||||
|
splitInto: "Dividir en",
|
||||||
|
parts: "partes",
|
||||||
|
splitBtn: "Dividir",
|
||||||
|
noSections: "No se detectaron secciones",
|
||||||
|
noSectionsHint: 'Haz clic en "Auto-Detectar Secciones" para analizar los capítulos del EPUB.',
|
||||||
|
readingSchedule: "Calendario de Lectura",
|
||||||
|
generateSchedule: "Generar Calendario",
|
||||||
|
noSchedule: "No hay calendario generado",
|
||||||
|
noScheduleHint: "Detecta secciones primero, luego genera un calendario de lectura para tu grupo.",
|
||||||
|
meeting: "Reunión",
|
||||||
|
memberProgress: "Progreso de Miembros",
|
||||||
|
noProgress: "Sin datos de progreso",
|
||||||
|
noProgressHint: "Los miembros mostrarán progreso cuando comiencen a leer.",
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export default esES;
|
export default esES;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { useNavigate } from "react-router-dom";
|
|||||||
import { useTranslation } from "react-i18n-lite";
|
import { useTranslation } from "react-i18n-lite";
|
||||||
import { booksApi } from "../api/books";
|
import { booksApi } from "../api/books";
|
||||||
import { getApiErrorMessage } from "../api/errors";
|
import { getApiErrorMessage } from "../api/errors";
|
||||||
|
import { SimpleFormPageLayout } from "../components/layout/SimpleFormPageLayout";
|
||||||
|
|
||||||
export function AddBookPage() {
|
export function AddBookPage() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -33,11 +34,7 @@ export function AddBookPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
<SimpleFormPageLayout title={t("addBook.title")} onBack={() => navigate("/")}>
|
||||||
<header style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24, padding: "16px 0", borderBottom: "1px solid #eee" }}>
|
|
||||||
<button onClick={() => navigate("/")} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>← {t("common.back")}</button>
|
|
||||||
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>{t("addBook.title")}</h1>
|
|
||||||
</header>
|
|
||||||
<form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
|
<form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
|
||||||
{error && <div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14 }}>{error}</div>}
|
{error && <div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14 }}>{error}</div>}
|
||||||
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||||
@@ -55,6 +52,6 @@ export function AddBookPage() {
|
|||||||
</div>
|
</div>
|
||||||
<button type="submit" disabled={uploading} style={{ padding: "12px 24px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 16, fontWeight: 600, cursor: "pointer", opacity: uploading ? 0.6 : 1, marginTop: 8 }}>{uploading ? t("addBook.uploading") : t("addBook.upload")}</button>
|
<button type="submit" disabled={uploading} style={{ padding: "12px 24px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 16, fontWeight: 600, cursor: "pointer", opacity: uploading ? 0.6 : 1, marginTop: 8 }}>{uploading ? t("addBook.uploading") : t("addBook.upload")}</button>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</SimpleFormPageLayout>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,5 +56,7 @@ function AuthForm({ isLogin, onToggle }: { isLogin: boolean; onToggle: () => voi
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LoginPage({ onToggle }: { onToggle: () => void }) { return <AuthForm isLogin={true} onToggle={onToggle} />; }
|
export default function AuthPage() {
|
||||||
export function RegisterPage({ onToggle }: { onToggle: () => void }) { return <AuthForm isLogin={false} onToggle={onToggle} />; }
|
const [isLogin, setIsLogin] = useState(true);
|
||||||
|
return <AuthForm isLogin={isLogin} onToggle={() => setIsLogin((v) => !v)} />;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,426 @@
|
|||||||
|
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 { getApiErrorMessage } from "../api/errors";
|
||||||
|
import type {
|
||||||
|
GroupBookDetail,
|
||||||
|
ReadingSchedule,
|
||||||
|
Section,
|
||||||
|
MemberProgress,
|
||||||
|
} from "../types/group";
|
||||||
|
|
||||||
|
export function GroupBookPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { groupId, bookId } = useParams<{ groupId: string; bookId: string }>();
|
||||||
|
|
||||||
|
const [book, setBook] = useState<GroupBookDetail | null>(null);
|
||||||
|
const [sections, setSections] = useState<Section[]>([]);
|
||||||
|
const [schedules, setSchedules] = useState<ReadingSchedule[]>([]);
|
||||||
|
const [progress, setProgress] = useState<MemberProgress[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [tab, setTab] = useState<"sections" | "schedule" | "progress">("sections");
|
||||||
|
|
||||||
|
// Merge state
|
||||||
|
const [selectedForMerge, setSelectedForMerge] = useState<number[]>([]);
|
||||||
|
const [splitSectionId, setSplitSectionId] = useState<number | null>(null);
|
||||||
|
const [splitAt, setSplitAt] = useState(2);
|
||||||
|
|
||||||
|
const gId = Number(groupId);
|
||||||
|
const bId = Number(bookId);
|
||||||
|
|
||||||
|
const loadData = useCallback(async () => {
|
||||||
|
if (!gId || !bId) return;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const [bookData, schedData, progData] = await Promise.all([
|
||||||
|
groupsApi.getGroupBook(gId, bId),
|
||||||
|
groupsApi.getSchedule(gId, bId).catch(() => [] as ReadingSchedule[]),
|
||||||
|
groupsApi.getProgress(gId, bId).catch(() => [] as MemberProgress[]),
|
||||||
|
]);
|
||||||
|
setBook(bookData);
|
||||||
|
setSections(bookData.sections ?? []);
|
||||||
|
setSchedules(schedData);
|
||||||
|
setProgress(progData);
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to load book"));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [gId, bId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadData();
|
||||||
|
}, [loadData]);
|
||||||
|
|
||||||
|
const handleDetectSections = async () => {
|
||||||
|
if (!gId || !bId) return;
|
||||||
|
try {
|
||||||
|
const newSections = await groupsApi.detectSections(gId, bId);
|
||||||
|
setSections(newSections);
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to detect sections"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleMerge = async () => {
|
||||||
|
if (selectedForMerge.length < 2 || !gId || !bId) return;
|
||||||
|
try {
|
||||||
|
await groupsApi.adjustSections(gId, bId, {
|
||||||
|
operation: "merge",
|
||||||
|
section_ids: selectedForMerge,
|
||||||
|
});
|
||||||
|
setSelectedForMerge([]);
|
||||||
|
await loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to merge sections"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSplit = async () => {
|
||||||
|
if (!splitSectionId || !gId || !bId) return;
|
||||||
|
try {
|
||||||
|
await groupsApi.adjustSections(gId, bId, {
|
||||||
|
operation: "split",
|
||||||
|
section_ids: [splitSectionId],
|
||||||
|
split_at: splitAt,
|
||||||
|
});
|
||||||
|
setSplitSectionId(null);
|
||||||
|
await loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to split section"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleGenerateSchedule = async () => {
|
||||||
|
if (!gId || !bId) return;
|
||||||
|
try {
|
||||||
|
const newSched = await groupsApi.generateSchedule(gId, bId, 4);
|
||||||
|
setSchedules(newSched);
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to generate schedule"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleMergeSelect = (id: number) => {
|
||||||
|
setSelectedForMerge((prev) =>
|
||||||
|
prev.includes(id) ? prev.filter((s) => s !== id) : [...prev, id]
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatMinutes = (mins: number): string => {
|
||||||
|
if (mins < 60) return `${mins}m`;
|
||||||
|
const h = Math.floor(mins / 60);
|
||||||
|
const m = mins % 60;
|
||||||
|
return m > 0 ? `${h}h ${m}m` : `${h}h`;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div style={{ maxWidth: 800, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||||
|
<p style={{ textAlign: "center", color: "#888", padding: 40 }}>{t("common.loading")}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!book) {
|
||||||
|
return (
|
||||||
|
<div style={{ maxWidth: 800, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||||
|
<p style={{ textAlign: "center", color: "#e74c3c", padding: 40 }}>Book not found</p>
|
||||||
|
<button onClick={() => navigate(`/groups/${groupId}`)} style={{ display: "block", margin: "0 auto" }}>← Back</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ maxWidth: 800, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||||
|
{/* Header */}
|
||||||
|
<header style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 0", borderBottom: "1px solid #eee", marginBottom: 20 }}>
|
||||||
|
<div>
|
||||||
|
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>{book.title}</h1>
|
||||||
|
<p style={{ margin: 4, fontSize: 13, color: "#888" }}>
|
||||||
|
{book.ebook.author && `by ${book.ebook.author} · `}
|
||||||
|
{book.ebook.page_count} chapters · {book.ebook.format.toUpperCase()}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button onClick={() => navigate(`/groups/${groupId}`)} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>
|
||||||
|
← {t("common.back")}
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14, marginBottom: 16 }}>
|
||||||
|
{error}
|
||||||
|
<button onClick={() => setError(null)} style={{ marginLeft: 12, background: "none", border: "none", cursor: "pointer", fontWeight: 600 }}>✕</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div style={{ display: "flex", gap: 4, marginBottom: 20, background: "#eee", borderRadius: 8, padding: 4 }}>
|
||||||
|
{(["sections", "schedule", "progress"] as const).map((t) => (
|
||||||
|
<button
|
||||||
|
key={t}
|
||||||
|
onClick={() => setTab(t)}
|
||||||
|
style={{
|
||||||
|
flex: 1, padding: "10px 16px", borderRadius: 6, border: "none",
|
||||||
|
fontSize: 14, fontWeight: 600, cursor: "pointer",
|
||||||
|
background: tab === t ? "#fff" : "transparent",
|
||||||
|
color: tab === t ? "#1a1a2e" : "#888",
|
||||||
|
boxShadow: tab === t ? "0 1px 4px rgba(0,0,0,0.1)" : "none",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t === "sections" ? t("groups.sections") : t === "schedule" ? t("groups.schedule") : t("groups.progress")}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Sections Tab */}
|
||||||
|
{tab === "sections" && (
|
||||||
|
<section>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
|
||||||
|
<h2 style={{ fontSize: 18, fontWeight: 600, color: "#1a1a2e", margin: 0 }}>
|
||||||
|
{sections.length} {t("groups.sections")}
|
||||||
|
</h2>
|
||||||
|
<div style={{ display: "flex", gap: 8 }}>
|
||||||
|
<button
|
||||||
|
onClick={handleDetectSections}
|
||||||
|
style={{ padding: "8px 16px", borderRadius: 6, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
{t("groups.detectSections")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Merge controls */}
|
||||||
|
<div style={{ background: "#fff", padding: 16, borderRadius: 10, marginBottom: 12, boxShadow: "0 1px 4px rgba(0,0,0,0.06)" }}>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
|
||||||
|
<span style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>{t("groups.mergeSections")}:</span>
|
||||||
|
<span style={{ fontSize: 13, color: "#888" }}>
|
||||||
|
{selectedForMerge.length === 0
|
||||||
|
? t("groups.selectSectionsHint")
|
||||||
|
: `${selectedForMerge.length} selected`}
|
||||||
|
</span>
|
||||||
|
{selectedForMerge.length >= 2 && (
|
||||||
|
<button
|
||||||
|
onClick={handleMerge}
|
||||||
|
style={{ padding: "6px 14px", borderRadius: 6, border: "none", background: "#27ae60", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
{t("groups.merge")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{selectedForMerge.length > 0 && (
|
||||||
|
<button
|
||||||
|
onClick={() => setSelectedForMerge([])}
|
||||||
|
style={{ padding: "6px 12px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", fontSize: 13, cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
{t("groups.clear")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{sections.length === 0 ? (
|
||||||
|
<div style={{ textAlign: "center", padding: 40, color: "#888" }}>
|
||||||
|
<p style={{ fontSize: 16 }}>{t("groups.noSections")}</p>
|
||||||
|
<p style={{ fontSize: 14 }}>{t("groups.noSectionsHint")}</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
|
||||||
|
{sections.map((section) => (
|
||||||
|
<div
|
||||||
|
key={section.id}
|
||||||
|
style={{
|
||||||
|
background: selectedForMerge.includes(section.id) ? "#e8f0fe" : "#fff",
|
||||||
|
border: selectedForMerge.includes(section.id) ? "2px solid #1a1a2e" : "1px solid #eee",
|
||||||
|
padding: 16, borderRadius: 10, cursor: "pointer",
|
||||||
|
boxShadow: "0 1px 4px rgba(0,0,0,0.06)",
|
||||||
|
transition: "all 0.15s",
|
||||||
|
}}
|
||||||
|
onClick={() => toggleMergeSelect(section.id)}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
|
||||||
|
<div style={{ flex: 1 }}>
|
||||||
|
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
|
||||||
|
<span style={{
|
||||||
|
background: "#1a1a2e", color: "#fff", borderRadius: 20,
|
||||||
|
width: 26, height: 26, display: "flex", alignItems: "center", justifyContent: "center",
|
||||||
|
fontSize: 13, fontWeight: 700, flexShrink: 0,
|
||||||
|
}}>
|
||||||
|
{section.order}
|
||||||
|
</span>
|
||||||
|
<h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, color: "#1a1a2e" }}>{section.title}</h3>
|
||||||
|
</div>
|
||||||
|
<p style={{ margin: "6px 0 0 34px", fontSize: 13, color: "#888" }}>
|
||||||
|
Ch. {section.start_chapter_index}–{section.end_chapter_index - 1} · ~{formatMinutes(section.estimated_reading_minutes)} reading time
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
setSplitSectionId(splitSectionId === section.id ? null : section.id);
|
||||||
|
}}
|
||||||
|
style={{
|
||||||
|
padding: "4px 10px", borderRadius: 4, border: "1px solid #ddd",
|
||||||
|
background: splitSectionId === section.id ? "#1a1a2e" : "#fff",
|
||||||
|
color: splitSectionId === section.id ? "#fff" : "#666",
|
||||||
|
fontSize: 12, cursor: "pointer", flexShrink: 0,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t("groups.split")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{splitSectionId === section.id && (
|
||||||
|
<div
|
||||||
|
style={{ marginTop: 10, padding: 10, background: "#f8f9fa", borderRadius: 6, display: "flex", alignItems: "center", gap: 8 }}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
<span style={{ fontSize: 13 }}>{t("groups.splitInto")}</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
value={splitAt}
|
||||||
|
min={2}
|
||||||
|
max={10}
|
||||||
|
onChange={(e) => setSplitAt(Number(e.target.value))}
|
||||||
|
style={{ width: 50, padding: "4px 8px", borderRadius: 4, border: "1px solid #ddd", fontSize: 13, textAlign: "center" }}
|
||||||
|
/>
|
||||||
|
<span style={{ fontSize: 13 }}>{t("groups.parts")}</span>
|
||||||
|
<button
|
||||||
|
onClick={handleSplit}
|
||||||
|
style={{ padding: "4px 12px", borderRadius: 4, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 12, cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
{t("groups.splitBtn")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Schedule Tab */}
|
||||||
|
{tab === "schedule" && (
|
||||||
|
<section>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
|
||||||
|
<h2 style={{ fontSize: 18, fontWeight: 600, color: "#1a1a2e", margin: 0 }}>
|
||||||
|
{t("groups.readingSchedule")}
|
||||||
|
</h2>
|
||||||
|
<button
|
||||||
|
onClick={handleGenerateSchedule}
|
||||||
|
style={{ padding: "8px 16px", borderRadius: 6, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
{t("groups.generateSchedule")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{schedules.length === 0 ? (
|
||||||
|
<div style={{ textAlign: "center", padding: 40, color: "#888" }}>
|
||||||
|
<p style={{ fontSize: 16 }}>{t("groups.noSchedule")}</p>
|
||||||
|
<p style={{ fontSize: 14 }}>{t("groups.noScheduleHint")}</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
|
||||||
|
{schedules.map((s) => (
|
||||||
|
<div
|
||||||
|
key={s.id}
|
||||||
|
style={{ background: "#fff", padding: 20, borderRadius: 12, boxShadow: "0 2px 8px rgba(0,0,0,0.06)" }}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
|
||||||
|
<div>
|
||||||
|
<h3 style={{ margin: 0, fontSize: 17, fontWeight: 700, color: "#1a1a2e" }}>
|
||||||
|
{t("groups.meeting")} {s.meeting_number}
|
||||||
|
</h3>
|
||||||
|
<p style={{ margin: "4px 0 0", fontSize: 13, color: "#888" }}>
|
||||||
|
Week of {new Date(s.week_date).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span style={{
|
||||||
|
background: "#f0f0f0", padding: "6px 12px", borderRadius: 20,
|
||||||
|
fontSize: 13, fontWeight: 600, color: "#555",
|
||||||
|
}}>
|
||||||
|
{s.section_details.reduce((sum, sec) => sum + sec.estimated_reading_minutes, 0) > 0
|
||||||
|
? `~${formatMinutes(s.section_details.reduce((sum, sec) => sum + sec.estimated_reading_minutes, 0))}`
|
||||||
|
: ""}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||||
|
{s.section_details.map((sec) => (
|
||||||
|
<div
|
||||||
|
key={sec.id}
|
||||||
|
style={{
|
||||||
|
display: "flex", alignItems: "center", gap: 10, padding: "8px 12px",
|
||||||
|
background: "#f8f9fa", borderRadius: 6, fontSize: 14,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{
|
||||||
|
background: "#1a1a2e", color: "#fff", borderRadius: 12,
|
||||||
|
width: 22, height: 22, display: "flex", alignItems: "center", justifyContent: "center",
|
||||||
|
fontSize: 11, fontWeight: 700, flexShrink: 0,
|
||||||
|
}}>
|
||||||
|
{sec.order}
|
||||||
|
</span>
|
||||||
|
<span style={{ flex: 1 }}>{sec.title}</span>
|
||||||
|
<span style={{ fontSize: 12, color: "#999" }}>{formatMinutes(sec.estimated_reading_minutes)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Progress Tab */}
|
||||||
|
{tab === "progress" && (
|
||||||
|
<section>
|
||||||
|
<h2 style={{ fontSize: 18, fontWeight: 600, color: "#1a1a2e", margin: "0 0 16px" }}>
|
||||||
|
{t("groups.memberProgress")}
|
||||||
|
</h2>
|
||||||
|
{progress.length === 0 ? (
|
||||||
|
<div style={{ textAlign: "center", padding: 40, color: "#888" }}>
|
||||||
|
<p style={{ fontSize: 16 }}>{t("groups.noProgress")}</p>
|
||||||
|
<p style={{ fontSize: 14 }}>{t("groups.noProgressHint")}</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
|
||||||
|
{progress.map((p) => {
|
||||||
|
const totalSections = sections.length;
|
||||||
|
const completed = p.completed_sections.length;
|
||||||
|
const pct = totalSections > 0 ? Math.round((completed / totalSections) * 100) : 0;
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={p.id}
|
||||||
|
style={{ background: "#fff", padding: 16, borderRadius: 10, boxShadow: "0 1px 4px rgba(0,0,0,0.06)" }}
|
||||||
|
>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
|
||||||
|
<span style={{ fontSize: 15, fontWeight: 600 }}>{p.user_email}</span>
|
||||||
|
<span style={{ fontSize: 13, color: "#888" }}>{completed}/{totalSections} · {pct}%</span>
|
||||||
|
</div>
|
||||||
|
<div style={{ height: 6, background: "#eee", borderRadius: 3, overflow: "hidden" }}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
height: "100%", borderRadius: 3,
|
||||||
|
background: "linear-gradient(90deg, #27ae60, #2ecc71)",
|
||||||
|
width: `${pct}%`, transition: "width 0.3s",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{p.current_section_title && (
|
||||||
|
<p style={{ margin: "8px 0 0", fontSize: 13, color: "#888" }}>
|
||||||
|
Currently: {p.current_section_title}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,300 @@
|
|||||||
|
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 { booksApi } from "../api/books";
|
||||||
|
import { getApiErrorMessage } from "../api/errors";
|
||||||
|
import type { ReadingGroupDetail, GroupBook, GroupBookDetail } from "../types/group";
|
||||||
|
import type { EBookListItem } from "../types/book";
|
||||||
|
|
||||||
|
export function GroupDetailPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { groupId } = useParams<{ groupId: string }>();
|
||||||
|
const [group, setGroup] = useState<ReadingGroupDetail | null>(null);
|
||||||
|
const [books, setBooks] = useState<GroupBook[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Upload state
|
||||||
|
const [showUpload, setShowUpload] = useState(false);
|
||||||
|
const [ebooks, setEbooks] = useState<EBookListItem[]>([]);
|
||||||
|
const [selectedEbookId, setSelectedEbookId] = useState<number | null>(null);
|
||||||
|
const [uploading, setUploading] = useState(false);
|
||||||
|
|
||||||
|
// Add member state
|
||||||
|
const [showAddMember, setShowAddMember] = useState(false);
|
||||||
|
const [memberEmail, setMemberEmail] = useState("");
|
||||||
|
const [adding, setAdding] = useState(false);
|
||||||
|
|
||||||
|
const id = Number(groupId);
|
||||||
|
|
||||||
|
const loadData = useCallback(async () => {
|
||||||
|
if (!id) return;
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const [groupData, bookData] = await Promise.all([
|
||||||
|
groupsApi.getGroup(id),
|
||||||
|
groupsApi.listGroupBooks(id),
|
||||||
|
]);
|
||||||
|
setGroup(groupData);
|
||||||
|
setBooks(bookData);
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to load group"));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [id]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadData();
|
||||||
|
}, [loadData]);
|
||||||
|
|
||||||
|
const handleUploadClick = async () => {
|
||||||
|
setShowUpload(true);
|
||||||
|
try {
|
||||||
|
const ebookList = await booksApi.getEBooks();
|
||||||
|
setEbooks(ebookList.filter((e) => e.format === "epub"));
|
||||||
|
} catch {
|
||||||
|
// Ebook list fetch failed silently
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleUpload = async () => {
|
||||||
|
if (!selectedEbookId || !id) return;
|
||||||
|
setUploading(true);
|
||||||
|
try {
|
||||||
|
const created = await groupsApi.createGroupBook(id, { ebook_id: selectedEbookId });
|
||||||
|
setShowUpload(false);
|
||||||
|
setSelectedEbookId(null);
|
||||||
|
await loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to upload book to group"));
|
||||||
|
} finally {
|
||||||
|
setUploading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleAddMember = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!memberEmail.trim() || !id) return;
|
||||||
|
setAdding(true);
|
||||||
|
try {
|
||||||
|
// Note: In a real implementation, we'd look up user by email.
|
||||||
|
// For now this requires user_id. Email lookup would be an enhancement.
|
||||||
|
await groupsApi.addMember(id, { user_id: Number(memberEmail) });
|
||||||
|
setShowAddMember(false);
|
||||||
|
setMemberEmail("");
|
||||||
|
await loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to add member. Please use a valid user ID."));
|
||||||
|
} finally {
|
||||||
|
setAdding(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemoveMember = async (userId: number) => {
|
||||||
|
if (!id) return;
|
||||||
|
try {
|
||||||
|
await groupsApi.removeMember(id, { user_id: userId });
|
||||||
|
await loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to remove member"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div style={{ maxWidth: 700, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||||
|
<p style={{ textAlign: "center", color: "#888", padding: 40 }}>{t("common.loading")}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!group) {
|
||||||
|
return (
|
||||||
|
<div style={{ maxWidth: 700, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||||
|
<p style={{ textAlign: "center", color: "#e74c3c", padding: 40 }}>Group not found</p>
|
||||||
|
<button onClick={() => navigate("/groups")} style={{ display: "block", margin: "0 auto" }}>← Back to Groups</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ maxWidth: 700, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||||
|
<header style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 0", borderBottom: "1px solid #eee", marginBottom: 20 }}>
|
||||||
|
<div>
|
||||||
|
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>{group.name}</h1>
|
||||||
|
{group.description && <p style={{ margin: "4px 0 0", fontSize: 14, color: "#666" }}>{group.description}</p>}
|
||||||
|
</div>
|
||||||
|
<button onClick={() => navigate("/groups")} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>
|
||||||
|
← {t("common.back")}
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14, marginBottom: 16 }}>
|
||||||
|
{error}
|
||||||
|
<button onClick={() => setError(null)} style={{ marginLeft: 12, background: "none", border: "none", cursor: "pointer", fontWeight: 600 }}>✕</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Members Section */}
|
||||||
|
<section style={{ background: "#fff", padding: 20, borderRadius: 12, marginBottom: 20, boxShadow: "0 2px 8px rgba(0,0,0,0.06)" }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
|
||||||
|
<h2 style={{ fontSize: 18, fontWeight: 600, color: "#1a1a2e", margin: 0 }}>{t("groups.members")} ({group.members.length})</h2>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowAddMember(!showAddMember)}
|
||||||
|
style={{ padding: "6px 14px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 13 }}
|
||||||
|
>
|
||||||
|
{showAddMember ? t("groups.cancel") : `+ ${t("groups.addMember")}`}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{showAddMember && (
|
||||||
|
<form onSubmit={handleAddMember} style={{ display: "flex", gap: 8, marginBottom: 12 }}>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={memberEmail}
|
||||||
|
onChange={(e) => setMemberEmail(e.target.value)}
|
||||||
|
placeholder={t("groups.memberIdPlaceholder")}
|
||||||
|
style={{ flex: 1, padding: "8px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 14, outline: "none" }}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={adding}
|
||||||
|
style={{ padding: "8px 16px", borderRadius: 6, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 14, cursor: "pointer", opacity: adding ? 0.6 : 1 }}
|
||||||
|
>
|
||||||
|
{t("groups.add")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
|
||||||
|
{group.members.map((m) => (
|
||||||
|
<div key={m.id} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "8px 0", borderBottom: "1px solid #f0f0f0" }}>
|
||||||
|
<div>
|
||||||
|
<span style={{ fontSize: 14, fontWeight: 500 }}>{m.user_email}</span>
|
||||||
|
<span style={{ marginLeft: 8, fontSize: 12, color: m.role === "admin" ? "#e67e22" : "#999", background: m.role === "admin" ? "#fef3e2" : "#f0f0f0", padding: "2px 8px", borderRadius: 4 }}>
|
||||||
|
{m.role}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{m.role !== "admin" && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleRemoveMember(m.user)}
|
||||||
|
style={{ background: "none", border: "none", color: "#e74c3c", cursor: "pointer", fontSize: 13 }}
|
||||||
|
>
|
||||||
|
{t("groups.remove")}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Books Section */}
|
||||||
|
<section style={{ background: "#fff", padding: 20, borderRadius: 12, boxShadow: "0 2px 8px rgba(0,0,0,0.06)" }}>
|
||||||
|
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 12 }}>
|
||||||
|
<h2 style={{ fontSize: 18, fontWeight: 600, color: "#1a1a2e", margin: 0 }}>{t("groups.books")} ({books.length})</h2>
|
||||||
|
<button
|
||||||
|
onClick={handleUploadClick}
|
||||||
|
style={{ padding: "8px 18px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 14, fontWeight: 600, cursor: "pointer" }}
|
||||||
|
>
|
||||||
|
{t("groups.uploadEpub")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showUpload && (
|
||||||
|
<div style={{ background: "#f8f9fa", padding: 16, borderRadius: 8, marginBottom: 16 }}>
|
||||||
|
<h3 style={{ fontSize: 15, fontWeight: 600, margin: "0 0 12px" }}>{t("groups.selectEbook")}</h3>
|
||||||
|
{ebooks.length === 0 ? (
|
||||||
|
<div style={{ textAlign: "center", padding: 20, color: "#888" }}>
|
||||||
|
<p>{t("groups.noEpubBooks")}</p>
|
||||||
|
<button onClick={() => navigate("/add")} style={{ marginTop: 8, padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 13 }}>
|
||||||
|
{t("groups.uploadFirst")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div>
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 12, maxHeight: 200, overflowY: "auto" }}>
|
||||||
|
{ebooks.map((eb) => (
|
||||||
|
<label
|
||||||
|
key={eb.id}
|
||||||
|
style={{
|
||||||
|
display: "flex", alignItems: "center", gap: 10, padding: "10px 12px",
|
||||||
|
borderRadius: 8, cursor: "pointer", fontSize: 14,
|
||||||
|
background: selectedEbookId === eb.id ? "#e8f0fe" : "#fff",
|
||||||
|
border: selectedEbookId === eb.id ? "2px solid #1a1a2e" : "1px solid #eee",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="radio"
|
||||||
|
name="ebook"
|
||||||
|
value={eb.id}
|
||||||
|
checked={selectedEbookId === eb.id}
|
||||||
|
onChange={() => setSelectedEbookId(eb.id)}
|
||||||
|
style={{ accentColor: "#1a1a2e" }}
|
||||||
|
/>
|
||||||
|
<div>
|
||||||
|
<strong>{eb.title}</strong>
|
||||||
|
{eb.author && <span style={{ color: "#888", marginLeft: 8 }}>by {eb.author}</span>}
|
||||||
|
<span style={{ marginLeft: 8, fontSize: 12, color: "#aaa" }}>({eb.filename})</span>
|
||||||
|
</div>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div style={{ display: "flex", gap: 8 }}>
|
||||||
|
<button
|
||||||
|
onClick={handleUpload}
|
||||||
|
disabled={!selectedEbookId || uploading}
|
||||||
|
style={{ padding: "10px 20px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 14, fontWeight: 600, cursor: uploading ? "default" : "pointer", opacity: uploading ? 0.6 : 1 }}
|
||||||
|
>
|
||||||
|
{uploading ? t("common.loading") : t("groups.confirmUpload")}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => setShowUpload(false)}
|
||||||
|
style={{ padding: "10px 20px", borderRadius: 8, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}
|
||||||
|
>
|
||||||
|
{t("groups.cancel")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{books.length === 0 ? (
|
||||||
|
<p style={{ textAlign: "center", color: "#888", padding: 30 }}>{t("groups.noBooks")}</p>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
|
||||||
|
{books.map((book) => (
|
||||||
|
<div
|
||||||
|
key={book.id}
|
||||||
|
onClick={() => navigate(`/groups/${groupId}/books/${book.id}`)}
|
||||||
|
style={{
|
||||||
|
display: "flex", justifyContent: "space-between", alignItems: "center",
|
||||||
|
padding: 16, borderRadius: 10, cursor: "pointer", transition: "background 0.2s",
|
||||||
|
background: book.status === "active" ? "#f0faf0" : "#fafafa",
|
||||||
|
border: book.status === "active" ? "2px solid #27ae60" : "1px solid #eee",
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e) => (e.currentTarget.style.background = book.status === "active" ? "#e8f5e9" : "#f5f5f5")}
|
||||||
|
onMouseLeave={(e) => (e.currentTarget.style.background = book.status === "active" ? "#f0faf0" : "#fafafa")}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<h3 style={{ margin: 0, fontSize: 16, fontWeight: 600, color: "#1a1a2e" }}>
|
||||||
|
{book.title}
|
||||||
|
{book.status === "active" && (
|
||||||
|
<span style={{ marginLeft: 8, fontSize: 11, color: "#27ae60", background: "#e8f5e9", padding: "2px 8px", borderRadius: 4 }}>Active</span>
|
||||||
|
)}
|
||||||
|
</h3>
|
||||||
|
<p style={{ margin: "4px 0 0", fontSize: 13, color: "#888" }}>
|
||||||
|
{book.section_count} sections · {book.ebook.page_count} chapters · uploaded by {book.uploaded_by_email}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span style={{ fontSize: 20, color: "#ccc" }}>→</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
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 { getApiErrorMessage } from "../api/errors";
|
||||||
|
import type { ReadingGroup } from "../types/group";
|
||||||
|
|
||||||
|
export function GroupsPage() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const [groups, setGroups] = useState<ReadingGroup[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [showCreate, setShowCreate] = useState(false);
|
||||||
|
const [newName, setNewName] = useState("");
|
||||||
|
const [newDesc, setNewDesc] = useState("");
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
|
||||||
|
const loadGroups = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const data = await groupsApi.listGroups();
|
||||||
|
setGroups(data);
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to load groups"));
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadGroups();
|
||||||
|
}, [loadGroups]);
|
||||||
|
|
||||||
|
const handleCreate = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!newName.trim()) return;
|
||||||
|
setCreating(true);
|
||||||
|
try {
|
||||||
|
await groupsApi.createGroup({ name: newName.trim(), description: newDesc.trim() });
|
||||||
|
setShowCreate(false);
|
||||||
|
setNewName("");
|
||||||
|
setNewDesc("");
|
||||||
|
await loadGroups();
|
||||||
|
} catch (err) {
|
||||||
|
setError(getApiErrorMessage(err, "Failed to create group"));
|
||||||
|
} finally {
|
||||||
|
setCreating(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ maxWidth: 700, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||||
|
<header style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "16px 0", borderBottom: "1px solid #eee", marginBottom: 20 }}>
|
||||||
|
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>{t("groups.title")}</h1>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => navigate("/")}
|
||||||
|
style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}
|
||||||
|
>
|
||||||
|
← {t("common.back")}
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14, marginBottom: 16 }}>
|
||||||
|
{error}
|
||||||
|
<button onClick={() => setError(null)} style={{ marginLeft: 12, background: "none", border: "none", cursor: "pointer", fontWeight: 600 }}>✕</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div style={{ marginBottom: 20 }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowCreate(!showCreate)}
|
||||||
|
style={{
|
||||||
|
padding: "12px 24px", borderRadius: 8, border: "none",
|
||||||
|
background: "#1a1a2e", color: "#fff", fontSize: 15, fontWeight: 600, cursor: "pointer",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{showCreate ? t("groups.cancel") : t("groups.createGroup")}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showCreate && (
|
||||||
|
<form onSubmit={handleCreate} style={{
|
||||||
|
background: "#fff", padding: 20, borderRadius: 12, marginBottom: 24,
|
||||||
|
boxShadow: "0 2px 8px rgba(0,0,0,0.06)", display: "flex", flexDirection: "column", gap: 14,
|
||||||
|
}}>
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||||
|
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>{t("groups.groupName")}</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={newName}
|
||||||
|
onChange={(e) => setNewName(e.target.value)}
|
||||||
|
placeholder={t("groups.groupNamePlaceholder")}
|
||||||
|
style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 16, outline: "none" }}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||||
|
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>{t("groups.description")} ({t("common.optional")})</label>
|
||||||
|
<textarea
|
||||||
|
value={newDesc}
|
||||||
|
onChange={(e) => setNewDesc(e.target.value)}
|
||||||
|
placeholder={t("groups.descriptionPlaceholder")}
|
||||||
|
rows={3}
|
||||||
|
style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 15, outline: "none", resize: "vertical" }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={creating || !newName.trim()}
|
||||||
|
style={{
|
||||||
|
padding: "10px 20px", borderRadius: 8, border: "none",
|
||||||
|
background: "#1a1a2e", color: "#fff", fontSize: 15, fontWeight: 600,
|
||||||
|
cursor: creating ? "default" : "pointer", opacity: creating ? 0.6 : 1, alignSelf: "flex-start",
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{creating ? t("common.loading") : t("groups.create")}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{loading ? (
|
||||||
|
<p style={{ textAlign: "center", color: "#888", padding: 40 }}>{t("common.loading")}</p>
|
||||||
|
) : groups.length === 0 ? (
|
||||||
|
<div style={{ textAlign: "center", padding: 40, color: "#888" }}>
|
||||||
|
<p style={{ fontSize: 16, marginBottom: 8 }}>{t("groups.noGroups")}</p>
|
||||||
|
<p style={{ fontSize: 14 }}>{t("groups.noGroupsHint")}</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
|
||||||
|
{groups.map((group) => (
|
||||||
|
<div
|
||||||
|
key={group.id}
|
||||||
|
onClick={() => navigate(`/groups/${group.id}`)}
|
||||||
|
style={{
|
||||||
|
background: "#fff", padding: 20, borderRadius: 12, cursor: "pointer",
|
||||||
|
boxShadow: "0 2px 8px rgba(0,0,0,0.06)", transition: "box-shadow 0.2s",
|
||||||
|
display: "flex", justifyContent: "space-between", alignItems: "center",
|
||||||
|
}}
|
||||||
|
onMouseEnter={(e) => (e.currentTarget.style.boxShadow = "0 4px 16px rgba(0,0,0,0.1)")}
|
||||||
|
onMouseLeave={(e) => (e.currentTarget.style.boxShadow = "0 2px 8px rgba(0,0,0,0.06)")}
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<h3 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: "#1a1a2e" }}>{group.name}</h3>
|
||||||
|
{group.description && (
|
||||||
|
<p style={{ margin: "6px 0 0", fontSize: 14, color: "#666" }}>{group.description}</p>
|
||||||
|
)}
|
||||||
|
<p style={{ margin: "8px 0 0", fontSize: 13, color: "#999" }}>
|
||||||
|
{group.member_count} {t("groups.members")} · {t("groups.admin")}: {group.admin_email}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span style={{ fontSize: 20, color: "#ccc" }}>→</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -57,7 +57,6 @@ export function LibraryPage() {
|
|||||||
const [filters, setFilters] = useState<FilterState>({ genre: "", author: "", reading_status: "" });
|
const [filters, setFilters] = useState<FilterState>({ genre: "", author: "", reading_status: "" });
|
||||||
const [genres, setGenres] = useState<string[]>([]);
|
const [genres, setGenres] = useState<string[]>([]);
|
||||||
const [authors, setAuthors] = useState<string[]>([]);
|
const [authors, setAuthors] = useState<string[]>([]);
|
||||||
const [totalCount, setTotalCount] = useState(0);
|
|
||||||
const [showFilters, setShowFilters] = useState(false);
|
const [showFilters, setShowFilters] = useState(false);
|
||||||
const [showSuggestions, setShowSuggestions] = useState(false);
|
const [showSuggestions, setShowSuggestions] = useState(false);
|
||||||
const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
|
const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
|
||||||
@@ -95,11 +94,9 @@ export function LibraryPage() {
|
|||||||
items = items.filter((b) => b.reading_status === params.reading_status);
|
items = items.filter((b) => b.reading_status === params.reading_status);
|
||||||
}
|
}
|
||||||
setBooks(items);
|
setBooks(items);
|
||||||
setTotalCount(items.length);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setError(err instanceof Error ? err.message : t("library.loadFailed"));
|
setError(err instanceof Error ? err.message : t("library.loadFailed"));
|
||||||
setBooks([]);
|
setBooks([]);
|
||||||
setTotalCount(0);
|
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -169,7 +166,6 @@ export function LibraryPage() {
|
|||||||
refreshFilterOptions(next);
|
refreshFilterOptions(next);
|
||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
setTotalCount((count) => Math.max(0, count - 1));
|
|
||||||
}, [refreshFilterOptions]);
|
}, [refreshFilterOptions]);
|
||||||
|
|
||||||
const handleBookContextMenu = useCallback((e: React.MouseEvent, book: LibraryBook) => {
|
const handleBookContextMenu = useCallback((e: React.MouseEvent, book: LibraryBook) => {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18n-lite";
|
|||||||
import { booksApi } from "../api/books";
|
import { booksApi } from "../api/books";
|
||||||
import type { ReadingSettings } from "../types/book";
|
import type { ReadingSettings } from "../types/book";
|
||||||
import type { SupportedLanguage } from "../locales";
|
import type { SupportedLanguage } from "../locales";
|
||||||
|
import { SimpleFormPageLayout } from "../components/layout/SimpleFormPageLayout";
|
||||||
|
|
||||||
const BG_COLORS = [
|
const BG_COLORS = [
|
||||||
{ value: "#ffffff", labelKey: "settings.bgWhite" },
|
{ value: "#ffffff", labelKey: "settings.bgWhite" },
|
||||||
@@ -41,11 +42,7 @@ export function SettingsPage() {
|
|||||||
if (loading) return <div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}><p>{t("settings.loading")}</p></div>;
|
if (loading) return <div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}><p>{t("settings.loading")}</p></div>;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
<SimpleFormPageLayout title={t("settings.title")} onBack={() => navigate("/")}>
|
||||||
<header style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24, padding: "16px 0", borderBottom: "1px solid #eee" }}>
|
|
||||||
<button onClick={() => navigate("/")} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>← {t("common.back")}</button>
|
|
||||||
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>{t("settings.title")}</h1>
|
|
||||||
</header>
|
|
||||||
<div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
|
<div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
|
||||||
{error && <div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14 }}>{error}</div>}
|
{error && <div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14 }}>{error}</div>}
|
||||||
{success && <div style={{ background: "#d4edda", padding: 12, borderRadius: 6, color: "#155724", fontSize: 14 }}>{t("settings.saved")}</div>}
|
{success && <div style={{ background: "#d4edda", padding: 12, borderRadius: 6, color: "#155724", fontSize: 14 }}>{t("settings.saved")}</div>}
|
||||||
@@ -90,6 +87,6 @@ export function SettingsPage() {
|
|||||||
|
|
||||||
<button onClick={handleSave} disabled={saving} style={{ padding: "12px 24px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 16, fontWeight: 600, cursor: "pointer", opacity: saving ? 0.6 : 1, marginTop: 8 }}>{saving ? t("common.saving") : t("settings.saveSettings")}</button>
|
<button onClick={handleSave} disabled={saving} style={{ padding: "12px 24px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 16, fontWeight: 600, cursor: "pointer", opacity: saving ? 0.6 : 1, marginTop: 8 }}>{saving ? t("common.saving") : t("settings.saveSettings")}</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</SimpleFormPageLayout>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -102,11 +102,3 @@ export interface BookSearchParams {
|
|||||||
page?: number;
|
page?: number;
|
||||||
page_size?: number;
|
page_size?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const READING_STATUS_OPTIONS: { value: string; label: string }[] = [
|
|
||||||
{ value: "", label: "All Statuses" },
|
|
||||||
{ value: "want_to_read", label: "Want to Read" },
|
|
||||||
{ value: "reading", label: "Reading" },
|
|
||||||
{ value: "finished", label: "Finished" },
|
|
||||||
{ value: "dnf", label: "Did Not Finish" },
|
|
||||||
];
|
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
/** Types for reading groups, group books, sections, and schedules */
|
||||||
|
|
||||||
|
export interface ReadingGroup {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
admin: number;
|
||||||
|
admin_email: string;
|
||||||
|
member_count: number;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReadingGroupDetail {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
admin: number;
|
||||||
|
admin_email: string;
|
||||||
|
members: GroupMembership[];
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupMembership {
|
||||||
|
id: number;
|
||||||
|
user: number;
|
||||||
|
user_email: string;
|
||||||
|
user_username: string;
|
||||||
|
role: "admin" | "member";
|
||||||
|
joined_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupBook {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
status: "active" | "replaced";
|
||||||
|
ebook: {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
author: string;
|
||||||
|
filename: string;
|
||||||
|
format: string;
|
||||||
|
page_count: number;
|
||||||
|
file_size: number;
|
||||||
|
cover_image: string | null;
|
||||||
|
created_at: string;
|
||||||
|
};
|
||||||
|
uploaded_by: number;
|
||||||
|
uploaded_by_email: string;
|
||||||
|
section_count: number;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Section {
|
||||||
|
id: number;
|
||||||
|
title: string;
|
||||||
|
order: number;
|
||||||
|
start_chapter_index: number;
|
||||||
|
end_chapter_index: number;
|
||||||
|
estimated_reading_minutes: number;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupBookDetail extends GroupBook {
|
||||||
|
sections: Section[];
|
||||||
|
schedules: ReadingSchedule[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReadingSchedule {
|
||||||
|
id: number;
|
||||||
|
meeting_number: number;
|
||||||
|
week_date: string;
|
||||||
|
section_ids: number[];
|
||||||
|
section_details: Section[];
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MemberProgress {
|
||||||
|
id: number;
|
||||||
|
user: number;
|
||||||
|
user_email: string;
|
||||||
|
user_username: string;
|
||||||
|
current_section: number | null;
|
||||||
|
current_section_title: string | null;
|
||||||
|
completed_sections: number[];
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateGroupPayload {
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AddMemberPayload {
|
||||||
|
user_id: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateGroupBookPayload {
|
||||||
|
ebook_id: number;
|
||||||
|
title?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdjustSectionsPayload {
|
||||||
|
operation: "merge" | "split";
|
||||||
|
section_ids: number[];
|
||||||
|
split_at?: number;
|
||||||
|
}
|
||||||
@@ -1,29 +1,5 @@
|
|||||||
/** Core domain types for Cloud Reader */
|
/** Core domain types for Cloud Reader */
|
||||||
|
|
||||||
export interface User {
|
|
||||||
id: number;
|
|
||||||
email: string;
|
|
||||||
username: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Book {
|
|
||||||
id: string;
|
|
||||||
title: string;
|
|
||||||
author: string;
|
|
||||||
total_pages: number;
|
|
||||||
cover_image: string;
|
|
||||||
created_at: string;
|
|
||||||
updated_at: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface BookSummary {
|
|
||||||
id: string;
|
|
||||||
title: string;
|
|
||||||
author: string;
|
|
||||||
total_pages: number;
|
|
||||||
cover_image: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Bookmark {
|
export interface Bookmark {
|
||||||
id: string;
|
id: string;
|
||||||
ebook: number;
|
ebook: number;
|
||||||
@@ -39,17 +15,6 @@ export interface Bookmark {
|
|||||||
updated_at: string;
|
updated_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Note {
|
|
||||||
id: string;
|
|
||||||
book: string;
|
|
||||||
book_title: string;
|
|
||||||
page: number;
|
|
||||||
location_text: string;
|
|
||||||
content: string;
|
|
||||||
created_at: string;
|
|
||||||
updated_at: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CreateMarkerPayload {
|
export interface CreateMarkerPayload {
|
||||||
ebook: number;
|
ebook: number;
|
||||||
epub_cfi: string;
|
epub_cfi: string;
|
||||||
@@ -60,18 +25,6 @@ export interface CreateMarkerPayload {
|
|||||||
highlight_color?: string;
|
highlight_color?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @deprecated Legacy note create */
|
|
||||||
export interface CreateNotePayload {
|
|
||||||
book: string;
|
|
||||||
page: number;
|
|
||||||
location_text?: string;
|
|
||||||
content: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface UpdateNotePayload {
|
|
||||||
content: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface PaginatedResponse<T> {
|
export interface PaginatedResponse<T> {
|
||||||
count: number;
|
count: number;
|
||||||
next: string | null;
|
next: string | null;
|
||||||
@@ -79,11 +32,6 @@ export interface PaginatedResponse<T> {
|
|||||||
results: T[];
|
results: T[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TokenResponse {
|
|
||||||
access: string;
|
|
||||||
refresh: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface MarkerEntry {
|
export interface MarkerEntry {
|
||||||
id: string;
|
id: string;
|
||||||
ebook_id: number;
|
ebook_id: number;
|
||||||
|
|||||||
@@ -3,19 +3,6 @@
|
|||||||
* Reading view, settings, chapters, and progress types.
|
* Reading view, settings, chapters, and progress types.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export interface ChapterSummary {
|
|
||||||
id: number;
|
|
||||||
book: number;
|
|
||||||
title: string;
|
|
||||||
number: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ChapterDetail extends ChapterSummary {
|
|
||||||
content: string;
|
|
||||||
created_at: string;
|
|
||||||
updated_at: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ReadingSettings {
|
export interface ReadingSettings {
|
||||||
font_family: "sans-serif" | "serif" | "monospace";
|
font_family: "sans-serif" | "serif" | "monospace";
|
||||||
font_size: number;
|
font_size: number;
|
||||||
|
|||||||
@@ -55,7 +55,10 @@ export function ebookMatchesQuery(item: Pick<EbookLibraryItem, "title" | "author
|
|||||||
return item.subjects.some((s) => s.toLowerCase().includes(q));
|
return item.subjects.some((s) => s.toLowerCase().includes(q));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function collectGenresFromEbooks(ebooks: EBookListItem[], locale: SupportedLanguage): string[] {
|
export function collectGenresFromEbooks(
|
||||||
|
ebooks: Pick<EBookListItem, "subjects">[],
|
||||||
|
locale: SupportedLanguage,
|
||||||
|
): string[] {
|
||||||
const set = new Set<string>();
|
const set = new Set<string>();
|
||||||
for (const e of ebooks) {
|
for (const e of ebooks) {
|
||||||
for (const s of filterSubjectsByLocale(e.subjects ?? [], locale)) set.add(s);
|
for (const s of filterSubjectsByLocale(e.subjects ?? [], locale)) set.add(s);
|
||||||
@@ -63,7 +66,7 @@ export function collectGenresFromEbooks(ebooks: EBookListItem[], locale: Support
|
|||||||
return [...set].sort((a, b) => a.localeCompare(b, locale));
|
return [...set].sort((a, b) => a.localeCompare(b, locale));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function collectAuthorsFromEbooks(ebooks: EBookListItem[]): string[] {
|
export function collectAuthorsFromEbooks(ebooks: Pick<EBookListItem, "author">[]): string[] {
|
||||||
const set = new Set<string>();
|
const set = new Set<string>();
|
||||||
for (const e of ebooks) {
|
for (const e of ebooks) {
|
||||||
if (e.author?.trim()) set.add(e.author.trim());
|
if (e.author?.trim()) set.add(e.author.trim());
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ function annotationId(bookmarkId: string): string {
|
|||||||
return `bookmark-hl-${bookmarkId}`;
|
return `bookmark-hl-${bookmarkId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function applyBookmarkHighlight(
|
function applyBookmarkHighlight(
|
||||||
rendition: EpubRenditionWithHighlights,
|
rendition: EpubRenditionWithHighlights,
|
||||||
bookmark: BookmarkHighlight,
|
bookmark: BookmarkHighlight,
|
||||||
): void {
|
): void {
|
||||||
@@ -53,7 +53,7 @@ export function applyBookmarkHighlight(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function removeBookmarkHighlight(
|
function removeBookmarkHighlight(
|
||||||
rendition: EpubRenditionWithHighlights,
|
rendition: EpubRenditionWithHighlights,
|
||||||
bookmark: BookmarkHighlight,
|
bookmark: BookmarkHighlight,
|
||||||
): void {
|
): void {
|
||||||
|
|||||||
@@ -67,11 +67,6 @@ export function percentageFromCfi(rendition: EpubRendition, cfi: string): number
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function spineLength(rendition: EpubRendition): number {
|
|
||||||
const items = rendition.book?.spine?.spineItems;
|
|
||||||
return items?.length ?? 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Map nav/TOC href to a spine href epub.js can display. */
|
/** Map nav/TOC href to a spine href epub.js can display. */
|
||||||
export function resolveSpineHref(book: EpubBookForNav, href: string): string {
|
export function resolveSpineHref(book: EpubBookForNav, href: string): string {
|
||||||
const hashIndex = href.indexOf("#");
|
const hashIndex = href.indexOf("#");
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
export const FINISHED_PROGRESS_THRESHOLD = 99;
|
const FINISHED_PROGRESS_THRESHOLD = 99;
|
||||||
|
|
||||||
export type LibraryReadingStatus = "want_to_read" | "reading" | "finished";
|
export type LibraryReadingStatus = "want_to_read" | "reading" | "finished";
|
||||||
|
|
||||||
/** API may return progress as a number or numeric string. */
|
/** API may return progress as a number or numeric string. */
|
||||||
export function coerceProgressPercent(progress: unknown): number | null {
|
function coerceProgressPercent(progress: unknown): number | null {
|
||||||
if (progress == null || progress === "") return null;
|
if (progress == null || progress === "") return null;
|
||||||
const n = typeof progress === "number" ? progress : Number(progress);
|
const n = typeof progress === "number" ? progress : Number(progress);
|
||||||
if (!Number.isFinite(n)) return null;
|
if (!Number.isFinite(n)) return null;
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import { DEFAULT_BOOKMARK_HIGHLIGHT_COLOR } from "@/constants/bookmarkHighlightColors";
|
import { DEFAULT_BOOKMARK_HIGHLIGHT_COLOR } from "@/constants/bookmarkHighlightColors";
|
||||||
import { DEFAULT_BOOKMARK_HIGHLIGHT_COLOR } from "@/constants/bookmarkHighlightColors";
|
|
||||||
import type { Bookmark, MarkerEntry, MarkersByBook } from "@/types";
|
import type { Bookmark, MarkerEntry, MarkersByBook } from "@/types";
|
||||||
|
|
||||||
export function bookmarkToMarkerEntry(b: Bookmark): MarkerEntry {
|
export function bookmarkToMarkerEntry(b: Bookmark): MarkerEntry {
|
||||||
@@ -19,7 +18,14 @@ export function bookmarkToMarkerEntry(b: Bookmark): MarkerEntry {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sortMarkers(a: MarkerEntry, b: MarkerEntry): number {
|
function sortMarkers(a: MarkerEntry, b: MarkerEntry): number {
|
||||||
|
if (a.chapter_index !== b.chapter_index) {
|
||||||
|
return a.chapter_index - b.chapter_index;
|
||||||
|
}
|
||||||
|
return a.epub_cfi.localeCompare(b.epub_cfi);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortBookmarks(a: Bookmark, b: Bookmark): number {
|
||||||
if (a.chapter_index !== b.chapter_index) {
|
if (a.chapter_index !== b.chapter_index) {
|
||||||
return a.chapter_index - b.chapter_index;
|
return a.chapter_index - b.chapter_index;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,6 @@ export interface ParsedPdfAnchor {
|
|||||||
|
|
||||||
const PDF_ANCHOR_PREFIX = "pdf:v1:";
|
const PDF_ANCHOR_PREFIX = "pdf:v1:";
|
||||||
|
|
||||||
export function isPdfAnchor(anchor: string): boolean {
|
|
||||||
return anchor.startsWith(PDF_ANCHOR_PREFIX) || anchor.startsWith("pdf:page:");
|
|
||||||
}
|
|
||||||
|
|
||||||
export function parsePageHref(href: string): number | null {
|
export function parsePageHref(href: string): number | null {
|
||||||
const match = href.match(/^pdf:page:(\d+)$/);
|
const match = href.match(/^pdf:page:(\d+)$/);
|
||||||
if (!match) return null;
|
if (!match) return null;
|
||||||
@@ -38,7 +34,7 @@ export function parsePdfAnchor(anchor: string): ParsedPdfAnchor | null {
|
|||||||
|
|
||||||
const rectsMatch = anchor.match(/rects=([^;]+)/);
|
const rectsMatch = anchor.match(/rects=([^;]+)/);
|
||||||
let rects: PdfRect[] = [];
|
let rects: PdfRect[] = [];
|
||||||
if (rectsMatch) {
|
if (rectsMatch?.[1]) {
|
||||||
try {
|
try {
|
||||||
const parsed = JSON.parse(decodeURIComponent(rectsMatch[1])) as unknown;
|
const parsed = JSON.parse(decodeURIComponent(rectsMatch[1])) as unknown;
|
||||||
if (Array.isArray(parsed)) {
|
if (Array.isArray(parsed)) {
|
||||||
@@ -56,27 +52,3 @@ export function parsePdfAnchor(anchor: string): ParsedPdfAnchor | null {
|
|||||||
|
|
||||||
return { page, rects };
|
return { page, rects };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function rectsFromSelection(
|
|
||||||
range: Range,
|
|
||||||
pageElement: HTMLElement,
|
|
||||||
): PdfRect[] {
|
|
||||||
const pageRect = pageElement.getBoundingClientRect();
|
|
||||||
if (pageRect.width <= 0 || pageRect.height <= 0) return [];
|
|
||||||
|
|
||||||
const rects: PdfRect[] = [];
|
|
||||||
for (const clientRect of range.getClientRects()) {
|
|
||||||
if (clientRect.width <= 0 || clientRect.height <= 0) continue;
|
|
||||||
const x = (clientRect.left - pageRect.left) / pageRect.width;
|
|
||||||
const y = (clientRect.top - pageRect.top) / pageRect.height;
|
|
||||||
const w = clientRect.width / pageRect.width;
|
|
||||||
const h = clientRect.height / pageRect.height;
|
|
||||||
rects.push([
|
|
||||||
Math.max(0, Math.min(1, x)),
|
|
||||||
Math.max(0, Math.min(1, y)),
|
|
||||||
Math.max(0, Math.min(1, w)),
|
|
||||||
Math.max(0, Math.min(1, h)),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
return rects;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -7,4 +7,6 @@ pdfjs.GlobalWorkerOptions.workerSrc = new URL(
|
|||||||
|
|
||||||
export { pdfjs };
|
export { pdfjs };
|
||||||
|
|
||||||
export type PdfDocumentProxy = Awaited<ReturnType<typeof pdfjs.getDocument>>["promise"];
|
export type PdfDocumentProxy = Awaited<
|
||||||
|
ReturnType<typeof pdfjs.getDocument>["promise"]
|
||||||
|
>;
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
import { ReactReaderStyle, type IReactReaderStyle } from "react-reader";
|
|
||||||
import type { ReadingSettings } from "../types/reader";
|
|
||||||
|
|
||||||
const THEME_ARROWS: Record<ReadingSettings["theme"], string> = {
|
|
||||||
sepia: "#b8a898",
|
|
||||||
dark: "#666666",
|
|
||||||
light: "#cccccc",
|
|
||||||
paper: "#c4b8a8",
|
|
||||||
};
|
|
||||||
|
|
||||||
const THEME_ARROW_HOVER: Record<ReadingSettings["theme"], string> = {
|
|
||||||
sepia: "#8a7a6a",
|
|
||||||
dark: "#aaaaaa",
|
|
||||||
light: "#888888",
|
|
||||||
paper: "#7a6a5a",
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Build complete react-reader styles — must spread ReactReaderStyle; partial objects break layout. */
|
|
||||||
export function buildReaderStyles(settings: ReadingSettings): IReactReaderStyle {
|
|
||||||
return {
|
|
||||||
...ReactReaderStyle,
|
|
||||||
container: {
|
|
||||||
...ReactReaderStyle.container,
|
|
||||||
height: "100%",
|
|
||||||
width: "100%",
|
|
||||||
},
|
|
||||||
containerExpanded: ReactReaderStyle.containerExpanded,
|
|
||||||
readerArea: {
|
|
||||||
...ReactReaderStyle.readerArea,
|
|
||||||
backgroundColor: settings.background_color,
|
|
||||||
transition: undefined,
|
|
||||||
},
|
|
||||||
titleArea: {
|
|
||||||
...ReactReaderStyle.titleArea,
|
|
||||||
display: "none",
|
|
||||||
},
|
|
||||||
reader: {
|
|
||||||
...ReactReaderStyle.reader,
|
|
||||||
top: 0,
|
|
||||||
left: 0,
|
|
||||||
right: 0,
|
|
||||||
bottom: 0,
|
|
||||||
},
|
|
||||||
arrow: {
|
|
||||||
...ReactReaderStyle.arrow,
|
|
||||||
color: THEME_ARROWS[settings.theme],
|
|
||||||
fontSize: 48,
|
|
||||||
marginTop: -24,
|
|
||||||
},
|
|
||||||
arrowHover: {
|
|
||||||
...ReactReaderStyle.arrowHover,
|
|
||||||
color: THEME_ARROW_HOVER[settings.theme],
|
|
||||||
},
|
|
||||||
tocButton: {
|
|
||||||
...ReactReaderStyle.tocButton,
|
|
||||||
display: "none",
|
|
||||||
},
|
|
||||||
tocArea: ReactReaderStyle.tocArea,
|
|
||||||
tocAreaButton: ReactReaderStyle.tocAreaButton,
|
|
||||||
loadingView: {
|
|
||||||
...ReactReaderStyle.loadingView,
|
|
||||||
color: "#999",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1 +1 @@
|
|||||||
{"root":["./src/app.tsx","./src/main.tsx","./src/api/annotations.ts","./src/api/books.ts","./src/api/client.ts","./src/api/errors.ts","./src/api/reader.ts","./src/components/bookcontextmenu.tsx","./src/components/toastcontainer.tsx","./src/components/annotations/bookmarksnotespage.tsx","./src/components/annotations/markerthreadsview.tsx","./src/components/annotations/index.ts","./src/components/layout/layout.tsx","./src/components/layout/index.ts","./src/components/reader/bookmarkerspanel.tsx","./src/components/reader/readertoolbar.tsx","./src/components/reader/readingsettingspanel.tsx","./src/components/reader/selectionpopover.tsx","./src/components/reader/tableofcontents.tsx","./src/components/search/searchsuggestions.tsx","./src/context/annotationscontext.tsx","./src/context/authcontext.tsx","./src/hooks/index.ts","./src/hooks/usedebounce.ts","./src/hooks/useepubreader.ts","./src/hooks/useepubselection.ts","./src/hooks/usemediaquery.ts","./src/hooks/usepaginatedquery.ts","./src/hooks/usereadingsettings.ts","./src/hooks/usetoast.tsx","./src/hooks/usevoicesearch.ts","./src/i18n/i18nprovider.tsx","./src/locales/en-us.ts","./src/locales/es-es.ts","./src/locales/index.ts","./src/pages/addbook.tsx","./src/pages/authpage.tsx","./src/pages/bookdetailpage.tsx","./src/pages/library.tsx","./src/pages/readingpage.tsx","./src/pages/settings.tsx","./src/types/book.ts","./src/types/index.ts","./src/types/reader.ts","./src/types/speech-recognition.d.ts","./src/types/__tests__/types.test.ts","./src/utils/epubrendition.ts","./src/utils/librarystatus.ts","./src/utils/markers.ts","./src/utils/reactreadertheme.ts","./vite-env.d.ts"],"version":"5.7.3"}
|
{"root":["./src/app.tsx","./src/main.tsx","./src/api/annotations.ts","./src/api/books.ts","./src/api/client.ts","./src/api/errors.ts","./src/api/loadebookwithprogress.ts","./src/api/reader.ts","./src/components/bookcontextmenu.tsx","./src/components/toastcontainer.tsx","./src/components/annotations/bookmarksnotespage.tsx","./src/components/annotations/collapsiblemarkertext.tsx","./src/components/annotations/markerpassageactions.tsx","./src/components/annotations/markerthreadsview.tsx","./src/components/layout/simpleformpagelayout.tsx","./src/components/library/finishedbooksshelf.tsx","./src/components/library/librarybookcard.tsx","./src/components/reader/bookmarkerspanel.tsx","./src/components/reader/bookmarkcolorpicker.tsx","./src/components/reader/bookmarkicon.tsx","./src/components/reader/bookmarkreaderrail.tsx","./src/components/reader/epubreadingview.tsx","./src/components/reader/panelclosebutton.tsx","./src/components/reader/pdflimitationsnotice.tsx","./src/components/reader/pdfreadingview.tsx","./src/components/reader/pdfviewer.tsx","./src/components/reader/readererrorscreen.tsx","./src/components/reader/readerloadingscreen.tsx","./src/components/reader/readersuspenseshell.tsx","./src/components/reader/readertocbutton.tsx","./src/components/reader/readertoolbar.tsx","./src/components/reader/readingsettingspanel.tsx","./src/components/reader/resumereadingbutton.tsx","./src/components/reader/selectionpopover.tsx","./src/components/reader/tableofcontents.tsx","./src/components/search/searchsuggestions.tsx","./src/constants/bookmarkhighlightcolors.ts","./src/context/annotationscontext.tsx","./src/context/authcontext.tsx","./src/hooks/usebookmarkraillayout.ts","./src/hooks/usedebounce.ts","./src/hooks/useepubhighlights.ts","./src/hooks/useepubreader.ts","./src/hooks/useepubselection.ts","./src/hooks/usemediaquery.ts","./src/hooks/usepdfreader.ts","./src/hooks/usereaderorientationcss.ts","./src/hooks/usereadingsettings.ts","./src/hooks/usetoast.tsx","./src/hooks/usevoicesearch.ts","./src/i18n/i18nprovider.tsx","./src/locales/en-us.ts","./src/locales/es-es.ts","./src/locales/index.ts","./src/pages/addbook.tsx","./src/pages/authpage.tsx","./src/pages/bookdetailpage.tsx","./src/pages/library.tsx","./src/pages/readingpage.tsx","./src/pages/settings.tsx","./src/types/book.ts","./src/types/index.ts","./src/types/reader.ts","./src/types/speech-recognition.d.ts","./src/types/__tests__/types.test.ts","./src/utils/bookmarkraillayout.ts","./src/utils/ebooklibrary.ts","./src/utils/epubhighlights.ts","./src/utils/epubrendition.ts","./src/utils/librarystatus.ts","./src/utils/markers.ts","./src/utils/pdfanchor.ts","./src/utils/pdftoc.ts","./src/utils/pdfjssetup.ts","./src/utils/subjectlocale.ts","./vite-env.d.ts"],"version":"5.7.3"}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Mobile (Expo) environment (example – never commit real secrets)
|
||||||
|
# Base URL of the Django backend. Must be reachable from the device/emulator.
|
||||||
|
# - Android emulator: http://10.0.2.2:8000
|
||||||
|
# - iOS simulator: http://localhost:8000
|
||||||
|
# - Physical device: http://<your-lan-ip>:8000
|
||||||
|
EXPO_PUBLIC_API_URL=http://10.0.2.2:8000
|
||||||
|
|
||||||
|
# EAS Build: set per profile in mobile/eas.json or via:
|
||||||
|
# eas secret:create --name EXPO_PUBLIC_API_URL --value https://your-api.example.com
|
||||||
|
# Run all eas commands from mobile/ (not repo root).
|
||||||
@@ -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 (
|
||||||
|
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<NavigationContainer>
|
<NavigationContainer>
|
||||||
<StatusBar style="auto" />
|
<StatusBar style="auto" />
|
||||||
<RootNavigator />
|
<RootNavigator />
|
||||||
</NavigationContainer>
|
</NavigationContainer>
|
||||||
</AuthProvider>
|
</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;
|
||||||
+16
-35
@@ -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",
|
||||||
|
},
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user