Archived
Implement: Refactor: Consolidate Duplicate Backend and Frontend Implementations (#11)
Reviewed and merged by Reid (Hermes Reviewer) Co-authored-by: crisleo-hermes <hermes@codescripters.org> Co-committed-by: crisleo-hermes <hermes@codescripters.org>
This commit was merged in pull request #11.
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
import React, { lazy, Suspense, useState } from "react";
|
||||
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 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 })));
|
||||
const BookmarksNotesPage = lazy(() => import("./components/annotations/BookmarksNotesPage").then((m) => ({ default: m.BookmarksNotesPage })));
|
||||
|
||||
const AuthPage = lazy(() =>
|
||||
import("./pages/AuthPage").then((m) => ({
|
||||
default: () => {
|
||||
const [isLogin, setIsLogin] = useState(true);
|
||||
return isLogin ? <m.LoginPage onToggle={() => setIsLogin(false)} /> : <m.RegisterPage onToggle={() => setIsLogin(true)} />;
|
||||
},
|
||||
})),
|
||||
);
|
||||
|
||||
function LoadingFallback() {
|
||||
return <div style={{ display: "flex", justifyContent: "center", alignItems: "center", minHeight: "100vh", color: "#888", fontSize: 16 }}><p>Loading...</p></div>;
|
||||
}
|
||||
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { isAuthenticated, loading } = useAuth();
|
||||
if (loading) return <LoadingFallback />;
|
||||
if (!isAuthenticated) return <Navigate to="/auth" replace />;
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
function AppRoutes() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
return (
|
||||
<Suspense fallback={<LoadingFallback />}>
|
||||
<Routes>
|
||||
<Route path="/auth" element={isAuthenticated ? <Navigate to="/" replace /> : <AuthPage />} />
|
||||
<Route path="/" element={<ProtectedRoute><LibraryPage /></ProtectedRoute>} />
|
||||
<Route path="/reader/:id" element={<ProtectedRoute><ReaderPage /></ProtectedRoute>} />
|
||||
<Route path="/add" element={<ProtectedRoute><AddBookPage /></ProtectedRoute>} />
|
||||
<Route path="/settings" element={<ProtectedRoute><SettingsPage /></ProtectedRoute>} />
|
||||
<Route path="/bookmarks-notes/:bookId?" element={<ProtectedRoute><BookmarksNotesPage /></ProtectedRoute>} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<AppRoutes />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import api from "./client";
|
||||
import type { EBookDetail, EBookListItem, ReadingProgress, ReadingSettings } from "../types/book";
|
||||
|
||||
export const booksApi = {
|
||||
async getEBooks(): Promise<EBookListItem[]> {
|
||||
const { data } = await api.get<EBookListItem[]>("/books/ebooks/");
|
||||
return data;
|
||||
},
|
||||
|
||||
async getEBook(id: number): Promise<EBookDetail> {
|
||||
const { data } = await api.get<EBookDetail>(`/books/ebooks/${id}/`);
|
||||
return data;
|
||||
},
|
||||
|
||||
async uploadEBook(
|
||||
file: File,
|
||||
title: string,
|
||||
author: string,
|
||||
coverImage?: File | null,
|
||||
): Promise<EBookDetail> {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
formData.append("title", title);
|
||||
if (author) formData.append("author", author);
|
||||
if (coverImage) formData.append("cover_image", coverImage);
|
||||
|
||||
const { data } = await api.post<EBookDetail>("/books/ebooks/", formData, {
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
});
|
||||
return data;
|
||||
},
|
||||
|
||||
async deleteEBook(id: number): Promise<void> {
|
||||
await api.delete(`/books/ebooks/${id}/`);
|
||||
},
|
||||
|
||||
async getProgress(ebookId: number): Promise<ReadingProgress> {
|
||||
const { data } = await api.get<ReadingProgress>(`/books/ebooks/${ebookId}/progress/`);
|
||||
return data;
|
||||
},
|
||||
|
||||
async updateProgress(ebookId: number, progressData: Partial<ReadingProgress>): Promise<ReadingProgress> {
|
||||
const { data } = await api.patch<ReadingProgress>(`/books/ebooks/${ebookId}/progress/`, progressData);
|
||||
return data;
|
||||
},
|
||||
|
||||
async getSettings(): Promise<ReadingSettings> {
|
||||
const { data } = await api.get<ReadingSettings>("/books/settings/");
|
||||
return data;
|
||||
},
|
||||
|
||||
async updateSettings(settingsData: Partial<ReadingSettings>): Promise<ReadingSettings> {
|
||||
const { data } = await api.patch<ReadingSettings>("/books/settings/", settingsData);
|
||||
return data;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,63 @@
|
||||
import React, { createContext, useCallback, useContext, useEffect, useState } from "react";
|
||||
import api from "../api/client";
|
||||
|
||||
interface AuthContextValue {
|
||||
isAuthenticated: boolean;
|
||||
loading: boolean;
|
||||
user: { email: string } | null;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
register: (email: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = useState<{ email: string } | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (token) {
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split(".")[1] ?? ""));
|
||||
setUser({ email: payload.email ?? payload.sub ?? "user" });
|
||||
} catch {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
}
|
||||
}
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
const { data } = await api.post<{ access: string; refresh: string }>("/auth/token/", { email, password });
|
||||
localStorage.setItem("access_token", data.access);
|
||||
localStorage.setItem("refresh_token", data.refresh);
|
||||
const payload = JSON.parse(atob(data.access.split(".")[1] ?? ""));
|
||||
setUser({ email: payload.email ?? payload.sub ?? "user" });
|
||||
}, []);
|
||||
|
||||
const register = useCallback(async (email: string, password: string) => {
|
||||
await api.post("/auth/register/", { email, password });
|
||||
await login(email, password);
|
||||
}, [login]);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("refresh_token");
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ isAuthenticated: !!user, loading, user, login, register, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth(): AuthContextValue {
|
||||
const ctx = useContext(AuthContext);
|
||||
if (!ctx) throw new Error("useAuth must be used within an AuthProvider");
|
||||
return ctx;
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import React, { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { booksApi } from "../api/books";
|
||||
|
||||
export function AddBookPage() {
|
||||
const navigate = useNavigate();
|
||||
const [title, setTitle] = useState("");
|
||||
const [author, setAuthor] = useState("");
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const selected = e.target.files?.[0] ?? null;
|
||||
if (selected) {
|
||||
const ext = selected.name.split(".").pop()?.toLowerCase();
|
||||
if (ext !== "epub" && ext !== "pdf") { setError("Only EPUB and PDF files are supported."); setFile(null); return; }
|
||||
setFile(selected); setError(null);
|
||||
if (!title) setTitle(selected.name.replace(/\.(epub|pdf)$/i, ""));
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!file || !title.trim()) { setError("Title and file are required."); return; }
|
||||
setUploading(true); setError(null);
|
||||
try { await booksApi.uploadEBook(file, title.trim(), author.trim()); navigate("/"); }
|
||||
catch (err) { setError(err instanceof Error ? err.message : "Upload failed."); }
|
||||
finally { setUploading(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||
<header style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24, padding: "16px 0", borderBottom: "1px solid #eee" }}>
|
||||
<button onClick={() => navigate("/")} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>← Back</button>
|
||||
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>Add Book</h1>
|
||||
</header>
|
||||
<form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
|
||||
{error && <div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14 }}>{error}</div>}
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>File (EPUB or PDF) *</label>
|
||||
<input type="file" accept=".epub,.pdf" onChange={handleFileChange} style={{ padding: "10px 0" }} />
|
||||
{file && <p style={{ fontSize: 13, color: "#666", marginTop: 4 }}>Selected: {file.name}</p>}
|
||||
</div>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>Title *</label>
|
||||
<input type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Book title" style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 16, outline: "none" }} />
|
||||
</div>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>Author</label>
|
||||
<input type="text" value={author} onChange={(e) => setAuthor(e.target.value)} placeholder="Author name" style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 16, outline: "none" }} />
|
||||
</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 ? "Uploading..." : "Upload Book"}</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import React, { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
|
||||
function AuthForm({ isLogin, onToggle }: { isLogin: boolean; onToggle: () => void }) {
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { login, register } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault(); setError(null);
|
||||
if (!isLogin && password !== confirmPassword) { setError("Passwords do not match."); return; }
|
||||
setLoading(true);
|
||||
try {
|
||||
if (isLogin) await login(email, password);
|
||||
else await register(email, password);
|
||||
navigate("/");
|
||||
} catch (err) { setError(err instanceof Error ? err.message : isLogin ? "Login failed" : "Registration failed"); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ display: "flex", justifyContent: "center", alignItems: "center", minHeight: "100vh", background: "#f8f9fa", padding: 16 }}>
|
||||
<div style={{ width: "100%", maxWidth: 400, background: "#fff", borderRadius: 12, padding: 32, boxShadow: "0 2px 16px rgba(0,0,0,0.08)" }}>
|
||||
<h1 style={{ fontSize: 28, fontWeight: 700, color: "#1a1a2e", textAlign: "center", marginBottom: 4 }}>Cloud Reader</h1>
|
||||
<h2 style={{ fontSize: 16, color: "#888", textAlign: "center", marginBottom: 24, fontWeight: 400 }}>{isLogin ? "Sign In" : "Create Account"}</h2>
|
||||
<form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 16 }}>
|
||||
{error && <div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14 }}>{error}</div>}
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>Email</label>
|
||||
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" required style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 16, outline: "none" }} />
|
||||
</div>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>Password</label>
|
||||
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="At least 8 characters" required minLength={8} style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 16, outline: "none" }} />
|
||||
</div>
|
||||
{!isLogin && <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>Confirm Password</label>
|
||||
<input type="password" value={confirmPassword} onChange={(e) => setConfirmPassword(e.target.value)} placeholder="Repeat your password" required minLength={8} style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 16, outline: "none" }} />
|
||||
</div>}
|
||||
<button type="submit" disabled={loading} style={{ padding: "12px 24px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 16, fontWeight: 600, cursor: "pointer", opacity: loading ? 0.6 : 1, marginTop: 8 }}>{loading ? (isLogin ? "Signing in..." : "Creating account...") : (isLogin ? "Sign In" : "Create Account")}</button>
|
||||
</form>
|
||||
<p style={{ textAlign: "center", marginTop: 20, color: "#888", fontSize: 14 }}>
|
||||
{isLogin ? "Don't have an account? " : "Already have an account? "}
|
||||
<button onClick={onToggle} style={{ background: "none", border: "none", color: "#1a1a2e", fontWeight: 600, cursor: "pointer", fontSize: 14, textDecoration: "underline" }}>{isLogin ? "Register" : "Sign In"}</button>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginPage({ onToggle }: { onToggle: () => void }) { return <AuthForm isLogin={true} onToggle={onToggle} />; }
|
||||
export function RegisterPage({ onToggle }: { onToggle: () => void }) { return <AuthForm isLogin={false} onToggle={onToggle} />; }
|
||||
@@ -0,0 +1,61 @@
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { booksApi } from "../api/books";
|
||||
import type { EBookListItem } from "../types/book";
|
||||
import { useAuth } from "../context/AuthContext";
|
||||
|
||||
export function LibraryPage() {
|
||||
const [books, setBooks] = useState<EBookListItem[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const loadBooks = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await booksApi.getEBooks();
|
||||
setBooks(data);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to load library");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { void loadBooks(); }, [loadBooks]);
|
||||
|
||||
return (
|
||||
<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")} 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>
|
||||
|
||||
{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>}
|
||||
|
||||
<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={{ padding: 12 }}>
|
||||
<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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { booksApi } from "../api/books";
|
||||
import type { EBookDetail } from "../types/book";
|
||||
|
||||
export function ReaderPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const [book, setBook] = useState<EBookDetail | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const progressTimer = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const bookId = Number(id);
|
||||
|
||||
const saveProgress = useCallback(async () => {
|
||||
if (!scrollRef.current || !book) return;
|
||||
const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;
|
||||
const position = Math.min(100, Math.round((scrollTop / (scrollHeight - clientHeight)) * 100));
|
||||
try { await booksApi.updateProgress(bookId, { current_position: position }); } catch { /* silent */ }
|
||||
}, [bookId, book]);
|
||||
|
||||
useEffect(() => {
|
||||
const loadBook = async () => {
|
||||
setLoading(true); setError(null);
|
||||
try {
|
||||
const data = await booksApi.getEBook(bookId);
|
||||
setBook(data);
|
||||
document.title = data.title;
|
||||
} catch (err) { setError(err instanceof Error ? err.message : "Failed to load book"); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
void loadBook();
|
||||
return () => { document.title = "Cloud Reader"; };
|
||||
}, [bookId]);
|
||||
|
||||
useEffect(() => {
|
||||
progressTimer.current = setInterval(() => { void saveProgress(); }, 5000);
|
||||
return () => { if (progressTimer.current) clearInterval(progressTimer.current); };
|
||||
}, [saveProgress]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleBeforeUnload = () => { void saveProgress(); };
|
||||
window.addEventListener("beforeunload", handleBeforeUnload);
|
||||
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
|
||||
}, [saveProgress]);
|
||||
|
||||
if (loading) return <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100vh", color: "#888" }}><p>Loading book...</p></div>;
|
||||
if (error) return <div style={{ display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", height: "100vh", gap: 16 }}><p style={{ color: "#e74c3c", fontSize: 16 }}>{error}</p><button onClick={() => navigate("/")} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer" }}>← Back to Library</button></div>;
|
||||
if (!book) return null;
|
||||
|
||||
return (
|
||||
<div style={{ display: "flex", flexDirection: "column", height: "100vh", background: "#fff" }}>
|
||||
<header style={{ display: "flex", alignItems: "center", padding: "12px 16px", borderBottom: "1px solid #eee", gap: 12, flexShrink: 0 }}>
|
||||
<button onClick={() => navigate("/")} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>← Library</button>
|
||||
<div style={{ flex: 1 }}><h1 style={{ fontSize: 18, fontWeight: 600, color: "#1a1a2e", margin: 0 }}>{book.title}</h1><p style={{ fontSize: 14, color: "#888", margin: "4px 0 0" }}>{book.author}</p></div>
|
||||
<button onClick={() => navigate(`/bookmarks-notes/${bookId}`)} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>📑 Bookmarks & Notes</button>
|
||||
</header>
|
||||
<div ref={scrollRef} style={{ flex: 1, overflow: "auto", background: "#fafafa" }}>
|
||||
{book.file_url ? <iframe src={book.file_url} style={{ width: "100%", height: "100%", border: "none" }} title={book.title} /> : <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100%", color: "#888" }}><p>No file available.</p></div>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { booksApi } from "../api/books";
|
||||
import type { ReadingSettings } from "../types/book";
|
||||
|
||||
const BG_COLORS = [
|
||||
{ value: "#ffffff", label: "White" },
|
||||
{ value: "#f4e4c1", label: "Sepia" },
|
||||
{ value: "#1a1a2e", label: "Dark" },
|
||||
{ value: "#c7edcc", label: "Green" },
|
||||
];
|
||||
|
||||
export function SettingsPage() {
|
||||
const navigate = useNavigate();
|
||||
const [settings, setSettings] = useState<ReadingSettings | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const load = async () => {
|
||||
try { const data = await booksApi.getSettings(); setSettings(data); }
|
||||
catch (err) { setError(err instanceof Error ? err.message : "Failed to load settings"); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!settings) return;
|
||||
setSaving(true); setError(null); setSuccess(false);
|
||||
try { await booksApi.updateSettings(settings); setSuccess(true); setTimeout(() => setSuccess(false), 2000); }
|
||||
catch (err) { setError(err instanceof Error ? err.message : "Failed to save settings"); }
|
||||
finally { setSaving(false); }
|
||||
};
|
||||
|
||||
if (loading) return <div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}><p>Loading settings...</p></div>;
|
||||
|
||||
return (
|
||||
<div style={{ maxWidth: 500, margin: "0 auto", padding: 16, minHeight: "100vh", background: "#f8f9fa" }}>
|
||||
<header style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 24, padding: "16px 0", borderBottom: "1px solid #eee" }}>
|
||||
<button onClick={() => navigate("/")} style={{ padding: "8px 16px", borderRadius: 6, border: "1px solid #ddd", background: "#fff", cursor: "pointer", fontSize: 14 }}>← Back</button>
|
||||
<h1 style={{ fontSize: 24, fontWeight: 700, color: "#1a1a2e", margin: 0 }}>Reading Settings</h1>
|
||||
</header>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 24 }}>
|
||||
{error && <div style={{ background: "#fde8e8", padding: 12, borderRadius: 6, color: "#e74c3c", fontSize: 14 }}>{error}</div>}
|
||||
{success && <div style={{ background: "#d4edda", padding: 12, borderRadius: 6, color: "#155724", fontSize: 14 }}>Settings saved!</div>}
|
||||
|
||||
{settings && <>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>Font Size ({settings.font_size}px)</label>
|
||||
<input type="range" min={12} max={36} value={settings.font_size} onChange={(e) => setSettings({ ...settings, font_size: Number(e.target.value) })} style={{ width: "100%", cursor: "pointer" }} />
|
||||
<div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "#999" }}><span>12px</span><span>36px</span></div>
|
||||
</div>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>Font Style</label>
|
||||
<select value={settings.font_style} onChange={(e) => setSettings({ ...settings, font_style: e.target.value as ReadingSettings["font_style"] })} style={{ padding: "10px 12px", borderRadius: 6, border: "1px solid #ddd", fontSize: 16, background: "#fff", outline: "none" }}>
|
||||
<option value="sans-serif">Sans Serif</option><option value="serif">Serif</option><option value="monospace">Monospace</option>
|
||||
</select>
|
||||
</div>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
|
||||
<label style={{ fontSize: 14, fontWeight: 600, color: "#555" }}>Background Color</label>
|
||||
<div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
|
||||
{BG_COLORS.map((bg) => (
|
||||
<button key={bg.value} onClick={() => setSettings({ ...settings, background_color: bg.value })}
|
||||
style={{ width: 48, height: 48, borderRadius: "50%", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", background: bg.value, border: settings.background_color === bg.value ? "3px solid #1a1a2e" : "3px solid #ddd" }}
|
||||
title={bg.label}>
|
||||
{settings.background_color === bg.value && <span style={{ fontSize: 20, fontWeight: 700, color: bg.value === "#ffffff" || bg.value === "#f4e4c1" ? "#1a1a2e" : "#fff" }}>✓</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>}
|
||||
|
||||
<button onClick={handleSave} disabled={saving} style={{ padding: "12px 24px", borderRadius: 8, border: "none", background: "#1a1a2e", color: "#fff", fontSize: 16, fontWeight: 600, cursor: "pointer", opacity: saving ? 0.6 : 1, marginTop: 8 }}>{saving ? "Saving..." : "Save Settings"}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
export interface BookListItem {
|
||||
id: number;
|
||||
title: string;
|
||||
author: string;
|
||||
genre: string;
|
||||
reading_status: string;
|
||||
reading_status_display: string;
|
||||
cover_image: string | null;
|
||||
}
|
||||
|
||||
export interface BookDetail {
|
||||
id: number;
|
||||
title: string;
|
||||
author: string;
|
||||
genre: string;
|
||||
description: string;
|
||||
reading_status: string;
|
||||
reading_status_display: string;
|
||||
cover_image: string | null;
|
||||
total_pages: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface EBookListItem {
|
||||
id: number;
|
||||
title: string;
|
||||
author: string;
|
||||
filename: string;
|
||||
cover_image: string | null;
|
||||
created_at: string;
|
||||
progress: number | null;
|
||||
}
|
||||
|
||||
export interface EBookDetail {
|
||||
id: number;
|
||||
title: string;
|
||||
author: string;
|
||||
filename: string;
|
||||
file_url: string;
|
||||
cover_image: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
progress: ReadingProgress | null;
|
||||
}
|
||||
|
||||
export interface ReadingProgress {
|
||||
current_position: number;
|
||||
last_page: number;
|
||||
}
|
||||
|
||||
export interface ReadingSettings {
|
||||
font_size: number;
|
||||
font_style: "sans-serif" | "serif" | "monospace";
|
||||
background_color: string;
|
||||
}
|
||||
Reference in New Issue
Block a user