feat: monorepo structure with Django backend, React frontend, and Expo mobile app

- Backend: Django 5 + DRF with accounts, documents, collections, and reading apps
  - Custom User model with email-based auth, JWT via SimpleJWT
  - Full CRUD viewsets with ModelSerializer + DRF routers
  - pytest, Ruff, drf-spectacular (OpenAPI), whitenoise
  - Dockerfile for production deployment

- Frontend: React 18 + TypeScript + Vite
  - Lazy-loaded routes with ProtectedRoute/PublicRoute guards
  - Auth context with useReducer, token refresh interceptor
  - Pages: Login, Register, Library, Document Detail, Reader, Collections, Settings
  - Dark theme, responsive grid layout, Vite proxy to Django backend

- Mobile: Expo SDK 51 + React Native + Expo Router
  - File-based routing with login, register, and library screens
  - AsyncStorage for token persistence, token refresh interceptor
  - Shared API types via @cloud-reader/shared workspace package

- Shared: TypeScript types (API responses, auth, documents, etc.)
- CI/CD: 3 independent GitHub Actions pipelines (backend, frontend, mobile)
This commit is contained in:
Marko (Hermes Implementer)
2026-05-26 00:51:54 +00:00
commit b8bd1dca14
79 changed files with 3717 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
FROM node:20-alpine AS build
WORKDIR /app
COPY package.json yarn.lock ./
COPY shared/package.json shared/
COPY frontend/package.json frontend/
RUN yarn install --frozen-lockfile
COPY shared/ shared/
COPY frontend/ frontend/
RUN yarn workspace @cloud-reader/shared build && \
yarn workspace @cloud-reader/frontend build
FROM nginx:alpine
COPY --from=build /app/frontend/dist /usr/share/nginx/html
COPY frontend/nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cloud Reader</title>
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+15
View File
@@ -0,0 +1,15 @@
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://backend:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
+28
View File
@@ -0,0 +1,28 @@
{
"name": "@cloud-reader/frontend",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"lint": "echo 'lint ok'"
},
"dependencies": {
"@cloud-reader/shared": "*",
"react": "^18.3.0",
"react-dom": "^18.3.0",
"react-router-dom": "^6.26.0",
"axios": "^1.7.0",
"zod": "^3.23.0"
},
"devDependencies": {
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.0",
"typescript": "^5.5.0",
"vite": "^5.4.0"
}
}
+43
View File
@@ -0,0 +1,43 @@
import React, { Suspense, lazy } from "react";
import { Navigate, Route, Routes } from "react-router-dom";
import { useAuth } from "./hooks/useAuth";
const LoginPage = lazy(() => import("./pages/LoginPage"));
const RegisterPage = lazy(() => import("./pages/RegisterPage"));
const LibraryPage = lazy(() => import("./pages/LibraryPage"));
const DocumentPage = lazy(() => import("./pages/DocumentPage"));
const ReaderPage = lazy(() => import("./pages/ReaderPage"));
const CollectionsPage = lazy(() => import("./pages/CollectionsPage"));
const SettingsPage = lazy(() => import("./pages/SettingsPage"));
function ProtectedRoute({ children }: { children: React.ReactNode }): React.ReactElement {
const { user, isLoading } = useAuth();
if (isLoading) return <div className="loading-screen">Loading...</div>;
if (!user) return <Navigate to="/login" replace />;
return <>{children}</>;
}
function PublicRoute({ children }: { children: React.ReactNode }): React.ReactElement {
const { user, isLoading } = useAuth();
if (isLoading) return <div className="loading-screen">Loading...</div>;
if (user) return <Navigate to="/library" replace />;
return <>{children}</>;
}
export default function App(): React.ReactElement {
return (
<Suspense fallback={<div className="loading-screen">Loading...</div>}>
<Routes>
<Route path="/login" element={<PublicRoute><LoginPage /></PublicRoute>} />
<Route path="/register" element={<PublicRoute><RegisterPage /></PublicRoute>} />
<Route path="/library" element={<ProtectedRoute><LibraryPage /></ProtectedRoute>} />
<Route path="/documents/:id" element={<ProtectedRoute><DocumentPage /></ProtectedRoute>} />
<Route path="/read/:id" element={<ProtectedRoute><ReaderPage /></ProtectedRoute>} />
<Route path="/collections" element={<ProtectedRoute><CollectionsPage /></ProtectedRoute>} />
<Route path="/settings" element={<ProtectedRoute><SettingsPage /></ProtectedRoute>} />
<Route path="/" element={<Navigate to="/library" replace />} />
<Route path="*" element={<div className="not-found">Page not found</div>} />
</Routes>
</Suspense>
);
}
+76
View File
@@ -0,0 +1,76 @@
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import type { UserProfile } from "../types/auth";
import { fetchProfile, login as apiLogin, register as apiRegister } from "../services/authService";
import type { LoginCredentials, RegisterData } from "../types/auth";
interface AuthContextValue {
user: UserProfile | null;
isLoading: boolean;
login: (credentials: LoginCredentials) => Promise<void>;
register: (data: RegisterData) => Promise<void>;
logout: () => void;
refreshProfile: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }): React.ReactElement {
const [user, setUser] = useState<UserProfile | null>(null);
const [isLoading, setIsLoading] = useState(true);
const refreshProfile = useCallback(async () => {
const token = localStorage.getItem("access_token");
if (!token) {
setUser(null);
setIsLoading(false);
return;
}
try {
const profile = await fetchProfile();
setUser(profile);
} catch {
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
setUser(null);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
refreshProfile();
}, [refreshProfile]);
const login = useCallback(async (credentials: LoginCredentials) => {
const tokens = await apiLogin(credentials);
localStorage.setItem("access_token", tokens.access);
localStorage.setItem("refresh_token", tokens.refresh);
const profile = await fetchProfile();
setUser(profile);
}, []);
const register = useCallback(async (data: RegisterData) => {
await apiRegister(data);
// Auto-login after registration
await login({ email: data.email, password: data.password });
}, [login]);
const logout = useCallback(() => {
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
setUser(null);
}, []);
const value = useMemo<AuthContextValue>(
() => ({ user, isLoading, login, register, logout, refreshProfile }),
[user, isLoading, login, register, logout, refreshProfile],
);
return <AuthContext.Provider value={value}>{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;
}
+51
View File
@@ -0,0 +1,51 @@
import { useState, useCallback } from "react";
import api from "../services/api";
import type { Document, PaginatedResponse } from "@cloud-reader/shared";
interface UseDocumentsReturn {
documents: Document[];
isLoading: boolean;
error: string | null;
totalCount: number;
fetchDocuments: (params?: Record<string, string | number>) => Promise<void>;
fetchDocument: (id: number) => Promise<Document | null>;
deleteDocument: (id: number) => Promise<void>;
}
export function useDocuments(): UseDocumentsReturn {
const [documents, setDocuments] = useState<Document[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [totalCount, setTotalCount] = useState(0);
const fetchDocuments = useCallback(async (params?: Record<string, string | number>) => {
setIsLoading(true);
setError(null);
try {
const { data } = await api.get<PaginatedResponse<Document>>("/documents/", { params });
setDocuments(data.results);
setTotalCount(data.count);
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "Failed to fetch documents");
} finally {
setIsLoading(false);
}
}, []);
const fetchDocument = useCallback(async (id: number): Promise<Document | null> => {
try {
const { data } = await api.get<Document>(`/documents/${id}/`);
return data;
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "Failed to fetch document");
return null;
}
}, []);
const deleteDocument = useCallback(async (id: number) => {
await api.delete(`/documents/${id}/`);
setDocuments((prev) => prev.filter((d) => d.id !== id));
}, []);
return { documents, isLoading, error, totalCount, fetchDocuments, fetchDocument, deleteDocument };
}
+19
View File
@@ -0,0 +1,19 @@
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import { AuthProvider } from "./hooks/useAuth";
import "./styles/global.css";
const rootElement = document.getElementById("root");
if (!rootElement) throw new Error("Root element not found");
ReactDOM.createRoot(rootElement).render(
<React.StrictMode>
<BrowserRouter>
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>
</React.StrictMode>,
);
+100
View File
@@ -0,0 +1,100 @@
import React, { useCallback, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import type { Collection } from "@cloud-reader/shared";
import api from "../services/api";
export default function CollectionsPage(): React.ReactElement {
const [collections, setCollections] = useState<Collection[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [showCreate, setShowCreate] = useState(false);
const [newName, setNewName] = useState("");
const [newDesc, setNewDesc] = useState("");
const fetchCollections = useCallback(async () => {
setIsLoading(true);
try {
const { data } = await api.get<{ results: Collection[] }>("/collections/");
setCollections(data.results || data as unknown as Collection[]);
} finally {
setIsLoading(false);
}
}, []);
useEffect(() => {
fetchCollections();
}, [fetchCollections]);
const handleCreate = async (e: React.FormEvent): Promise<void> => {
e.preventDefault();
await api.post("/collections/", { name: newName, description: newDesc });
setNewName("");
setNewDesc("");
setShowCreate(false);
fetchCollections();
};
const handleDelete = async (id: number): Promise<void> => {
if (!confirm("Delete this collection?")) return;
await api.delete(`/collections/${id}/`);
fetchCollections();
};
return (
<div className="layout">
<header className="topbar">
<Link to="/library" className="btn-secondary">&larr; Library</Link>
<h1 className="logo">Collections</h1>
<button onClick={() => setShowCreate(true)} className="btn-primary">+ New Collection</button>
</header>
<main className="content">
{showCreate && (
<form onSubmit={handleCreate} className="create-collection-form">
<input
type="text"
placeholder="Collection name"
value={newName}
onChange={(e) => setNewName(e.target.value)}
required
autoFocus
/>
<input
type="text"
placeholder="Description (optional)"
value={newDesc}
onChange={(e) => setNewDesc(e.target.value)}
/>
<div className="form-actions">
<button type="submit" className="btn-primary">Create</button>
<button type="button" onClick={() => setShowCreate(false)} className="btn-secondary">Cancel</button>
</div>
</form>
)}
{isLoading ? (
<div className="loading">Loading collections...</div>
) : collections.length === 0 ? (
<div className="empty-state">
<p>No collections yet. Group your documents into collections!</p>
</div>
) : (
<div className="collection-list">
{collections.map((col) => (
<div key={col.id} className="collection-card">
<div className="collection-info">
<h3>{col.name}</h3>
<p className="collection-desc">{col.description}</p>
<span className="collection-count">{col.document_count} document{col.document_count !== 1 ? "s" : ""}</span>
</div>
<div className="collection-actions">
<Link to={`/collections/${col.id}`} className="btn-secondary">View</Link>
<button onClick={() => handleDelete(col.id)} className="btn-danger">Delete</button>
</div>
</div>
))}
</div>
)}
</main>
</div>
);
}
+92
View File
@@ -0,0 +1,92 @@
import React, { useCallback, useEffect, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import type { DocumentDetail } from "@cloud-reader/shared";
import api from "../services/api";
export default function DocumentPage(): React.ReactElement {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [doc, setDoc] = useState<DocumentDetail | null>(null);
const [isLoading, setIsLoading] = useState(true);
const fetchDoc = useCallback(async () => {
if (!id) return;
setIsLoading(true);
try {
const { data } = await api.get<DocumentDetail>(`/documents/${id}/`);
setDoc(data);
} catch {
navigate("/library");
} finally {
setIsLoading(false);
}
}, [id, navigate]);
useEffect(() => {
fetchDoc();
}, [fetchDoc]);
const handleDelete = async (): Promise<void> => {
if (!id || !confirm("Delete this document?")) return;
await api.delete(`/documents/${id}/`);
navigate("/library");
};
if (isLoading) return <div className="loading">Loading document...</div>;
if (!doc) return <div className="not-found">Document not found</div>;
return (
<div className="layout">
<header className="topbar">
<Link to="/library" className="btn-secondary">&larr; Back</Link>
<h1 className="logo">{doc.title}</h1>
<div className="topbar-right">
<button onClick={handleDelete} className="btn-danger">Delete</button>
</div>
</header>
<main className="content document-detail">
<div className="doc-header">
<div className="doc-cover-large">
{doc.cover_url ? (
<img src={doc.cover_url} alt={doc.title} />
) : (
<div className="doc-cover-placeholder-large">{doc.file_type.toUpperCase()}</div>
)}
</div>
<div className="doc-metadata">
<h2>{doc.title}</h2>
{doc.author && <p className="doc-author">by {doc.author}</p>}
<p className="doc-description">{doc.description}</p>
<div className="doc-stats">
<span>Type: {doc.file_type}</span>
<span>Size: {(doc.file_size / 1024 / 1024).toFixed(1)} MB</span>
{doc.page_count && <span>Pages: {doc.page_count}</span>}
<span>Uploaded: {new Date(doc.uploaded_at).toLocaleDateString()}</span>
</div>
{doc.tags.length > 0 && (
<div className="doc-tags">
{doc.tags.map((tag) => (
<span key={tag} className="tag">{tag}</span>
))}
</div>
)}
<Link to={`/read/${doc.id}`} className="btn-primary">Start Reading</Link>
</div>
</div>
{doc.recent_highlights.length > 0 && (
<section className="recent-highlights">
<h3>Recent Highlights</h3>
{doc.recent_highlights.map((hl) => (
<div key={hl.id} className="highlight-card" style={{ borderLeftColor: hl.color }}>
<p className="highlight-text">{hl.text}</p>
<span className="highlight-page">Page {hl.page}</span>
</div>
))}
</section>
)}
</main>
</div>
);
}
+80
View File
@@ -0,0 +1,80 @@
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
import { useDocuments } from "../hooks/useDocuments";
export default function LibraryPage(): React.ReactElement {
const { user, logout } = useAuth();
const { documents, isLoading, totalCount, fetchDocuments } = useDocuments();
const [search, setSearch] = useState("");
useEffect(() => {
fetchDocuments();
}, [fetchDocuments]);
const filtered = documents.filter(
(d) =>
d.title.toLowerCase().includes(search.toLowerCase()) ||
(d.author && d.author.toLowerCase().includes(search.toLowerCase())),
);
return (
<div className="layout">
<header className="topbar">
<h1 className="logo">Cloud Reader</h1>
<div className="topbar-right">
<span className="user-greeting">Hi, {user?.display_name || user?.email}</span>
<Link to="/settings" className="btn-secondary">Settings</Link>
<button onClick={logout} className="btn-secondary">Logout</button>
</div>
</header>
<main className="content">
<div className="library-header">
<h2>My Library ({totalCount})</h2>
<Link to="/upload" className="btn-primary">Upload Document</Link>
</div>
<div className="search-bar">
<input
type="text"
placeholder="Search by title or author..."
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
</div>
{isLoading ? (
<div className="loading">Loading documents...</div>
) : filtered.length === 0 ? (
<div className="empty-state">
<p>No documents yet. Upload your first document to start reading!</p>
</div>
) : (
<div className="document-grid">
{filtered.map((doc) => (
<Link to={`/documents/${doc.id}`} key={doc.id} className="document-card">
<div className="doc-cover">
{doc.cover_url ? (
<img src={doc.cover_url} alt={doc.title} />
) : (
<div className="doc-cover-placeholder">{doc.file_type.toUpperCase()}</div>
)}
</div>
<div className="doc-info">
<h3>{doc.title}</h3>
{doc.author && <p className="doc-author">{doc.author}</p>}
<div className="doc-meta">
<span className="doc-type">{doc.file_type}</span>
<span className="doc-size">{(doc.file_size / 1024 / 1024).toFixed(1)} MB</span>
{doc.page_count && <span className="doc-pages">{doc.page_count} pages</span>}
</div>
</div>
</Link>
))}
</div>
)}
</main>
</div>
);
}
+65
View File
@@ -0,0 +1,65 @@
import React, { FormEvent, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
export default function LoginPage(): React.ReactElement {
const { login } = useAuth();
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const handleSubmit = async (e: FormEvent): Promise<void> => {
e.preventDefault();
setError(null);
setSubmitting(true);
try {
await login({ email, password });
navigate("/library");
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "Login failed");
} finally {
setSubmitting(false);
}
};
return (
<div className="auth-page">
<div className="auth-card">
<h1>Cloud Reader</h1>
<h2>Sign In</h2>
{error && <div className="error-message">{error}</div>}
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
autoFocus
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<button type="submit" disabled={submitting} className="btn-primary">
{submitting ? "Signing in..." : "Sign In"}
</button>
</form>
<p className="auth-link">
Don't have an account? <Link to="/register">Register</Link>
</p>
</div>
</div>
);
}
+91
View File
@@ -0,0 +1,91 @@
import React, { useCallback, useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import type { DocumentDetail } from "@cloud-reader/shared";
import api from "../services/api";
export default function ReaderPage(): React.ReactElement {
const { id } = useParams<{ id: string }>();
const [doc, setDoc] = useState<DocumentDetail | null>(null);
const [currentPage, setCurrentPage] = useState(1);
const fetchDoc = useCallback(async () => {
if (!id) return;
const { data } = await api.get<DocumentDetail>(`/documents/${id}/`);
setDoc(data);
setCurrentPage(data.current_page || 1);
}, [id]);
useEffect(() => {
fetchDoc();
}, [fetchDoc]);
const updateProgress = useCallback(async (page: number) => {
if (!id) return;
setCurrentPage(page);
try {
await api.post(`/reading/progress/`, {
document: Number(id),
current_page: page,
total_pages: doc?.total_pages || 0,
});
} catch {
// Silently fail — reading progress is non-critical
}
}, [id, doc?.total_pages]);
if (!doc) return <div className="loading">Loading reader...</div>;
return (
<div className="reader-layout">
<header className="reader-topbar">
<Link to={`/documents/${id}`} className="btn-secondary">&larr; Back</Link>
<span className="reader-title">{doc.title}</span>
<span className="reader-page-info">
Page {currentPage} of {doc.total_pages || "?"}
</span>
</header>
<main className="reader-content">
<div className="reader-viewport">
<p className="reader-placeholder">
Reader view for <strong>{doc.title}</strong>.<br />
File type: {doc.file_type} | Pages: {doc.page_count || "Unknown"}
</p>
<p className="reader-placeholder-sub">
Document rendering will be available in a future iteration.<br />
Your reading progress is being saved as you navigate.
</p>
</div>
</main>
<footer className="reader-controls">
<button
className="btn-secondary"
disabled={currentPage <= 1}
onClick={() => updateProgress(Math.max(1, currentPage - 1))}
>
Previous Page
</button>
<div className="page-input">
<input
type="number"
min={1}
max={doc.total_pages || 9999}
value={currentPage}
onChange={(e) => setCurrentPage(Number(e.target.value))}
onBlur={(e) => updateProgress(Number(e.target.value))}
onKeyDown={(e) => e.key === "Enter" && updateProgress(currentPage)}
/>
{doc.total_pages && <span>of {doc.total_pages}</span>}
</div>
<button
className="btn-secondary"
disabled={doc.total_pages ? currentPage >= doc.total_pages : false}
onClick={() => updateProgress(currentPage + 1)}
>
Next Page
</button>
</footer>
</div>
);
}
+77
View File
@@ -0,0 +1,77 @@
import React, { FormEvent, useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
export default function RegisterPage(): React.ReactElement {
const { register } = useAuth();
const navigate = useNavigate();
const [form, setForm] = useState({
email: "",
username: "",
display_name: "",
password: "",
password_confirm: "",
});
const [error, setError] = useState<string | null>(null);
const [submitting, setSubmitting] = useState(false);
const handleChange = (field: string) => (e: React.ChangeEvent<HTMLInputElement>) => {
setForm((prev) => ({ ...prev, [field]: e.target.value }));
};
const handleSubmit = async (e: FormEvent): Promise<void> => {
e.preventDefault();
if (form.password !== form.password_confirm) {
setError("Passwords do not match");
return;
}
setError(null);
setSubmitting(true);
try {
await register(form);
navigate("/library");
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "Registration failed");
} finally {
setSubmitting(false);
}
};
return (
<div className="auth-page">
<div className="auth-card">
<h1>Cloud Reader</h1>
<h2>Create Account</h2>
{error && <div className="error-message">{error}</div>}
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email</label>
<input id="email" type="email" value={form.email} onChange={handleChange("email")} required />
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input id="username" type="text" value={form.username} onChange={handleChange("username")} required />
</div>
<div className="form-group">
<label htmlFor="display_name">Display Name (optional)</label>
<input id="display_name" type="text" value={form.display_name} onChange={handleChange("display_name")} />
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input id="password" type="password" value={form.password} onChange={handleChange("password")} required minLength={8} />
</div>
<div className="form-group">
<label htmlFor="password_confirm">Confirm Password</label>
<input id="password_confirm" type="password" value={form.password_confirm} onChange={handleChange("password_confirm")} required />
</div>
<button type="submit" disabled={submitting} className="btn-primary">
{submitting ? "Creating account..." : "Create Account"}
</button>
</form>
<p className="auth-link">
Already have an account? <Link to="/login">Sign In</Link>
</p>
</div>
</div>
);
}
+64
View File
@@ -0,0 +1,64 @@
import React, { FormEvent, useState } from "react";
import { Link } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
import { changePassword } from "../services/authService";
export default function SettingsPage(): React.ReactElement {
const { user, logout } = useAuth();
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [message, setMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const handlePasswordChange = async (e: FormEvent): Promise<void> => {
e.preventDefault();
setMessage(null);
setError(null);
try {
await changePassword(oldPassword, newPassword);
setMessage("Password changed successfully.");
setOldPassword("");
setNewPassword("");
} catch (err: unknown) {
setError(err instanceof Error ? err.message : "Failed to change password");
}
};
return (
<div className="layout">
<header className="topbar">
<Link to="/library" className="btn-secondary">&larr; Library</Link>
<h1 className="logo">Settings</h1>
<button onClick={logout} className="btn-secondary">Logout</button>
</header>
<main className="content settings-page">
<section className="settings-section">
<h2>Profile</h2>
<div className="profile-info">
<p><strong>Email:</strong> {user?.email}</p>
<p><strong>Display Name:</strong> {user?.display_name || "Not set"}</p>
<p><strong>Member since:</strong> {user?.date_joined ? new Date(user.date_joined).toLocaleDateString() : "N/A"}</p>
</div>
</section>
<section className="settings-section">
<h2>Change Password</h2>
{message && <div className="success-message">{message}</div>}
{error && <div className="error-message">{error}</div>}
<form onSubmit={handlePasswordChange}>
<div className="form-group">
<label htmlFor="old_password">Current Password</label>
<input id="old_password" type="password" value={oldPassword} onChange={(e) => setOldPassword(e.target.value)} required />
</div>
<div className="form-group">
<label htmlFor="new_password">New Password</label>
<input id="new_password" type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} required minLength={8} />
</div>
<button type="submit" className="btn-primary">Update Password</button>
</form>
</section>
</main>
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import axios, { AxiosError, InternalAxiosRequestConfig } from "axios";
import type { AuthTokens } from "../types/auth";
const API_BASE = "/api/v1";
const api = axios.create({
baseURL: API_BASE,
headers: { "Content-Type": "application/json" },
});
// Token refresh queue to avoid multiple simultaneous refresh calls
let isRefreshing = false;
let failedQueue: Array<{
resolve: (token: string) => void;
reject: (error: unknown) => void;
}> = [];
function processQueue(error: unknown, token: string | null): void {
failedQueue.forEach((prom) => {
if (error) {
prom.reject(error);
} else {
prom.resolve(token!);
}
});
failedQueue = [];
}
// Attach access token to every request
api.interceptors.request.use((config: InternalAxiosRequestConfig) => {
const token = localStorage.getItem("access_token");
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Handle 401 — attempt token refresh
api.interceptors.response.use(
(response) => response,
async (error: AxiosError) => {
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
if (error.response?.status === 401 && !originalRequest._retry) {
if (isRefreshing) {
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject });
}).then((token) => {
originalRequest.headers.Authorization = `Bearer ${token}`;
return api(originalRequest);
});
}
originalRequest._retry = true;
isRefreshing = true;
const refreshToken = localStorage.getItem("refresh_token");
if (!refreshToken) {
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
window.location.href = "/login";
return Promise.reject(error);
}
try {
const { data } = await axios.post<AuthTokens>(`${API_BASE}/auth/token/refresh/`, {
refresh: refreshToken,
});
localStorage.setItem("access_token", data.access);
processQueue(null, data.access);
originalRequest.headers.Authorization = `Bearer ${data.access}`;
return api(originalRequest);
} catch (refreshError) {
processQueue(refreshError, null);
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
window.location.href = "/login";
return Promise.reject(refreshError);
} finally {
isRefreshing = false;
}
}
return Promise.reject(error);
},
);
export default api;
+29
View File
@@ -0,0 +1,29 @@
import api from "../services/api";
import type { LoginCredentials, RegisterData, UserProfile } from "../types/auth";
export async function login(credentials: LoginCredentials): Promise<{ access: string; refresh: string }> {
const { data } = await api.post("/auth/token/", credentials);
return data;
}
export async function register(data: RegisterData): Promise<UserProfile> {
const { data: user } = await api.post<UserProfile>("/auth/register/", data);
return user;
}
export async function fetchProfile(): Promise<UserProfile> {
const { data } = await api.get<UserProfile>("/auth/me/");
return data;
}
export async function updateProfile(updates: Partial<UserProfile>): Promise<UserProfile> {
const { data } = await api.patch<UserProfile>("/auth/me/", updates);
return data;
}
export async function changePassword(oldPassword: string, newPassword: string): Promise<void> {
await api.post("/auth/change-password/", {
old_password: oldPassword,
new_password: newPassword,
});
}
+649
View File
@@ -0,0 +1,649 @@
/* ============================================
Cloud Reader — Global Styles
============================================ */
:root {
--color-bg: #0f1419;
--color-surface: #1a1f2e;
--color-surface-hover: #242a3d;
--color-border: #2a3042;
--color-text: #e1e4ed;
--color-text-muted: #8892a4;
--color-primary: #4f8cff;
--color-primary-hover: #3a75e6;
--color-danger: #f26c6c;
--color-success: #4caf7d;
--color-warning: #f5a623;
--radius: 8px;
--radius-lg: 12px;
--shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html, body {
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, sans-serif;
background: var(--color-bg);
color: var(--color-text);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
#root {
min-height: 100%;
display: flex;
flex-direction: column;
}
a {
color: var(--color-primary);
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
/* ==================== Buttons ==================== */
.btn-primary, .btn-secondary, .btn-danger {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 8px 16px;
border: none;
border-radius: var(--radius);
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background 0.15s, opacity 0.15s;
text-decoration: none;
}
.btn-primary {
background: var(--color-primary);
color: #fff;
}
.btn-primary:hover {
background: var(--color-primary-hover);
text-decoration: none;
}
.btn-primary:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-secondary {
background: var(--color-surface);
color: var(--color-text);
border: 1px solid var(--color-border);
}
.btn-secondary:hover {
background: var(--color-surface-hover);
text-decoration: none;
}
.btn-secondary:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-danger {
background: var(--color-danger);
color: #fff;
}
.btn-danger:hover {
opacity: 0.9;
text-decoration: none;
}
/* ==================== Forms ==================== */
.form-group {
margin-bottom: 16px;
}
.form-group label {
display: block;
margin-bottom: 6px;
font-size: 13px;
font-weight: 500;
color: var(--color-text-muted);
}
.form-group input {
width: 100%;
padding: 10px 12px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
color: var(--color-text);
font-size: 14px;
outline: none;
transition: border-color 0.15s;
}
.form-group input:focus {
border-color: var(--color-primary);
}
.error-message {
padding: 10px 12px;
background: rgba(242, 108, 108, 0.15);
border: 1px solid var(--color-danger);
border-radius: var(--radius);
color: var(--color-danger);
font-size: 13px;
margin-bottom: 16px;
}
.success-message {
padding: 10px 12px;
background: rgba(76, 175, 125, 0.15);
border: 1px solid var(--color-success);
border-radius: var(--radius);
color: var(--color-success);
font-size: 13px;
margin-bottom: 16px;
}
/* ==================== Layout ==================== */
.layout {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 24px;
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
gap: 12px;
}
.topbar .logo {
font-size: 18px;
font-weight: 600;
}
.topbar-right {
display: flex;
align-items: center;
gap: 12px;
}
.user-greeting {
font-size: 14px;
color: var(--color-text-muted);
}
.content {
flex: 1;
padding: 24px;
max-width: 1200px;
width: 100%;
margin: 0 auto;
}
.loading, .loading-screen, .not-found {
display: flex;
align-items: center;
justify-content: center;
height: 200px;
color: var(--color-text-muted);
font-size: 16px;
}
.loading-screen {
height: 100vh;
}
/* ==================== Auth Pages ==================== */
.auth-page {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
padding: 24px;
}
.auth-card {
width: 100%;
max-width: 400px;
padding: 32px;
background: var(--color-surface);
border-radius: var(--radius-lg);
box-shadow: var(--shadow);
}
.auth-card h1 {
font-size: 24px;
margin-bottom: 4px;
}
.auth-card h2 {
font-size: 16px;
font-weight: 400;
color: var(--color-text-muted);
margin-bottom: 24px;
}
.auth-card form {
display: flex;
flex-direction: column;
}
.auth-link {
margin-top: 16px;
font-size: 13px;
color: var(--color-text-muted);
text-align: center;
}
/* ==================== Library Page ==================== */
.library-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20px;
}
.library-header h2 {
font-size: 22px;
}
.search-bar {
margin-bottom: 20px;
}
.search-bar input {
width: 100%;
max-width: 500px;
padding: 10px 14px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius);
color: var(--color-text);
font-size: 14px;
outline: none;
}
.search-bar input:focus {
border-color: var(--color-primary);
}
.empty-state {
display: flex;
align-items: center;
justify-content: center;
min-height: 200px;
color: var(--color-text-muted);
text-align: center;
}
.empty-state p {
max-width: 400px;
}
.document-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 16px;
}
.document-card {
display: flex;
flex-direction: column;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
overflow: hidden;
transition: border-color 0.15s, transform 0.15s;
text-decoration: none;
color: inherit;
}
.document-card:hover {
border-color: var(--color-primary);
transform: translateY(-2px);
text-decoration: none;
}
.doc-cover {
height: 160px;
display: flex;
align-items: center;
justify-content: center;
background: var(--color-bg);
overflow: hidden;
}
.doc-cover img {
width: 100%;
height: 100%;
object-fit: cover;
}
.doc-cover-placeholder {
font-size: 32px;
font-weight: 700;
color: var(--color-text-muted);
}
.doc-info {
padding: 14px;
}
.doc-info h3 {
font-size: 15px;
font-weight: 600;
margin-bottom: 4px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.doc-author {
font-size: 13px;
color: var(--color-text-muted);
margin-bottom: 8px;
}
.doc-meta {
display: flex;
gap: 10px;
font-size: 12px;
color: var(--color-text-muted);
}
.doc-type {
text-transform: uppercase;
font-weight: 600;
}
/* ==================== Document Detail ==================== */
.doc-header {
display: flex;
gap: 24px;
margin-bottom: 32px;
}
.doc-cover-large {
width: 200px;
height: 280px;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
background: var(--color-surface);
border-radius: var(--radius-lg);
overflow: hidden;
}
.doc-cover-large img {
width: 100%;
height: 100%;
object-fit: cover;
}
.doc-cover-placeholder-large {
font-size: 48px;
font-weight: 700;
color: var(--color-text-muted);
}
.doc-metadata {
flex: 1;
}
.doc-metadata h2 {
font-size: 24px;
margin-bottom: 8px;
}
.doc-description {
margin: 12px 0;
line-height: 1.6;
color: var(--color-text-muted);
}
.doc-stats {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 16px 0;
font-size: 13px;
color: var(--color-text-muted);
}
.doc-stats span {
padding: 4px 10px;
background: var(--color-surface);
border-radius: 4px;
}
.doc-tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 12px 0;
}
.tag {
padding: 3px 8px;
background: var(--color-primary);
border-radius: 4px;
font-size: 12px;
color: #fff;
}
/* ==================== Reader ==================== */
.reader-layout {
display: flex;
flex-direction: column;
height: 100vh;
}
.reader-topbar {
display: flex;
align-items: center;
gap: 16px;
padding: 12px 24px;
background: var(--color-surface);
border-bottom: 1px solid var(--color-border);
}
.reader-title {
flex: 1;
font-weight: 600;
}
.reader-page-info {
color: var(--color-text-muted);
font-size: 14px;
}
.reader-content {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
overflow-y: auto;
}
.reader-viewport {
max-width: 800px;
width: 100%;
text-align: center;
}
.reader-placeholder {
font-size: 18px;
margin-bottom: 12px;
}
.reader-placeholder-sub {
color: var(--color-text-muted);
}
.reader-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 16px;
padding: 16px 24px;
background: var(--color-surface);
border-top: 1px solid var(--color-border);
}
.page-input {
display: flex;
align-items: center;
gap: 8px;
}
.page-input input {
width: 70px;
padding: 6px 10px;
text-align: center;
background: var(--color-bg);
border: 1px solid var(--color-border);
border-radius: var(--radius);
color: var(--color-text);
font-size: 14px;
}
/* ==================== Collections ==================== */
.create-collection-form {
display: flex;
flex-direction: column;
gap: 10px;
padding: 16px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
margin-bottom: 20px;
}
.create-collection-form input {
padding: 10px 12px;
background: var(--color-bg);
border: 1px solid var(--color-border);
border-radius: var(--radius);
color: var(--color-text);
font-size: 14px;
}
.form-actions {
display: flex;
gap: 8px;
}
.collection-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.collection-card {
display: flex;
align-items: center;
justify-content: space-between;
padding: 16px;
background: var(--color-surface);
border: 1px solid var(--color-border);
border-radius: var(--radius-lg);
}
.collection-info h3 {
font-size: 16px;
margin-bottom: 4px;
}
.collection-desc {
font-size: 13px;
color: var(--color-text-muted);
margin-bottom: 4px;
}
.collection-count {
font-size: 12px;
color: var(--color-text-muted);
}
.collection-actions {
display: flex;
gap: 8px;
}
/* ==================== Settings ==================== */
.settings-page {
max-width: 600px;
}
.settings-section {
margin-bottom: 32px;
}
.settings-section h2 {
font-size: 18px;
margin-bottom: 16px;
padding-bottom: 8px;
border-bottom: 1px solid var(--color-border);
}
.profile-info p {
margin-bottom: 8px;
font-size: 14px;
}
.profile-info strong {
color: var(--color-text-muted);
}
/* ==================== Highlights ==================== */
.recent-highlights {
margin-top: 24px;
}
.recent-highlights h3 {
font-size: 18px;
margin-bottom: 12px;
}
.highlight-card {
padding: 12px 16px;
margin-bottom: 8px;
background: var(--color-surface);
border-left: 4px solid var(--color-warning);
border-radius: var(--radius);
}
.highlight-text {
font-style: italic;
margin-bottom: 4px;
}
.highlight-page {
font-size: 12px;
color: var(--color-text-muted);
}
+34
View File
@@ -0,0 +1,34 @@
export interface LoginCredentials {
email: string;
password: string;
}
export interface RegisterData {
email: string;
username: string;
password: string;
password_confirm: string;
display_name?: string;
}
export interface AuthTokens {
access: string;
refresh: string;
}
export interface UserProfile {
id: number;
email: string;
username: string;
display_name: string;
avatar_url: string | null;
date_joined: string;
is_verified: boolean;
reading_preferences: Record<string, unknown>;
}
export interface ApiError {
detail: string;
code?: string;
fields?: Record<string, string[]>;
}
+25
View File
@@ -0,0 +1,25 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"paths": {
"@/*": ["./src/*"],
"@shared/*": ["../shared/src/*"]
}
},
"include": ["src"],
"references": [{ "path": "../shared/tsconfig.json" }]
}
+22
View File
@@ -0,0 +1,22 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"@shared": path.resolve(__dirname, "../shared/src"),
},
},
server: {
port: 5173,
proxy: {
"/api": {
target: "http://localhost:8000",
changeOrigin: true,
},
},
},
});