Compare commits

..
Author SHA1 Message Date
Marko (Hermes Implementer) 45d16d00ed refactor: consolidate backend/frontend, remove api/web duplicates
- backend/ kept as canonical, api/ features merged (EBook, ReadingProgress, ReadingSettings)
- frontend/ kept as canonical, web/ pages merged (Library, Reader, AddBook, Auth, Settings)
- Added Dockerfiles for backend/ and frontend/
- Updated docker-compose.yml for consolidated services
- Updated README, package.json workspaces
- api/ and web/ directories removed
2026-05-26 02:58:24 +00:00
10 changed files with 39 additions and 1073 deletions
@@ -1,96 +0,0 @@
# Generated by Django 5.1.7 on 2026-05-26 03:33
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Book',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(db_index=True, max_length=512)),
('author', models.CharField(blank=True, db_index=True, default='', max_length=256)),
('genre', models.CharField(blank=True, db_index=True, default='', max_length=128)),
('description', models.TextField(blank=True, default='')),
('reading_status', models.CharField(choices=[('want_to_read', 'Want to Read'), ('reading', 'Reading'), ('finished', 'Finished'), ('dnf', 'Did Not Finish')], db_index=True, default='want_to_read', max_length=20)),
('total_pages', models.PositiveIntegerField(default=0)),
('cover_image', models.URLField(blank=True, default='')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
options={
'verbose_name': 'Book',
'verbose_name_plural': 'Books',
'db_table': 'books_book',
'ordering': ['title'],
'indexes': [models.Index(fields=['title', 'author', 'genre'], name='books_book_title_9fddc2_idx')],
},
),
migrations.CreateModel(
name='EBook',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=512)),
('author', models.CharField(blank=True, default='', max_length=256)),
('file', models.FileField(upload_to='ebooks/%Y/%m/%d/')),
('cover_image', models.ImageField(blank=True, null=True, upload_to='ebook_covers/%Y/%m/%d/')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ebooks', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'E-Book',
'verbose_name_plural': 'E-Books',
'db_table': 'books_ebook',
'ordering': ['-created_at'],
},
),
migrations.CreateModel(
name='ReadingProgress',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('current_position', models.FloatField(default=0.0)),
('last_page', models.IntegerField(default=0)),
('updated_at', models.DateTimeField(auto_now=True)),
('ebook', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='reading_progress', to='books.ebook')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='reading_progress', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name_plural': 'reading progress',
'db_table': 'books_reading_progress',
},
),
migrations.CreateModel(
name='ReadingSettings',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('font_size', models.IntegerField(default=18)),
('font_style', models.CharField(choices=[('sans-serif', 'Sans Serif'), ('serif', 'Serif'), ('monospace', 'Monospace')], default='sans-serif', max_length=20)),
('background_color', models.CharField(choices=[('#ffffff', 'White'), ('#f4e4c1', 'Sepia'), ('#1a1a2e', 'Dark'), ('#c7edcc', 'Green')], default='#ffffff', max_length=7)),
('updated_at', models.DateTimeField(auto_now=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='reading_settings', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name_plural': 'reading settings',
'db_table': 'books_reading_settings',
},
),
migrations.AddIndex(
model_name='ebook',
index=models.Index(fields=['user', '-created_at'], name='books_ebook_user_id_0b6bdb_idx'),
),
migrations.AlterUniqueTogether(
name='readingprogress',
unique_together={('user', 'ebook')},
),
]
-255
View File
@@ -1,255 +0,0 @@
"""Tests for the Book search & discovery endpoints."""
import pytest
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from apps.books.models import Book, ReadingStatus
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def api_client():
return APIClient()
@pytest.fixture
def user(django_user_model):
return django_user_model.objects.create_user(
email="reader@example.com",
password="testpass123",
)
@pytest.fixture
def auth_client(api_client, user):
api_client.force_authenticate(user=user)
return api_client
@pytest.fixture
def books():
books_data = [
Book.objects.create(
title="Dune",
author="Frank Herbert",
genre="Science Fiction",
reading_status=ReadingStatus.FINISHED,
total_pages=688,
description="A desert planet saga.",
),
Book.objects.create(
title="Neuromancer",
author="William Gibson",
genre="Science Fiction",
reading_status=ReadingStatus.READING,
total_pages=271,
description="Cyberpunk classic.",
),
Book.objects.create(
title="The Hobbit",
author="J.R.R. Tolkien",
genre="Fantasy",
reading_status=ReadingStatus.WANT_TO_READ,
total_pages=310,
description="A hobbit's adventure.",
),
Book.objects.create(
title="1984",
author="George Orwell",
genre="Dystopian",
reading_status=ReadingStatus.FINISHED,
total_pages=328,
description="Big Brother is watching.",
),
]
return books_data
# ---------------------------------------------------------------------------
# Search tests
# ---------------------------------------------------------------------------
@pytest.mark.django_db
class TestBookSearch:
"""Verify the search endpoint returns correct results."""
def test_search_by_title(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"q": "Dune"})
assert response.status_code == status.HTTP_200_OK
titles = [b["title"] for b in response.data["results"]]
assert "Dune" in titles
assert "Neuromancer" not in titles
def test_search_by_author(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"q": "Tolkien"})
assert response.status_code == status.HTTP_200_OK
titles = [b["title"] for b in response.data["results"]]
assert "The Hobbit" in titles
def test_search_by_genre(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"q": "Fantasy"})
assert response.status_code == status.HTTP_200_OK
titles = [b["title"] for b in response.data["results"]]
assert "The Hobbit" in titles
def test_search_case_insensitive(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"q": "dune"})
assert response.status_code == status.HTTP_200_OK
assert any(b["title"] == "Dune" for b in response.data["results"])
def test_search_partial_match(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"q": "Neu"})
assert response.status_code == status.HTTP_200_OK
titles = [b["title"] for b in response.data["results"]]
assert "Neuromancer" in titles
def test_search_empty_query_returns_all(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"q": ""})
assert response.status_code == status.HTTP_200_OK
assert len(response.data["results"]) == 4
def test_search_no_results(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"q": "zzzznotfound"})
assert response.status_code == status.HTTP_200_OK
assert len(response.data["results"]) == 0
# ---------------------------------------------------------------------------
# Filter tests
# ---------------------------------------------------------------------------
@pytest.mark.django_db
class TestBookFilters:
"""Verify filters for genre, author, and reading_status."""
def test_filter_by_genre(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"genre": "Science Fiction"})
assert response.status_code == status.HTTP_200_OK
titles = [b["title"] for b in response.data["results"]]
assert "Dune" in titles
assert "Neuromancer" in titles
assert "The Hobbit" not in titles
def test_filter_by_author(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"author": "George Orwell"})
assert response.status_code == status.HTTP_200_OK
titles = [b["title"] for b in response.data["results"]]
assert "1984" in titles
assert "Dune" not in titles
def test_filter_by_reading_status(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"reading_status": ReadingStatus.FINISHED})
assert response.status_code == status.HTTP_200_OK
titles = [b["title"] for b in response.data["results"]]
assert "Dune" in titles
assert "1984" in titles
assert "Neuromancer" not in titles
assert "The Hobbit" not in titles
def test_filter_combined_with_search(self, auth_client, books):
"""Search + filter should intersect results."""
url = reverse("book-list")
response = auth_client.get(url, {"q": "Dune", "reading_status": ReadingStatus.FINISHED})
assert response.status_code == status.HTTP_200_OK
titles = [b["title"] for b in response.data["results"]]
assert "Dune" in titles
# 1984 matches reading_status but not search
assert "1984" not in titles
# ---------------------------------------------------------------------------
# Discovery endpoints
# ---------------------------------------------------------------------------
@pytest.mark.django_db
class TestBookDiscovery:
"""Verify genre and author discovery endpoints."""
def test_genres_endpoint(self, auth_client, books):
url = reverse("book-genres")
response = auth_client.get(url)
assert response.status_code == status.HTTP_200_OK
assert isinstance(response.data, list)
assert "Science Fiction" in response.data
assert "Fantasy" in response.data
assert "Dystopian" in response.data
# No duplicate genres
assert response.data.count("Science Fiction") == 1
def test_authors_endpoint(self, auth_client, books):
url = reverse("book-authors")
response = auth_client.get(url)
assert response.status_code == status.HTTP_200_OK
assert isinstance(response.data, list)
assert "Frank Herbert" in response.data
assert "J.R.R. Tolkien" in response.data
def test_genres_requires_auth(self, api_client, books):
url = reverse("book-genres")
response = api_client.get(url)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_authors_requires_auth(self, api_client, books):
url = reverse("book-authors")
response = api_client.get(url)
assert response.status_code == status.HTTP_401_UNAUTHORIZED
# ---------------------------------------------------------------------------
# Detail view
# ---------------------------------------------------------------------------
@pytest.mark.django_db
class TestBookDetail:
"""Verify the book detail endpoint."""
def test_retrieve_book(self, auth_client, books):
book = books[0]
url = reverse("book-detail", kwargs={"pk": book.pk})
response = auth_client.get(url)
assert response.status_code == status.HTTP_200_OK
assert response.data["title"] == "Dune"
assert response.data["author"] == "Frank Herbert"
assert response.data["description"] == "A desert planet saga."
assert response.data["total_pages"] == 688
def test_retrieve_nonexistent_returns_404(self, auth_client, books):
url = reverse("book-detail", kwargs={"pk": 99999})
response = auth_client.get(url)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_pagination(self, auth_client, books):
"""List with small page size should paginate."""
url = reverse("book-list")
response = auth_client.get(f"{url}?page_size=2")
assert response.status_code == status.HTTP_200_OK
assert "count" in response.data
assert "results" in response.data
assert response.data["count"] == 4
def test_ordering(self, auth_client, books):
url = reverse("book-list")
response = auth_client.get(url, {"ordering": "title"})
assert response.status_code == status.HTTP_200_OK
titles = [b["title"] for b in response.data["results"]]
assert titles == sorted(titles)
+5 -142
View File
@@ -1,27 +1,21 @@
from __future__ import annotations
import logging
from typing import Any
from django.db.models import QuerySet, Q
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import parsers, permissions, status, viewsets
from rest_framework import parsers, status, viewsets
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter, SearchFilter
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from apps.books.models import Book, BookChapter, EBook, ReadingProgress, ReadingSettings
from apps.books.models import Book, EBook, ReadingProgress, ReadingSettings
from apps.books.serializers import (
BookDetailSerializer, BookListSerializer, BookSerializer,
BookChapterSerializer, EBookContentSerializer, EBookDetailSerializer,
EBookListSerializer, EBookTocSerializer, EBookUploadSerializer,
EBookDetailSerializer, EBookListSerializer, EBookUploadSerializer,
ReadingProgressSerializer, ReadingSettingsSerializer,
)
logger = logging.getLogger(__name__)
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
@@ -57,7 +51,7 @@ class BookViewSet(viewsets.ModelViewSet):
return Response([a for a in author_list if a])
class IsEBookOwner(permissions.BasePermission):
class IsEBookOwner(AllowAny):
def has_object_permission(self, request: Request, view: object, obj: EBook) -> bool:
return obj.user == request.user
@@ -69,10 +63,8 @@ class EBookViewSet(viewsets.ModelViewSet):
def get_serializer_class(self):
if self.action == "create":
return EBookUploadSerializer
if self.action in ("list",):
if self.action == "list":
return EBookListSerializer
if self.action in ("toc",):
return BookChapterSerializer
return EBookDetailSerializer
def get_queryset(self):
@@ -90,135 +82,6 @@ class EBookViewSet(viewsets.ModelViewSet):
serializer.save()
return Response(serializer.data)
@action(detail=True, methods=["post"])
def process(self, request: Request, pk: int | None = None) -> Response:
"""Trigger e-book processing: metadata extraction, TOC building, page counting."""
ebook = self.get_object()
if not ebook.file:
return Response({"error": "No file found for this e-book."}, status=status.HTTP_400_BAD_REQUEST)
try:
from apps.books.services import process_ebook
file_path = ebook.file.path
result = process_ebook(file_path, original_filename=ebook.filename())
# Update ebook with extracted data
ebook.format = result.get("format", ebook.format)
ebook.page_count = result.get("page_count", 0)
ebook.metadata_json = result.get("metadata", {})
ebook.save(update_fields=["format", "page_count", "metadata_json", "updated_at"])
# Store chapters in DB
raw_toc: list[dict[str, Any]] = result.get("toc", [])
BookChapter.objects.filter(ebook=ebook).delete()
_store_chapters(ebook, raw_toc)
return Response({
"format": ebook.format,
"page_count": ebook.page_count,
"metadata": ebook.metadata_json,
"toc_count": len(raw_toc),
"status": "processed",
})
except Exception as exc:
logger.exception("Failed to process ebook %s", ebook.id)
return Response({"error": f"Processing failed: {exc}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
@action(detail=True, methods=["get"])
def toc(self, request: Request, pk: int | None = None) -> Response:
"""Return hierarchical table of contents."""
ebook = self.get_object()
chapters = BookChapter.objects.filter(ebook=ebook).order_by("index").select_related("ebook")
serializer = BookChapterSerializer(chapters, many=True)
return Response({
"chapters": serializer.data,
"format": ebook.format,
"page_count": ebook.page_count,
})
@action(detail=True, methods=["get"])
def content(self, request: Request, pk: int | None = None) -> Response:
"""Return paginated content for a given page number.
Query params:
page (int): page/chapter index to fetch (1-indexed, default: 1)
"""
ebook = self.get_object()
page = max(1, int(request.query_params.get("page", 1)))
chapters = list(BookChapter.objects.filter(ebook=ebook).order_by("index").select_related("ebook"))
total_pages = len(chapters) or ebook.page_count or 1
chapter: BookChapter | None = None
chapter_title = ""
content_html = ""
if chapters and 0 <= page - 1 < len(chapters):
ch = chapters[page - 1]
chapter_title = ch.title
content_html = _fetch_chapter_content(ebook, ch)
serializer = EBookContentSerializer(data={
"page": page,
"total_pages": total_pages,
"content": content_html,
"chapter_title": chapter_title,
"format": ebook.format,
})
serializer.is_valid(raise_exception=True)
return Response(serializer.data)
def _store_chapters(ebook: EBook, toc: list[dict[str, Any]], parent_index: int = 0) -> None:
"""Recursively store TOC entries as BookChapter records."""
for idx, entry in enumerate(toc):
BookChapter.objects.create(
ebook=ebook,
title=entry.get("title", "Untitled"),
index=parent_index + idx,
href=entry.get("href", ""),
children=entry.get("children", []),
)
children = entry.get("children", [])
if children:
_store_chapters(ebook, children, parent_index + idx + 1)
def _fetch_chapter_content(ebook: EBook, chapter: BookChapter) -> str:
"""Fetch HTML content for a chapter from the e-book file."""
if ebook.format == "epub":
return _fetch_epub_chapter_content(ebook.file.path, chapter)
return ""
def _fetch_epub_chapter_content(file_path: str, chapter: BookChapter) -> str:
"""Extract HTML content of a specific EPUB chapter by href."""
try:
from ebooklib import epub
from bs4 import BeautifulSoup
except ImportError:
return ""
try:
book = epub.read_epub(file_path)
href = chapter.href or ""
# Find the item by href
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")
# Clean up — remove body/html/head wrappers, keep inner content
body = soup.find("body")
if body:
return str(body)
return str(soup)
return ""
except Exception:
logger.exception("Failed to fetch EPUB chapter content for %s", chapter.href)
return ""
class ReadingSettingsViewSet(viewsets.GenericViewSet):
permission_classes = [IsAuthenticated]
-98
View File
@@ -1,98 +0,0 @@
# Book Search & Discovery — Spec
## Overview
Enable users to search books within the library and discover new books via filters and a dedicated detail view.
## Backend API Contracts
### Book List & Search
`GET /api/books/`
**Query Parameters:**
| Param | Type | Description |
|-------|------|-------------|
| `q` | string | Full-text search across title, author, genre |
| `genre` | string | Exact filter by genre |
| `author` | string | Exact filter by author |
| `reading_status` | string | Filter: `want_to_read`, `reading`, `finished`, `dnf` |
| `ordering` | string | `title`, `author`, `genre`, `created_at` (prefix `-` for desc) |
| `page` | int | Page number (default: 1) |
**Response (paginated):**
```json
{
"count": 42,
"next": "http://.../?page=2",
"previous": null,
"results": [
{
"id": 1,
"title": "Dune",
"author": "Frank Herbert",
"genre": "Science Fiction",
"reading_status": "finished",
"reading_status_display": "Finished",
"cover_image": "https://..."
}
]
}
```
### Book Detail
`GET /api/books/{id}/`
**Response:**
```json
{
"id": 1,
"title": "Dune",
"author": "Frank Herbert",
"genre": "Science Fiction",
"description": "...",
"reading_status": "finished",
"reading_status_display": "Finished",
"cover_image": "https://...",
"total_pages": 688,
"created_at": "2025-01-01T00:00:00Z",
"updated_at": "2025-01-15T00:00:00Z"
}
```
### Genre / Author Discovery
`GET /api/books/genres/``["Fiction", "Science Fiction", ...]`
`GET /api/books/authors/``["Frank Herbert", "Ursula K. Le Guin", ...]`
## Frontend Components
### LibraryPage (enhanced)
- **Search bar** at top: text input with debounced `onChange` → calls API with `q` param
- **Filter row**: genre dropdown, author dropdown, reading status dropdown
- Genre/Author dropdowns populated from `/api/books/genres/` and `/api/books/authors/`
- Reading status uses static enum values
- **Results grid**: card layout showing cover, title, author, reading status badge
- **Empty state**: "No books found" with clear message when results are empty
- **Loading state**: spinner/skeleton while fetching
- **Click card → navigate to** `/books/{id}`
### BookDetailPage (new)
- Shows full book info: cover, title, author, genre, description, reading status, total pages
- Back button to return to library
- Clean, mobile-responsive layout
## Routes (Frontend)
| Path | Component | Auth |
|------|-----------|------|
| `/` | LibraryPage | Protected |
| `/books/:id` | BookDetailPage | Protected |
## Data Flow
1. User types in search bar → 300ms debounce → `GET /api/books/?q=...`
2. User selects filter → `GET /api/books/?genre=...&author=...&reading_status=...`
3. User clicks result → navigate to `/books/:id`
4. BookDetailPage → `GET /api/books/{id}/`
## Mobile Optimizations
- Filters collapse into a toggleable panel on small screens
- Cards stack in single column on mobile
- Touch-friendly tap targets (min 44px)
-2
View File
@@ -3,7 +3,6 @@ import { BrowserRouter, Navigate, Route, Routes } from "react-router-dom";
import { AuthProvider, useAuth } from "./context/AuthContext";
const LibraryPage = lazy(() => import("./pages/Library").then((m) => ({ default: m.LibraryPage })));
const BookDetailPage = lazy(() => import("./pages/BookDetailPage").then((m) => ({ default: m.BookDetailPage })));
const ReaderPage = lazy(() => import("./pages/Reader").then((m) => ({ default: m.ReaderPage })));
const AddBookPage = lazy(() => import("./pages/AddBook").then((m) => ({ default: m.AddBookPage })));
const SettingsPage = lazy(() => import("./pages/Settings").then((m) => ({ default: m.SettingsPage })));
@@ -36,7 +35,6 @@ function AppRoutes() {
<Routes>
<Route path="/auth" element={isAuthenticated ? <Navigate to="/" replace /> : <AuthPage />} />
<Route path="/" element={<ProtectedRoute><LibraryPage /></ProtectedRoute>} />
<Route path="/books/:id" element={<ProtectedRoute><BookDetailPage /></ProtectedRoute>} />
<Route path="/reader/:id" element={<ProtectedRoute><ReaderPage /></ProtectedRoute>} />
<Route path="/add" element={<ProtectedRoute><AddBookPage /></ProtectedRoute>} />
<Route path="/settings" element={<ProtectedRoute><SettingsPage /></ProtectedRoute>} />
+1 -16
View File
@@ -1,5 +1,5 @@
import api from "./client";
import type { ContentResponse, EBookDetail, EBookListItem, ReadingProgress, ReadingSettings, TocResponse } from "../types/book";
import type { EBookDetail, EBookListItem, ReadingProgress, ReadingSettings } from "../types/book";
export const booksApi = {
async getEBooks(): Promise<EBookListItem[]> {
@@ -34,21 +34,6 @@ export const booksApi = {
await api.delete(`/books/ebooks/${id}/`);
},
async processEBook(id: number): Promise<{ status: string }> {
const { data } = await api.post<{ status: string }>(`/books/ebooks/${id}/process/`);
return data;
},
async getToc(id: number): Promise<TocResponse> {
const { data } = await api.get<TocResponse>(`/books/ebooks/${id}/toc/`);
return data;
},
async getContent(id: number, page: number): Promise<ContentResponse> {
const { data } = await api.get<ContentResponse>(`/books/ebooks/${id}/content/?page=${page}`);
return data;
},
async getProgress(ebookId: number): Promise<ReadingProgress> {
const { data } = await api.get<ReadingProgress>(`/books/ebooks/${ebookId}/progress/`);
return data;
-159
View File
@@ -1,159 +0,0 @@
import React, { useCallback, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { booksApi } from "../api/books";
import type { BookDetail } from "../types/book";
export function BookDetailPage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [book, setBook] = useState<BookDetail | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const loadBook = useCallback(async () => {
if (!id) return;
setLoading(true);
setError(null);
try {
const bookId = Number(id);
if (Number.isNaN(bookId)) {
setError("Invalid book ID");
return;
}
const data = await booksApi.getBook(bookId);
setBook(data);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to load book details");
} finally {
setLoading(false);
}
}, [id]);
useEffect(() => {
void loadBook();
}, [loadBook]);
const statusColors: Record<string, { bg: string; text: string }> = {
want_to_read: { bg: "#dbeafe", text: "#1d4ed8" },
reading: { bg: "#dcfce7", text: "#16a34a" },
finished: { bg: "#f3e8ff", text: "#9333ea" },
dnf: { bg: "#fef3c7", text: "#b45309" },
};
if (loading) {
return (
<div style={{ maxWidth: 720, margin: "0 auto", padding: 24, minHeight: "100vh", background: "#f8f9fa" }}>
<div style={{ height: 32, width: 80, background: "#e5e7eb", borderRadius: 6, marginBottom: 24 }} />
<div style={{ display: "flex", gap: 24, flexWrap: "wrap" }}>
<div style={{ width: 240, height: 360, background: "#e5e7eb", borderRadius: 12, flexShrink: 0 }} />
<div style={{ flex: 1 }}>
<div style={{ height: 28, background: "#e5e7eb", borderRadius: 6, marginBottom: 12, width: "60%" }} />
<div style={{ height: 18, background: "#e5e7eb", borderRadius: 4, marginBottom: 8, width: "40%" }} />
<div style={{ height: 18, background: "#e5e7eb", borderRadius: 4, marginBottom: 8, width: "30%" }} />
<div style={{ height: 14, background: "#e5e7eb", borderRadius: 4, marginBottom: 4, width: "90%" }} />
<div style={{ height: 14, background: "#e5e7eb", borderRadius: 4, marginBottom: 4, width: "80%" }} />
<div style={{ height: 14, background: "#e5e7eb", borderRadius: 4, width: "70%" }} />
</div>
</div>
</div>
);
}
if (error || !book) {
return (
<div style={{ maxWidth: 720, margin: "0 auto", padding: 24, minHeight: "100vh", background: "#f8f9fa" }}>
<button onClick={() => navigate("/")} className="btn btn-secondary" style={{ marginBottom: 24 }}> Back to Library</button>
<div style={{ textAlign: "center", padding: "80px 20px" }}>
<div style={{ fontSize: 64, marginBottom: 16 }}>😕</div>
<h2 style={{ fontSize: 20, color: "#1f2937", marginBottom: 8 }}>Book not found</h2>
<p style={{ color: "#6b7280", marginBottom: 20 }}>{error || "The book you're looking for doesn't exist or has been removed."}</p>
<button onClick={() => void loadBook()} className="btn" style={{ padding: "10px 24px" }}>Retry</button>
</div>
</div>
);
}
const sc = statusColors[book.reading_status] ?? { bg: "#f3f4f6", text: "#6b7280" };
return (
<div style={{ maxWidth: 720, margin: "0 auto", padding: 24, minHeight: "100vh", background: "#f8f9fa" }}>
{/* Back button */}
<button
onClick={() => navigate("/")}
style={{
display: "inline-flex", alignItems: "center", gap: 4, padding: "8px 16px",
borderRadius: 8, border: "1px solid #e5e7eb", background: "#fff",
color: "#374151", fontSize: 14, cursor: "pointer", marginBottom: 24,
}}
>
Back to Library
</button>
{/* Book Detail */}
<div style={{ display: "flex", gap: 32, flexWrap: "wrap" }}>
{/* Cover */}
<div style={{ flexShrink: 0 }}>
<div style={{
width: 240, height: 360, borderRadius: 12, overflow: "hidden",
background: "#f0f0f0", display: "flex", alignItems: "center", justifyContent: "center",
boxShadow: "0 4px 20px rgba(0,0,0,0.1)",
}}>
{book.cover_image
? <img src={book.cover_image} alt={book.title} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
: <span style={{ fontSize: 80 }}>📖</span>}
</div>
</div>
{/* Info */}
<div style={{ flex: 1, minWidth: 240 }}>
<h1 style={{ fontSize: 28, fontWeight: 700, color: "#1f2937", marginBottom: 8, lineHeight: 1.2 }}>
{book.title}
</h1>
{book.author && (
<p style={{ fontSize: 18, color: "#4b5563", marginBottom: 6 }}>
by {book.author}
</p>
)}
<div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16, marginTop: 12 }}>
<span style={{ background: sc.bg, color: sc.text, fontSize: 13, fontWeight: 600, padding: "4px 12px", borderRadius: 999 }}>
{book.reading_status_display}
</span>
{book.genre && (
<span style={{ background: "#eef2ff", color: "#4f46e5", fontSize: 13, padding: "4px 12px", borderRadius: 999 }}>
{book.genre}
</span>
)}
{book.total_pages > 0 && (
<span style={{ background: "#f3f4f6", color: "#6b7280", fontSize: 13, padding: "4px 12px", borderRadius: 999 }}>
{book.total_pages} pages
</span>
)}
</div>
{book.description && (
<div style={{ marginTop: 20 }}>
<h3 style={{ fontSize: 16, fontWeight: 600, color: "#1f2937", marginBottom: 8 }}>Description</h3>
<p style={{ fontSize: 15, color: "#4b5563", lineHeight: 1.7, whiteSpace: "pre-wrap" }}>
{book.description}
</p>
</div>
)}
<div style={{ marginTop: 24, paddingTop: 16, borderTop: "1px solid #e5e7eb" }}>
<p style={{ fontSize: 13, color: "#9ca3af" }}>
Added {new Date(book.created_at).toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" })}
{book.created_at !== book.updated_at && ` · Updated ${new Date(book.updated_at).toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" })}`}
</p>
</div>
{/* Mobile-only: open in reader if it's an ebook, or just navigate back */}
<div style={{ marginTop: 24, display: "none" }}>
<button onClick={() => navigate("/")} className="btn btn-block">Back to Library</button>
</div>
</div>
</div>
</div>
);
}
+28 -272
View File
@@ -1,305 +1,61 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
import React, { useCallback, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { booksApi } from "../api/books";
import type { BookListItem, BookSearchParams } from "../types/book";
import { READING_STATUS_OPTIONS } from "../types/book";
import type { EBookListItem } from "../types/book";
import { useAuth } from "../context/AuthContext";
interface FilterState {
genre: string;
author: string;
reading_status: string;
}
function useDebounce<T>(value: T, delay: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debounced;
}
export function LibraryPage() {
const navigate = useNavigate();
const { logout } = useAuth();
const [books, setBooks] = useState<BookListItem[]>([]);
const [books, setBooks] = useState<EBookListItem[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const [filters, setFilters] = useState<FilterState>({ genre: "", author: "", reading_status: "" });
const [genres, setGenres] = useState<string[]>([]);
const [authors, setAuthors] = useState<string[]>([]);
const [totalCount, setTotalCount] = useState(0);
const [showFilters, setShowFilters] = useState(false);
const { logout } = useAuth();
const navigate = useNavigate();
const debouncedSearch = useDebounce(searchQuery, 300);
const loadedRef = useRef(false);
// Load filter options once
useEffect(() => {
if (loadedRef.current) return;
loadedRef.current = true;
void Promise.all([booksApi.getGenres(), booksApi.getAuthors()]).then(
([genreList, authorList]) => {
setGenres(genreList);
setAuthors(authorList);
},
() => {
// Filters degrade gracefully if discovery endpoints fail
},
);
}, []);
const loadBooks = useCallback(async (params: BookSearchParams) => {
const loadBooks = useCallback(async () => {
setLoading(true);
setError(null);
try {
const response = await booksApi.searchBooks(params);
setBooks(response.results);
setTotalCount(response.count);
const data = await booksApi.getEBooks();
setBooks(data);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to load books");
setBooks([]);
setTotalCount(0);
setError(err instanceof Error ? err.message : "Failed to load library");
} finally {
setLoading(false);
}
}, []);
// Reload when search or filters change
useEffect(() => {
const params: BookSearchParams = {};
if (debouncedSearch) params.q = debouncedSearch;
if (filters.genre) params.genre = filters.genre;
if (filters.author) params.author = filters.author;
if (filters.reading_status) params.reading_status = filters.reading_status;
void loadBooks(params);
}, [debouncedSearch, filters, loadBooks]);
const handleFilterChange = (key: keyof FilterState, value: string) => {
setFilters((prev) => ({ ...prev, [key]: value }));
};
const clearAllFilters = () => {
setSearchQuery("");
setFilters({ genre: "", author: "", reading_status: "" });
};
const hasActiveFilters = !!searchQuery || !!filters.genre || !!filters.author || !!filters.reading_status;
useEffect(() => { void loadBooks(); }, [loadBooks]);
return (
<div style={{ maxWidth: 960, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
{/* Header */}
<header style={{
display: "flex", justifyContent: "space-between", alignItems: "center",
marginBottom: 20, padding: "16px 0", borderBottom: "1px solid #e5e7eb", flexWrap: "wrap", gap: 8,
}}>
<div>
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1f2937", margin: 0 }}>Library</h1>
{!loading && <p style={{ fontSize: 13, color: "#6b7280", marginTop: 2 }}>{totalCount} book{totalCount !== 1 ? "s" : ""}</p>}
</div>
<div style={{ maxWidth: 800, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
<header style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 24, padding: "16px 0", borderBottom: "1px solid #eee", flexWrap: "wrap", gap: 8 }}>
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e" }}>My Library</h1>
<div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
<button onClick={() => navigate("/add")} className="btn">+ Add Book</button>
<button onClick={() => navigate("/bookmarks-notes")} className="btn btn-secondary">Bookmarks</button>
<button onClick={() => navigate("/settings")} className="btn btn-secondary">Settings</button>
<button onClick={logout} className="btn btn-danger">Logout</button>
<button onClick={() => navigate("/add")} style={{ padding: "10px 20px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 14, fontWeight: 600, cursor: "pointer" }}>+ Add Book</button>
<button onClick={() => navigate("/settings")} style={{ padding: "10px 20px", borderRadius: 8, border: "1px solid #ddd", background: "#fff", color: "#333", fontSize: 14, cursor: "pointer" }}>Settings</button>
<button onClick={() => navigate("/bookmarks-notes")} style={{ padding: "10px 20px", borderRadius: 8, border: "1px solid #ddd", background: "#fff", color: "#333", fontSize: 14, cursor: "pointer" }}>Bookmarks</button>
<button onClick={logout} style={{ padding: "10px 20px", borderRadius: 8, border: "1px solid #e74c3c", background: "#fff", color: "#e74c3c", fontSize: 14, cursor: "pointer" }}>Logout</button>
</div>
</header>
{/* Search Bar */}
<div style={{ marginBottom: 16 }}>
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<div style={{ flex: 1, position: "relative" }}>
<input
type="text"
placeholder="Search by title, author, or genre..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
style={{
width: "100%", padding: "12px 16px 12px 44px", borderRadius: 10,
border: "1px solid #e5e7eb", fontSize: 15, background: "#fff",
outline: "none", boxSizing: "border-box",
}}
/>
<span style={{
position: "absolute", left: 14, top: "50%", transform: "translateY(-50%)",
fontSize: 18, color: "#9ca3af", pointerEvents: "none",
}}>🔍</span>
</div>
<button
onClick={() => setShowFilters(!showFilters)}
className={`btn ${showFilters ? "" : "btn-secondary"}`}
title="Toggle filters"
>
{showFilters ? "▲ Filters" : "▼ Filters"}
</button>
</div>
</div>
{error && <div style={{ background: "#fde8e8", padding: 16, borderRadius: 8, marginBottom: 16, textAlign: "center" }}><p>{error}</p><button onClick={loadBooks} style={{ marginTop: 8, padding: "8px 16px", border: "none", borderRadius: 6, background: "#e74c3c", color: "#fff", cursor: "pointer" }}>Retry</button></div>}
{loading && books.length === 0 && <div style={{ textAlign: "center", padding: "60px 20px" }}><p>Loading your library...</p></div>}
{!loading && !error && books.length === 0 && <div style={{ textAlign: "center", padding: "60px 20px" }}><p style={{ fontSize: 20, color: "#666", marginBottom: 8 }}>Your library is empty</p><p style={{ color: "#999", marginBottom: 20 }}>Add a book to get started</p><button onClick={() => navigate("/add")} style={{ padding: "10px 20px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 14, fontWeight: 600, cursor: "pointer" }}>Add Your First Book</button></div>}
{/* Filters Panel */}
{showFilters && (
<div style={{
background: "#fff", borderRadius: 10, padding: 16, marginBottom: 16,
border: "1px solid #e5e7eb", display: "flex", gap: 12, flexWrap: "wrap", alignItems: "end",
}}>
<div style={{ minWidth: 160, flex: 1 }}>
<label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "#6b7280", marginBottom: 4 }}>Genre</label>
<select
value={filters.genre}
onChange={(e) => handleFilterChange("genre", e.target.value)}
style={{
width: "100%", padding: "8px 12px", borderRadius: 6, border: "1px solid #e5e7eb",
fontSize: 14, background: "#fff", cursor: "pointer",
}}
>
<option value="">All Genres</option>
{genres.map((g) => <option key={g} value={g}>{g}</option>)}
</select>
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 16 }}>
{books.map((book) => (
<div key={book.id} onClick={() => navigate(`/reader/${book.id}`)} style={{ background: "#fff", borderRadius: 12, overflow: "hidden", boxShadow: "0 2px 8px rgba(0,0,0,0.06)", cursor: "pointer" }}>
<div style={{ height: 180, background: "#f0f0f0", display: "flex", alignItems: "center", justifyContent: "center" }}>
{book.cover_image ? <img src={book.cover_image} alt={book.title} style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : <span style={{ fontSize: 48 }}>📖</span>}
</div>
<div style={{ minWidth: 160, flex: 1 }}>
<label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "#6b7280", marginBottom: 4 }}>Author</label>
<select
value={filters.author}
onChange={(e) => handleFilterChange("author", e.target.value)}
style={{
width: "100%", padding: "8px 12px", borderRadius: 6, border: "1px solid #e5e7eb",
fontSize: 14, background: "#fff", cursor: "pointer",
}}
>
<option value="">All Authors</option>
{authors.map((a) => <option key={a} value={a}>{a}</option>)}
</select>
</div>
<div style={{ minWidth: 160, flex: 1 }}>
<label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "#6b7280", marginBottom: 4 }}>Status</label>
<select
value={filters.reading_status}
onChange={(e) => handleFilterChange("reading_status", e.target.value)}
style={{
width: "100%", padding: "8px 12px", borderRadius: 6, border: "1px solid #e5e7eb",
fontSize: 14, background: "#fff", cursor: "pointer",
}}
>
{READING_STATUS_OPTIONS.map((opt) => <option key={opt.value} value={opt.value}>{opt.label}</option>)}
</select>
</div>
{hasActiveFilters && (
<button onClick={clearAllFilters} className="btn btn-secondary" style={{ whiteSpace: "nowrap" }}>
Clear
</button>
)}
</div>
)}
{/* Error State */}
{error && (
<div style={{ background: "#fef2f2", padding: 16, borderRadius: 8, marginBottom: 16, textAlign: "center" }}>
<p style={{ color: "#dc2626", fontSize: 14 }}>{error}</p>
<button onClick={() => void loadBooks({})} style={{ marginTop: 8, padding: "8px 16px", border: "none", borderRadius: 6, background: "#dc2626", color: "#fff", cursor: "pointer", fontSize: 13 }}>Retry</button>
</div>
)}
{/* Loading State */}
{loading && (
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 16, opacity: 0.6 }}>
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} style={{ background: "#fff", borderRadius: 12, overflow: "hidden", boxShadow: "0 2px 8px rgba(0,0,0,0.06)" }}>
<div style={{ height: 180, background: "#f0f0f0" }} />
<div style={{ padding: 12 }}>
<div style={{ height: 14, background: "#f0f0f0", borderRadius: 4, marginBottom: 6, width: "70%" }} />
<div style={{ height: 12, background: "#f0f0f0", borderRadius: 4, width: "40%" }} />
<h3 style={{ fontSize: 14, fontWeight: 600, color: "#1a1a2e", marginBottom: 4, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{book.title}</h3>
<p style={{ fontSize: 12, color: "#888", marginBottom: 8 }}>{book.author || "Unknown Author"}</p>
{book.progress !== null && <div style={{ width: "100%", height: 4, background: "#eee", borderRadius: 2, overflow: "hidden" }}><div style={{ height: "100%", background: "#1a1a2e", borderRadius: 2, width: `${Math.min(book.progress, 100)}%` }} /></div>}
</div>
</div>
))}
</div>
)}
{/* Empty State */}
{!loading && !error && books.length === 0 && (
<div style={{ textAlign: "center", padding: "80px 20px" }}>
<div style={{ fontSize: 64, marginBottom: 16 }}>{hasActiveFilters ? "🔍" : "📚"}</div>
<h2 style={{ fontSize: 20, color: "#1f2937", marginBottom: 8 }}>
{hasActiveFilters ? "No books found" : "Your library is empty"}
</h2>
<p style={{ color: "#6b7280", marginBottom: 20, fontSize: 15, lineHeight: 1.5 }}>
{hasActiveFilters
? "Try adjusting your search query or filters to discover more books."
: "Add a book to get started building your collection."}
</p>
{hasActiveFilters ? (
<button onClick={clearAllFilters} className="btn" style={{ padding: "10px 24px" }}>
Clear All Filters
</button>
) : (
<button onClick={() => navigate("/add")} className="btn" style={{ padding: "10px 24px" }}>
Add Your First Book
</button>
)}
</div>
)}
{/* Results Grid */}
{!loading && books.length > 0 && (
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 16 }}>
{books.map((book) => {
const statusColors: Record<string, { bg: string; text: string }> = {
want_to_read: { bg: "#dbeafe", text: "#1d4ed8" },
reading: { bg: "#dcfce7", text: "#16a34a" },
finished: { bg: "#f3e8ff", text: "#9333ea" },
dnf: { bg: "#fef3c7", text: "#b45309" },
};
const sc = statusColors[book.reading_status] ?? { bg: "#f3f4f6", text: "#6b7280" };
return (
<div
key={book.id}
onClick={() => navigate(`/books/${book.id}`)}
style={{
background: "#fff", borderRadius: 12, overflow: "hidden",
boxShadow: "0 2px 8px rgba(0,0,0,0.06)", cursor: "pointer",
transition: "transform 0.15s, box-shadow 0.15s",
}}
onMouseEnter={(e) => {
(e.currentTarget as HTMLElement).style.transform = "translateY(-2px)";
(e.currentTarget as HTMLElement).style.boxShadow = "0 4px 16px rgba(0,0,0,0.1)";
}}
onMouseLeave={(e) => {
(e.currentTarget as HTMLElement).style.transform = "";
(e.currentTarget as HTMLElement).style.boxShadow = "0 2px 8px rgba(0,0,0,0.06)";
}}
>
<div style={{ height: 180, background: "#f0f0f0", display: "flex", alignItems: "center", justifyContent: "center", position: "relative" }}>
{book.cover_image
? <img src={book.cover_image} alt={book.title} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
: <span style={{ fontSize: 48 }}>📖</span>}
<span style={{
position: "absolute", top: 8, right: 8,
background: sc.bg, color: sc.text, fontSize: 11, fontWeight: 600,
padding: "2px 8px", borderRadius: 999, lineHeight: "18px",
}}>
{book.reading_status_display}
</span>
</div>
<div style={{ padding: 12 }}>
<h3 style={{ fontSize: 14, fontWeight: 600, color: "#1f2937", marginBottom: 2, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{book.title}
</h3>
<p style={{ fontSize: 12, color: "#6b7280", marginBottom: 4 }}>
{book.author || "Unknown Author"}
</p>
{book.genre && (
<span style={{ fontSize: 11, color: "#4f46e5", background: "#eef2ff", padding: "1px 6px", borderRadius: 4 }}>
{book.genre}
</span>
)}
</div>
</div>
);
})}
</div>
)}
</div>
);
}
-28
View File
@@ -27,8 +27,6 @@ export interface EBookListItem {
title: string;
author: string;
filename: string;
format: string;
page_count: number;
cover_image: string | null;
created_at: string;
progress: number | null;
@@ -40,10 +38,6 @@ export interface EBookDetail {
author: string;
filename: string;
file_url: string;
format: string;
page_count: number;
file_size: number;
metadata_json: Record<string, unknown>;
cover_image: string | null;
created_at: string;
updated_at: string;
@@ -60,25 +54,3 @@ export interface ReadingSettings {
font_style: "sans-serif" | "serif" | "monospace";
background_color: string;
}
export interface BookChapter {
id: number;
title: string;
index: number;
href: string;
children: BookChapter[];
}
export interface TocResponse {
chapters: BookChapter[];
format: string;
page_count: number;
}
export interface ContentResponse {
page: number;
total_pages: number;
content: string;
chapter_title: string;
format: string;
}