mirror of
https://github.com/Tony0410/readlater.git
synced 2026-06-10 14:05:56 +08:00
Initial commit: ReadLater v1.0
- Save articles via URL or bookmarklet - Clean dark reader with customizable fonts/sizing - Text-to-speech with browser + Kokoro support - Speed control up to 3x - Favorites and archive - SQLite database with Drizzle ORM - Docker deployment ready Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
112
src/app/api/articles/[id]/route.ts
Normal file
112
src/app/api/articles/[id]/route.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, schema } from "@/lib/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
interface RouteParams {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
// GET /api/articles/[id] - Get single article
|
||||
export async function GET(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
const article = await db
|
||||
.select()
|
||||
.from(schema.articles)
|
||||
.where(eq(schema.articles.id, id))
|
||||
.limit(1);
|
||||
|
||||
if (article.length === 0) {
|
||||
return NextResponse.json({ error: "Article not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(article[0]);
|
||||
} catch (error) {
|
||||
console.error("Error fetching article:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch article" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// PATCH /api/articles/[id] - Update article
|
||||
export async function PATCH(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const body = await request.json();
|
||||
|
||||
// Only allow updating specific fields
|
||||
const allowedFields = [
|
||||
"isFavorite",
|
||||
"isArchived",
|
||||
"readingProgress",
|
||||
"tags",
|
||||
"readAt",
|
||||
];
|
||||
const updates: Record<string, unknown> = { updatedAt: new Date() };
|
||||
|
||||
for (const field of allowedFields) {
|
||||
if (field in body) {
|
||||
if (field === "tags" && Array.isArray(body[field])) {
|
||||
updates[field] = JSON.stringify(body[field]);
|
||||
} else if (field === "readAt" && body[field]) {
|
||||
updates[field] = new Date(body[field]);
|
||||
} else {
|
||||
updates[field] = body[field];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await db
|
||||
.update(schema.articles)
|
||||
.set(updates)
|
||||
.where(eq(schema.articles.id, id));
|
||||
|
||||
const article = await db
|
||||
.select()
|
||||
.from(schema.articles)
|
||||
.where(eq(schema.articles.id, id))
|
||||
.limit(1);
|
||||
|
||||
if (article.length === 0) {
|
||||
return NextResponse.json({ error: "Article not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(article[0]);
|
||||
} catch (error) {
|
||||
console.error("Error updating article:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to update article" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/articles/[id] - Delete article
|
||||
export async function DELETE(request: NextRequest, { params }: RouteParams) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(schema.articles)
|
||||
.where(eq(schema.articles.id, id))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json({ error: "Article not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
await db.delete(schema.articles).where(eq(schema.articles.id, id));
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error("Error deleting article:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to delete article" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
93
src/app/api/articles/route.ts
Normal file
93
src/app/api/articles/route.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, schema } from "@/lib/db";
|
||||
import { extractArticle } from "@/lib/utils/extract";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
|
||||
// GET /api/articles - List all articles
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const filter = searchParams.get("filter"); // all, favorites, archived
|
||||
|
||||
let query = db.select().from(schema.articles);
|
||||
|
||||
if (filter === "favorites") {
|
||||
query = query.where(eq(schema.articles.isFavorite, true)) as typeof query;
|
||||
} else if (filter === "archived") {
|
||||
query = query.where(eq(schema.articles.isArchived, true)) as typeof query;
|
||||
} else {
|
||||
// Default: show non-archived
|
||||
query = query.where(eq(schema.articles.isArchived, false)) as typeof query;
|
||||
}
|
||||
|
||||
const articles = await query.orderBy(desc(schema.articles.createdAt));
|
||||
|
||||
return NextResponse.json(articles);
|
||||
} catch (error) {
|
||||
console.error("Error fetching articles:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Failed to fetch articles" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/articles - Save a new article
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { url } = body;
|
||||
|
||||
if (!url) {
|
||||
return NextResponse.json({ error: "URL is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if article already exists
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(schema.articles)
|
||||
.where(eq(schema.articles.url, url))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) {
|
||||
return NextResponse.json(
|
||||
{ error: "Article already saved", article: existing[0] },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
// Extract article content
|
||||
const extracted = await extractArticle(url);
|
||||
|
||||
const id = uuidv4();
|
||||
const newArticle: schema.NewArticle = {
|
||||
id,
|
||||
url,
|
||||
title: extracted.title,
|
||||
author: extracted.author,
|
||||
siteName: extracted.siteName,
|
||||
excerpt: extracted.excerpt,
|
||||
content: extracted.content,
|
||||
textContent: extracted.textContent,
|
||||
leadImage: extracted.leadImage,
|
||||
wordCount: extracted.wordCount,
|
||||
};
|
||||
|
||||
await db.insert(schema.articles).values(newArticle);
|
||||
|
||||
const article = await db
|
||||
.select()
|
||||
.from(schema.articles)
|
||||
.where(eq(schema.articles.id, id))
|
||||
.limit(1);
|
||||
|
||||
return NextResponse.json(article[0], { status: 201 });
|
||||
} catch (error) {
|
||||
console.error("Error saving article:", error);
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : "Failed to save article" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
140
src/app/api/save/route.ts
Normal file
140
src/app/api/save/route.ts
Normal file
@@ -0,0 +1,140 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { db, schema } from "@/lib/db";
|
||||
import { extractArticle } from "@/lib/utils/extract";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
// GET /api/save?url=... - Save article and return HTML response for bookmarklet
|
||||
export async function GET(request: NextRequest) {
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const url = searchParams.get("url");
|
||||
|
||||
const htmlResponse = (status: "success" | "error" | "exists", message: string) => {
|
||||
const bgColor = status === "success" ? "#22c55e" : status === "exists" ? "#eab308" : "#ef4444";
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>ReadLater</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: #000;
|
||||
color: #fff;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
.container {
|
||||
text-align: center;
|
||||
max-width: 300px;
|
||||
}
|
||||
.icon {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
border-radius: 50%;
|
||||
background: ${bgColor};
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: 0 auto 20px;
|
||||
}
|
||||
.icon svg {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
fill: white;
|
||||
}
|
||||
h1 {
|
||||
font-size: 18px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
p {
|
||||
color: #888;
|
||||
font-size: 14px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.close {
|
||||
margin-top: 20px;
|
||||
padding: 10px 20px;
|
||||
background: #333;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
font-size: 14px;
|
||||
}
|
||||
.close:hover {
|
||||
background: #444;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="icon">
|
||||
${status === "success" ? '<svg viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>' : status === "exists" ? '<svg viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>' : '<svg viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>'}
|
||||
</div>
|
||||
<h1>${status === "success" ? "Saved!" : status === "exists" ? "Already Saved" : "Error"}</h1>
|
||||
<p>${message}</p>
|
||||
<button class="close" onclick="window.close()">Close</button>
|
||||
</div>
|
||||
<script>
|
||||
setTimeout(() => window.close(), 3000);
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
return new NextResponse(html, {
|
||||
headers: { "Content-Type": "text/html" },
|
||||
});
|
||||
};
|
||||
|
||||
if (!url) {
|
||||
return htmlResponse("error", "No URL provided");
|
||||
}
|
||||
|
||||
try {
|
||||
const decodedUrl = decodeURIComponent(url);
|
||||
|
||||
// Check if article already exists
|
||||
const existing = await db
|
||||
.select()
|
||||
.from(schema.articles)
|
||||
.where(eq(schema.articles.url, decodedUrl))
|
||||
.limit(1);
|
||||
|
||||
if (existing.length > 0) {
|
||||
return htmlResponse("exists", `"${existing[0].title}" is already in your reading list`);
|
||||
}
|
||||
|
||||
// Extract article content
|
||||
const extracted = await extractArticle(decodedUrl);
|
||||
|
||||
const id = uuidv4();
|
||||
const newArticle: schema.NewArticle = {
|
||||
id,
|
||||
url: decodedUrl,
|
||||
title: extracted.title,
|
||||
author: extracted.author,
|
||||
siteName: extracted.siteName,
|
||||
excerpt: extracted.excerpt,
|
||||
content: extracted.content,
|
||||
textContent: extracted.textContent,
|
||||
leadImage: extracted.leadImage,
|
||||
wordCount: extracted.wordCount,
|
||||
};
|
||||
|
||||
await db.insert(schema.articles).values(newArticle);
|
||||
|
||||
return htmlResponse("success", `"${extracted.title}" has been added to your reading list`);
|
||||
} catch (error) {
|
||||
console.error("Error saving article:", error);
|
||||
return htmlResponse(
|
||||
"error",
|
||||
error instanceof Error ? error.message : "Failed to save article"
|
||||
);
|
||||
}
|
||||
}
|
||||
94
src/app/bookmarklet/page.tsx
Normal file
94
src/app/bookmarklet/page.tsx
Normal file
@@ -0,0 +1,94 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { BookOpen, Copy, Check } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function BookmarkletPage() {
|
||||
const [baseUrl, setBaseUrl] = useState("");
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setBaseUrl(window.location.origin);
|
||||
}, []);
|
||||
|
||||
const bookmarkletCode = `javascript:(function(){var url=encodeURIComponent(window.location.href);window.open('${baseUrl}/api/save?url='+url,'_blank','width=400,height=300');})();`;
|
||||
|
||||
const handleCopy = async () => {
|
||||
await navigator.clipboard.writeText(bookmarkletCode);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-[var(--background)] text-[var(--foreground)] p-8">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<Link
|
||||
href="/"
|
||||
className="flex items-center gap-2 text-[var(--accent)] hover:underline mb-8"
|
||||
>
|
||||
<BookOpen className="w-5 h-5" />
|
||||
Back to ReadLater
|
||||
</Link>
|
||||
|
||||
<h1 className="text-3xl font-bold mb-6">Bookmarklet</h1>
|
||||
|
||||
<div className="bg-[var(--surface)] rounded-lg p-6 mb-8">
|
||||
<h2 className="text-xl font-semibold mb-4">Quick Save Bookmarklet</h2>
|
||||
<p className="text-[var(--muted)] mb-6">
|
||||
Drag this button to your bookmarks bar, or right-click and "Add to Bookmarks".
|
||||
Then click it on any page to save the article to ReadLater.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-4 items-start">
|
||||
<a
|
||||
href={bookmarkletCode}
|
||||
onClick={(e) => e.preventDefault()}
|
||||
className="inline-flex items-center gap-2 px-6 py-3 bg-[var(--accent)] text-white rounded-lg font-medium cursor-move"
|
||||
title="Drag to bookmarks bar"
|
||||
>
|
||||
<BookOpen className="w-5 h-5" />
|
||||
Save to ReadLater
|
||||
</a>
|
||||
|
||||
<button
|
||||
onClick={handleCopy}
|
||||
className="inline-flex items-center gap-2 px-4 py-3 border border-[var(--border)] rounded-lg hover:bg-[var(--surface)] transition-colors"
|
||||
>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="w-5 h-5 text-green-500" />
|
||||
Copied!
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="w-5 h-5" />
|
||||
Copy code
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-[var(--surface)] rounded-lg p-6">
|
||||
<h2 className="text-xl font-semibold mb-4">Manual Installation</h2>
|
||||
<p className="text-[var(--muted)] mb-4">
|
||||
If dragging doesn't work, create a new bookmark and paste this as the URL:
|
||||
</p>
|
||||
<pre className="bg-[var(--background)] p-4 rounded-lg overflow-x-auto text-sm">
|
||||
<code className="text-[var(--muted)]">{bookmarkletCode}</code>
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 text-[var(--muted)] text-sm">
|
||||
<h3 className="font-semibold mb-2">How it works:</h3>
|
||||
<ol className="list-decimal list-inside space-y-1">
|
||||
<li>Click the bookmarklet on any article page</li>
|
||||
<li>A popup will confirm the article was saved</li>
|
||||
<li>The article appears in your ReadLater list</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
BIN
src/app/favicon.ico
Normal file
BIN
src/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
156
src/app/globals.css
Normal file
156
src/app/globals.css
Normal file
@@ -0,0 +1,156 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #000000;
|
||||
--foreground: #ffffff;
|
||||
--muted: #888888;
|
||||
--border: #333333;
|
||||
--accent: #3b82f6;
|
||||
--surface: #111111;
|
||||
}
|
||||
|
||||
[data-theme="light"] {
|
||||
--background: #ffffff;
|
||||
--foreground: #1a1a1a;
|
||||
--muted: #666666;
|
||||
--border: #e5e5e5;
|
||||
--accent: #2563eb;
|
||||
--surface: #f5f5f5;
|
||||
}
|
||||
|
||||
[data-theme="sepia"] {
|
||||
--background: #f4ecd8;
|
||||
--foreground: #5c4b37;
|
||||
--muted: #8b7355;
|
||||
--border: #d4c4a8;
|
||||
--accent: #8b5a2b;
|
||||
--surface: #ebe3d0;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-border: var(--border);
|
||||
--color-accent: var(--accent);
|
||||
--color-surface: var(--surface);
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
transition: background-color 0.2s, color 0.2s;
|
||||
}
|
||||
|
||||
/* Reader fonts */
|
||||
.font-serif {
|
||||
font-family: Georgia, Cambria, "Times New Roman", Times, serif;
|
||||
}
|
||||
|
||||
.font-sans {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
|
||||
.font-mono {
|
||||
font-family: "SF Mono", Monaco, "Cascadia Code", monospace;
|
||||
}
|
||||
|
||||
.font-system {
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
}
|
||||
|
||||
/* Reader content styles */
|
||||
.reader-content {
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.reader-content p {
|
||||
margin-bottom: 1.5em;
|
||||
}
|
||||
|
||||
.reader-content h1,
|
||||
.reader-content h2,
|
||||
.reader-content h3,
|
||||
.reader-content h4 {
|
||||
margin-top: 1.5em;
|
||||
margin-bottom: 0.75em;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.reader-content a {
|
||||
color: var(--accent);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.reader-content img {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border-radius: 0.5rem;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.reader-content blockquote {
|
||||
border-left: 3px solid var(--border);
|
||||
padding-left: 1em;
|
||||
margin-left: 0;
|
||||
font-style: italic;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.reader-content pre {
|
||||
background: var(--surface);
|
||||
padding: 1em;
|
||||
border-radius: 0.5rem;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.reader-content code {
|
||||
background: var(--surface);
|
||||
padding: 0.2em 0.4em;
|
||||
border-radius: 0.25rem;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
.reader-content pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.reader-content ul,
|
||||
.reader-content ol {
|
||||
margin-left: 1.5em;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
|
||||
.reader-content li {
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
|
||||
/* TTS highlight */
|
||||
.tts-highlight {
|
||||
background-color: var(--accent);
|
||||
color: white;
|
||||
padding: 0.1em 0.2em;
|
||||
border-radius: 0.2em;
|
||||
}
|
||||
|
||||
/* Scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: var(--background);
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--border);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--muted);
|
||||
}
|
||||
19
src/app/layout.tsx
Normal file
19
src/app/layout.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { Metadata } from "next";
|
||||
import "./globals.css";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "ReadLater - Save and Read Articles",
|
||||
description: "Self-hosted read-it-later app with text-to-speech",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en" data-theme="dark">
|
||||
<body className="antialiased">{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
249
src/app/page.tsx
Normal file
249
src/app/page.tsx
Normal file
@@ -0,0 +1,249 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { Article } from "@/lib/types";
|
||||
import { useReaderSettings, useTTSSettings } from "@/hooks/useSettings";
|
||||
import { useTTS } from "@/hooks/useTTS";
|
||||
import { ArticleList } from "@/components/ArticleList";
|
||||
import { Reader } from "@/components/Reader";
|
||||
import { SettingsPanel } from "@/components/SettingsPanel";
|
||||
import { TTSControls } from "@/components/TTSControls";
|
||||
import { AddArticle } from "@/components/AddArticle";
|
||||
import { BookOpen, Star, Archive, Menu } from "lucide-react";
|
||||
|
||||
type FilterType = "all" | "favorites" | "archived";
|
||||
|
||||
export default function Home() {
|
||||
const [articles, setArticles] = useState<Article[]>([]);
|
||||
const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);
|
||||
const [filter, setFilter] = useState<FilterType>("all");
|
||||
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
||||
const [isSidebarOpen, setIsSidebarOpen] = useState(true);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
const [readerSettings, setReaderSettings] = useReaderSettings();
|
||||
const [ttsSettings, setTTSSettings] = useTTSSettings();
|
||||
|
||||
const tts = useTTS({
|
||||
settings: ttsSettings,
|
||||
text: selectedArticle?.textContent || "",
|
||||
});
|
||||
|
||||
// Apply theme
|
||||
useEffect(() => {
|
||||
document.documentElement.setAttribute("data-theme", readerSettings.theme);
|
||||
}, [readerSettings.theme]);
|
||||
|
||||
// Fetch articles
|
||||
const fetchArticles = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/articles?filter=${filter}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setArticles(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch articles:", error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [filter]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchArticles();
|
||||
}, [fetchArticles]);
|
||||
|
||||
// Add article
|
||||
const handleAddArticle = async (url: string) => {
|
||||
const response = await fetch("/api/articles", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ url }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
throw new Error(data.error || "Failed to add article");
|
||||
}
|
||||
|
||||
await fetchArticles();
|
||||
};
|
||||
|
||||
// Toggle favorite
|
||||
const handleToggleFavorite = async (id: string, isFavorite: boolean) => {
|
||||
await fetch(`/api/articles/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ isFavorite }),
|
||||
});
|
||||
|
||||
setArticles((prev) =>
|
||||
prev.map((a) => (a.id === id ? { ...a, isFavorite } : a))
|
||||
);
|
||||
|
||||
if (selectedArticle?.id === id) {
|
||||
setSelectedArticle((prev) => (prev ? { ...prev, isFavorite } : null));
|
||||
}
|
||||
};
|
||||
|
||||
// Toggle archive
|
||||
const handleToggleArchive = async (id: string, isArchived: boolean) => {
|
||||
await fetch(`/api/articles/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ isArchived }),
|
||||
});
|
||||
|
||||
await fetchArticles();
|
||||
|
||||
if (selectedArticle?.id === id) {
|
||||
setSelectedArticle(null);
|
||||
}
|
||||
};
|
||||
|
||||
// Delete article
|
||||
const handleDelete = async (id: string) => {
|
||||
await fetch(`/api/articles/${id}`, { method: "DELETE" });
|
||||
await fetchArticles();
|
||||
|
||||
if (selectedArticle?.id === id) {
|
||||
setSelectedArticle(null);
|
||||
}
|
||||
};
|
||||
|
||||
// Reading view
|
||||
if (selectedArticle) {
|
||||
return (
|
||||
<>
|
||||
<Reader
|
||||
article={selectedArticle}
|
||||
settings={readerSettings}
|
||||
onBack={() => {
|
||||
tts.stop();
|
||||
setSelectedArticle(null);
|
||||
}}
|
||||
onToggleFavorite={() =>
|
||||
handleToggleFavorite(selectedArticle.id, !selectedArticle.isFavorite)
|
||||
}
|
||||
onOpenSettings={() => setIsSettingsOpen(true)}
|
||||
>
|
||||
<TTSControls
|
||||
isPlaying={tts.isPlaying}
|
||||
isPaused={tts.isPaused}
|
||||
isLoading={tts.isLoading}
|
||||
onPlay={tts.play}
|
||||
onPause={tts.pause}
|
||||
onResume={tts.resume}
|
||||
onStop={tts.stop}
|
||||
/>
|
||||
</Reader>
|
||||
<SettingsPanel
|
||||
isOpen={isSettingsOpen}
|
||||
onClose={() => setIsSettingsOpen(false)}
|
||||
readerSettings={readerSettings}
|
||||
onReaderSettingsChange={setReaderSettings}
|
||||
ttsSettings={ttsSettings}
|
||||
onTTSSettingsChange={setTTSSettings}
|
||||
availableVoices={tts.voices}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// List view
|
||||
return (
|
||||
<div className="min-h-screen flex">
|
||||
{/* Sidebar */}
|
||||
<aside
|
||||
className={`${
|
||||
isSidebarOpen ? "w-64" : "w-0"
|
||||
} flex-shrink-0 border-r border-[var(--border)] transition-all duration-200 overflow-hidden`}
|
||||
>
|
||||
<div className="w-64 h-full flex flex-col">
|
||||
<div className="p-4 border-b border-[var(--border)]">
|
||||
<h1 className="text-xl font-bold flex items-center gap-2">
|
||||
<BookOpen className="w-6 h-6" />
|
||||
ReadLater
|
||||
</h1>
|
||||
</div>
|
||||
<nav className="flex-1 p-2">
|
||||
{[
|
||||
{ value: "all", label: "All Articles", icon: BookOpen },
|
||||
{ value: "favorites", label: "Favorites", icon: Star },
|
||||
{ value: "archived", label: "Archived", icon: Archive },
|
||||
].map(({ value, label, icon: Icon }) => (
|
||||
<button
|
||||
key={value}
|
||||
onClick={() => setFilter(value as FilterType)}
|
||||
className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-colors ${
|
||||
filter === value
|
||||
? "bg-[var(--accent)] text-white"
|
||||
: "text-[var(--foreground)] hover:bg-[var(--surface)]"
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-5 h-5" />
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
<div className="p-4 border-t border-[var(--border)]">
|
||||
<button
|
||||
onClick={() => setIsSettingsOpen(true)}
|
||||
className="w-full px-4 py-2 text-[var(--muted)] hover:text-[var(--foreground)] transition-colors text-left"
|
||||
>
|
||||
Settings
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Main content */}
|
||||
<main className="flex-1 flex flex-col min-w-0">
|
||||
<header className="flex items-center gap-4 px-4 py-3 border-b border-[var(--border)]">
|
||||
<button
|
||||
onClick={() => setIsSidebarOpen(!isSidebarOpen)}
|
||||
className="p-2 rounded hover:bg-[var(--surface)] transition-colors lg:hidden"
|
||||
>
|
||||
<Menu className="w-5 h-5" />
|
||||
</button>
|
||||
<h2 className="text-lg font-semibold">
|
||||
{filter === "all"
|
||||
? "All Articles"
|
||||
: filter === "favorites"
|
||||
? "Favorites"
|
||||
: "Archived"}
|
||||
</h2>
|
||||
<span className="text-[var(--muted)]">({articles.length})</span>
|
||||
</header>
|
||||
|
||||
<AddArticle onAdd={handleAddArticle} />
|
||||
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<div className="animate-pulse text-[var(--muted)]">Loading...</div>
|
||||
</div>
|
||||
) : (
|
||||
<ArticleList
|
||||
articles={articles}
|
||||
onSelect={setSelectedArticle}
|
||||
onToggleFavorite={handleToggleFavorite}
|
||||
onToggleArchive={handleToggleArchive}
|
||||
onDelete={handleDelete}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<SettingsPanel
|
||||
isOpen={isSettingsOpen}
|
||||
onClose={() => setIsSettingsOpen(false)}
|
||||
readerSettings={readerSettings}
|
||||
onReaderSettingsChange={setReaderSettings}
|
||||
ttsSettings={ttsSettings}
|
||||
onTTSSettingsChange={setTTSSettings}
|
||||
availableVoices={tts.voices}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
61
src/components/AddArticle.tsx
Normal file
61
src/components/AddArticle.tsx
Normal file
@@ -0,0 +1,61 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Plus, Loader2 } from "lucide-react";
|
||||
|
||||
interface AddArticleProps {
|
||||
onAdd: (url: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function AddArticle({ onAdd }: AddArticleProps) {
|
||||
const [url, setUrl] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!url.trim()) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
await onAdd(url.trim());
|
||||
setUrl("");
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Failed to add article");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="p-4 border-b border-[var(--border)]">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder="Paste article URL..."
|
||||
className="flex-1 px-4 py-2 rounded-lg border border-[var(--border)] bg-[var(--background)] text-[var(--foreground)] placeholder-[var(--muted)] focus:outline-none focus:border-[var(--accent)]"
|
||||
disabled={isLoading}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading || !url.trim()}
|
||||
className="px-4 py-2 rounded-lg bg-[var(--accent)] text-white font-medium disabled:opacity-50 disabled:cursor-not-allowed hover:opacity-90 transition-opacity flex items-center gap-2"
|
||||
>
|
||||
{isLoading ? (
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
) : (
|
||||
<Plus className="w-5 h-5" />
|
||||
)}
|
||||
<span className="hidden sm:inline">Add</span>
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="mt-2 text-sm text-red-500">{error}</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
130
src/components/ArticleList.tsx
Normal file
130
src/components/ArticleList.tsx
Normal file
@@ -0,0 +1,130 @@
|
||||
"use client";
|
||||
|
||||
import { Article } from "@/lib/types";
|
||||
import { Star, Archive, Trash2, ExternalLink, Clock } from "lucide-react";
|
||||
import { formatDistanceToNow } from "@/lib/utils/date";
|
||||
|
||||
interface ArticleListProps {
|
||||
articles: Article[];
|
||||
selectedId?: string;
|
||||
onSelect: (article: Article) => void;
|
||||
onToggleFavorite: (id: string, isFavorite: boolean) => void;
|
||||
onToggleArchive: (id: string, isArchived: boolean) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
export function ArticleList({
|
||||
articles,
|
||||
selectedId,
|
||||
onSelect,
|
||||
onToggleFavorite,
|
||||
onToggleArchive,
|
||||
onDelete,
|
||||
}: ArticleListProps) {
|
||||
if (articles.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-64 text-[var(--muted)]">
|
||||
<p>No articles yet</p>
|
||||
<p className="text-sm mt-2">Add a URL to get started</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="divide-y divide-[var(--border)]">
|
||||
{articles.map((article) => (
|
||||
<div
|
||||
key={article.id}
|
||||
className={`p-4 cursor-pointer transition-colors hover:bg-[var(--surface)] ${
|
||||
selectedId === article.id ? "bg-[var(--surface)]" : ""
|
||||
}`}
|
||||
onClick={() => onSelect(article)}
|
||||
>
|
||||
<div className="flex gap-4">
|
||||
{article.leadImage && (
|
||||
<img
|
||||
src={article.leadImage}
|
||||
alt=""
|
||||
className="w-20 h-20 object-cover rounded flex-shrink-0"
|
||||
/>
|
||||
)}
|
||||
<div className="flex-1 min-w-0">
|
||||
<h3 className="font-medium truncate mb-1">{article.title}</h3>
|
||||
<p className="text-sm text-[var(--muted)] mb-2">
|
||||
{article.siteName}
|
||||
{article.author && ` · ${article.author}`}
|
||||
</p>
|
||||
{article.excerpt && (
|
||||
<p className="text-sm text-[var(--muted)] line-clamp-2">
|
||||
{article.excerpt}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-4 mt-2 text-xs text-[var(--muted)]">
|
||||
<span className="flex items-center gap-1">
|
||||
<Clock className="w-3 h-3" />
|
||||
{Math.ceil(article.wordCount / 200)} min read
|
||||
</span>
|
||||
<span>{formatDistanceToNow(article.createdAt)}</span>
|
||||
{article.readingProgress > 0 && article.readingProgress < 100 && (
|
||||
<span>{article.readingProgress}% read</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-3">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onToggleFavorite(article.id, !article.isFavorite);
|
||||
}}
|
||||
className={`p-2 rounded transition-colors ${
|
||||
article.isFavorite
|
||||
? "text-yellow-500 bg-yellow-500/10"
|
||||
: "text-[var(--muted)] hover:text-[var(--foreground)] hover:bg-[var(--surface)]"
|
||||
}`}
|
||||
title={article.isFavorite ? "Remove from favorites" : "Add to favorites"}
|
||||
>
|
||||
<Star className="w-4 h-4" fill={article.isFavorite ? "currentColor" : "none"} />
|
||||
</button>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onToggleArchive(article.id, !article.isArchived);
|
||||
}}
|
||||
className={`p-2 rounded transition-colors ${
|
||||
article.isArchived
|
||||
? "text-green-500 bg-green-500/10"
|
||||
: "text-[var(--muted)] hover:text-[var(--foreground)] hover:bg-[var(--surface)]"
|
||||
}`}
|
||||
title={article.isArchived ? "Unarchive" : "Archive"}
|
||||
>
|
||||
<Archive className="w-4 h-4" />
|
||||
</button>
|
||||
<a
|
||||
href={article.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="p-2 rounded text-[var(--muted)] hover:text-[var(--foreground)] hover:bg-[var(--surface)] transition-colors"
|
||||
title="Open original"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</a>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (confirm("Delete this article?")) {
|
||||
onDelete(article.id);
|
||||
}
|
||||
}}
|
||||
className="p-2 rounded text-[var(--muted)] hover:text-red-500 hover:bg-red-500/10 transition-colors ml-auto"
|
||||
title="Delete"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
116
src/components/Reader.tsx
Normal file
116
src/components/Reader.tsx
Normal file
@@ -0,0 +1,116 @@
|
||||
"use client";
|
||||
|
||||
import { Article, ReaderSettings } from "@/lib/types";
|
||||
import { ArrowLeft, Star, Settings } from "lucide-react";
|
||||
|
||||
interface ReaderProps {
|
||||
article: Article;
|
||||
settings: ReaderSettings;
|
||||
onBack: () => void;
|
||||
onToggleFavorite: () => void;
|
||||
onOpenSettings: () => void;
|
||||
children?: React.ReactNode; // TTS controls slot
|
||||
}
|
||||
|
||||
export function Reader({
|
||||
article,
|
||||
settings,
|
||||
onBack,
|
||||
onToggleFavorite,
|
||||
onOpenSettings,
|
||||
children,
|
||||
}: ReaderProps) {
|
||||
const fontClass = {
|
||||
system: "font-system",
|
||||
serif: "font-serif",
|
||||
sans: "font-sans",
|
||||
mono: "font-mono",
|
||||
}[settings.fontFamily];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
{/* Header */}
|
||||
<header className="sticky top-0 z-10 bg-[var(--background)] border-b border-[var(--border)]">
|
||||
<div className="flex items-center justify-between px-4 py-3">
|
||||
<button
|
||||
onClick={onBack}
|
||||
className="flex items-center gap-2 text-[var(--muted)] hover:text-[var(--foreground)] transition-colors"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5" />
|
||||
<span className="hidden sm:inline">Back</span>
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
{children}
|
||||
<button
|
||||
onClick={onToggleFavorite}
|
||||
className={`p-2 rounded transition-colors ${
|
||||
article.isFavorite
|
||||
? "text-yellow-500"
|
||||
: "text-[var(--muted)] hover:text-[var(--foreground)]"
|
||||
}`}
|
||||
title={article.isFavorite ? "Remove from favorites" : "Add to favorites"}
|
||||
>
|
||||
<Star className="w-5 h-5" fill={article.isFavorite ? "currentColor" : "none"} />
|
||||
</button>
|
||||
<button
|
||||
onClick={onOpenSettings}
|
||||
className="p-2 rounded text-[var(--muted)] hover:text-[var(--foreground)] transition-colors"
|
||||
title="Reader settings"
|
||||
>
|
||||
<Settings className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Article content */}
|
||||
<article
|
||||
className={`mx-auto px-4 py-8 ${fontClass}`}
|
||||
style={{
|
||||
maxWidth: `${settings.maxWidth}px`,
|
||||
fontSize: `${settings.fontSize}px`,
|
||||
lineHeight: settings.lineHeight,
|
||||
}}
|
||||
>
|
||||
{/* Article header */}
|
||||
<header className="mb-8">
|
||||
<h1 className="text-2xl sm:text-3xl font-bold mb-4" style={{ lineHeight: 1.3 }}>
|
||||
{article.title}
|
||||
</h1>
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-[var(--muted)] text-sm">
|
||||
{article.siteName && <span>{article.siteName}</span>}
|
||||
{article.author && <span>By {article.author}</span>}
|
||||
<span>{Math.ceil(article.wordCount / 200)} min read</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Lead image */}
|
||||
{article.leadImage && (
|
||||
<img
|
||||
src={article.leadImage}
|
||||
alt=""
|
||||
className="w-full rounded-lg mb-8 max-h-96 object-cover"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Content */}
|
||||
<div
|
||||
className="reader-content"
|
||||
dangerouslySetInnerHTML={{ __html: article.content }}
|
||||
/>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="mt-12 pt-8 border-t border-[var(--border)]">
|
||||
<a
|
||||
href={article.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-[var(--accent)] hover:underline"
|
||||
>
|
||||
View original article
|
||||
</a>
|
||||
</footer>
|
||||
</article>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
297
src/components/SettingsPanel.tsx
Normal file
297
src/components/SettingsPanel.tsx
Normal file
@@ -0,0 +1,297 @@
|
||||
"use client";
|
||||
|
||||
import { ReaderSettings, TTSSettings } from "@/lib/types";
|
||||
import { X, Sun, Moon, BookOpen } from "lucide-react";
|
||||
|
||||
interface SettingsPanelProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
readerSettings: ReaderSettings;
|
||||
onReaderSettingsChange: (settings: ReaderSettings) => void;
|
||||
ttsSettings: TTSSettings;
|
||||
onTTSSettingsChange: (settings: TTSSettings) => void;
|
||||
availableVoices: SpeechSynthesisVoice[];
|
||||
}
|
||||
|
||||
export function SettingsPanel({
|
||||
isOpen,
|
||||
onClose,
|
||||
readerSettings,
|
||||
onReaderSettingsChange,
|
||||
ttsSettings,
|
||||
onTTSSettingsChange,
|
||||
availableVoices,
|
||||
}: SettingsPanelProps) {
|
||||
if (!isOpen) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className="fixed inset-0 bg-black/50 z-40"
|
||||
onClick={onClose}
|
||||
/>
|
||||
|
||||
{/* Panel */}
|
||||
<div className="fixed right-0 top-0 h-full w-full max-w-md bg-[var(--background)] border-l border-[var(--border)] z-50 overflow-y-auto">
|
||||
<div className="p-6">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h2 className="text-xl font-semibold">Settings</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="p-2 rounded hover:bg-[var(--surface)] transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Theme */}
|
||||
<section className="mb-8">
|
||||
<h3 className="text-sm font-medium text-[var(--muted)] uppercase tracking-wide mb-4">
|
||||
Theme
|
||||
</h3>
|
||||
<div className="flex gap-2">
|
||||
{[
|
||||
{ value: "dark", icon: Moon, label: "Dark" },
|
||||
{ value: "light", icon: Sun, label: "Light" },
|
||||
{ value: "sepia", icon: BookOpen, label: "Sepia" },
|
||||
].map(({ value, icon: Icon, label }) => (
|
||||
<button
|
||||
key={value}
|
||||
onClick={() =>
|
||||
onReaderSettingsChange({
|
||||
...readerSettings,
|
||||
theme: value as ReaderSettings["theme"],
|
||||
})
|
||||
}
|
||||
className={`flex-1 flex flex-col items-center gap-2 p-4 rounded-lg border transition-colors ${
|
||||
readerSettings.theme === value
|
||||
? "border-[var(--accent)] bg-[var(--accent)]/10"
|
||||
: "border-[var(--border)] hover:border-[var(--muted)]"
|
||||
}`}
|
||||
>
|
||||
<Icon className="w-5 h-5" />
|
||||
<span className="text-sm">{label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Font Size */}
|
||||
<section className="mb-8">
|
||||
<h3 className="text-sm font-medium text-[var(--muted)] uppercase tracking-wide mb-4">
|
||||
Font Size: {readerSettings.fontSize}px
|
||||
</h3>
|
||||
<input
|
||||
type="range"
|
||||
min="14"
|
||||
max="32"
|
||||
value={readerSettings.fontSize}
|
||||
onChange={(e) =>
|
||||
onReaderSettingsChange({
|
||||
...readerSettings,
|
||||
fontSize: parseInt(e.target.value),
|
||||
})
|
||||
}
|
||||
className="w-full accent-[var(--accent)]"
|
||||
/>
|
||||
<div className="flex justify-between text-xs text-[var(--muted)] mt-1">
|
||||
<span>14px</span>
|
||||
<span>32px</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Font Family */}
|
||||
<section className="mb-8">
|
||||
<h3 className="text-sm font-medium text-[var(--muted)] uppercase tracking-wide mb-4">
|
||||
Font
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{[
|
||||
{ value: "serif", label: "Serif", sample: "Georgia" },
|
||||
{ value: "sans", label: "Sans", sample: "Helvetica" },
|
||||
{ value: "mono", label: "Mono", sample: "Monaco" },
|
||||
{ value: "system", label: "System", sample: "Default" },
|
||||
].map(({ value, label, sample }) => (
|
||||
<button
|
||||
key={value}
|
||||
onClick={() =>
|
||||
onReaderSettingsChange({
|
||||
...readerSettings,
|
||||
fontFamily: value as ReaderSettings["fontFamily"],
|
||||
})
|
||||
}
|
||||
className={`p-3 rounded-lg border text-left transition-colors ${
|
||||
readerSettings.fontFamily === value
|
||||
? "border-[var(--accent)] bg-[var(--accent)]/10"
|
||||
: "border-[var(--border)] hover:border-[var(--muted)]"
|
||||
}`}
|
||||
>
|
||||
<div className={`font-${value} text-lg`}>{label}</div>
|
||||
<div className="text-xs text-[var(--muted)]">{sample}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Line Height */}
|
||||
<section className="mb-8">
|
||||
<h3 className="text-sm font-medium text-[var(--muted)] uppercase tracking-wide mb-4">
|
||||
Line Height: {readerSettings.lineHeight}
|
||||
</h3>
|
||||
<input
|
||||
type="range"
|
||||
min="1.4"
|
||||
max="2.2"
|
||||
step="0.1"
|
||||
value={readerSettings.lineHeight}
|
||||
onChange={(e) =>
|
||||
onReaderSettingsChange({
|
||||
...readerSettings,
|
||||
lineHeight: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
className="w-full accent-[var(--accent)]"
|
||||
/>
|
||||
<div className="flex justify-between text-xs text-[var(--muted)] mt-1">
|
||||
<span>Tight</span>
|
||||
<span>Loose</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Content Width */}
|
||||
<section className="mb-8">
|
||||
<h3 className="text-sm font-medium text-[var(--muted)] uppercase tracking-wide mb-4">
|
||||
Content Width: {readerSettings.maxWidth}px
|
||||
</h3>
|
||||
<input
|
||||
type="range"
|
||||
min="500"
|
||||
max="900"
|
||||
step="50"
|
||||
value={readerSettings.maxWidth}
|
||||
onChange={(e) =>
|
||||
onReaderSettingsChange({
|
||||
...readerSettings,
|
||||
maxWidth: parseInt(e.target.value),
|
||||
})
|
||||
}
|
||||
className="w-full accent-[var(--accent)]"
|
||||
/>
|
||||
<div className="flex justify-between text-xs text-[var(--muted)] mt-1">
|
||||
<span>Narrow</span>
|
||||
<span>Wide</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<hr className="border-[var(--border)] my-8" />
|
||||
|
||||
{/* TTS Settings */}
|
||||
<section className="mb-8">
|
||||
<h3 className="text-sm font-medium text-[var(--muted)] uppercase tracking-wide mb-4">
|
||||
Text-to-Speech Engine
|
||||
</h3>
|
||||
<div className="flex gap-2">
|
||||
{[
|
||||
{ value: "browser", label: "Browser" },
|
||||
{ value: "kokoro", label: "Kokoro" },
|
||||
].map(({ value, label }) => (
|
||||
<button
|
||||
key={value}
|
||||
onClick={() =>
|
||||
onTTSSettingsChange({
|
||||
...ttsSettings,
|
||||
engine: value as TTSSettings["engine"],
|
||||
})
|
||||
}
|
||||
className={`flex-1 p-3 rounded-lg border transition-colors ${
|
||||
ttsSettings.engine === value
|
||||
? "border-[var(--accent)] bg-[var(--accent)]/10"
|
||||
: "border-[var(--border)] hover:border-[var(--muted)]"
|
||||
}`}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* TTS Speed */}
|
||||
<section className="mb-8">
|
||||
<h3 className="text-sm font-medium text-[var(--muted)] uppercase tracking-wide mb-4">
|
||||
TTS Speed: {ttsSettings.speed}x
|
||||
</h3>
|
||||
<input
|
||||
type="range"
|
||||
min="0.5"
|
||||
max="3"
|
||||
step="0.1"
|
||||
value={ttsSettings.speed}
|
||||
onChange={(e) =>
|
||||
onTTSSettingsChange({
|
||||
...ttsSettings,
|
||||
speed: parseFloat(e.target.value),
|
||||
})
|
||||
}
|
||||
className="w-full accent-[var(--accent)]"
|
||||
/>
|
||||
<div className="flex justify-between text-xs text-[var(--muted)] mt-1">
|
||||
<span>0.5x</span>
|
||||
<span>3x</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Browser Voice Selection */}
|
||||
{ttsSettings.engine === "browser" && availableVoices.length > 0 && (
|
||||
<section className="mb-8">
|
||||
<h3 className="text-sm font-medium text-[var(--muted)] uppercase tracking-wide mb-4">
|
||||
Voice
|
||||
</h3>
|
||||
<select
|
||||
value={ttsSettings.voice}
|
||||
onChange={(e) =>
|
||||
onTTSSettingsChange({
|
||||
...ttsSettings,
|
||||
voice: e.target.value,
|
||||
})
|
||||
}
|
||||
className="w-full p-3 rounded-lg border border-[var(--border)] bg-[var(--background)] text-[var(--foreground)]"
|
||||
>
|
||||
<option value="">Default</option>
|
||||
{availableVoices.map((voice) => (
|
||||
<option key={voice.voiceURI} value={voice.voiceURI}>
|
||||
{voice.name} ({voice.lang})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Kokoro URL */}
|
||||
{ttsSettings.engine === "kokoro" && (
|
||||
<section className="mb-8">
|
||||
<h3 className="text-sm font-medium text-[var(--muted)] uppercase tracking-wide mb-4">
|
||||
Kokoro API URL
|
||||
</h3>
|
||||
<input
|
||||
type="text"
|
||||
value={ttsSettings.kokoroUrl}
|
||||
onChange={(e) =>
|
||||
onTTSSettingsChange({
|
||||
...ttsSettings,
|
||||
kokoroUrl: e.target.value,
|
||||
})
|
||||
}
|
||||
placeholder="http://localhost:8880"
|
||||
className="w-full p-3 rounded-lg border border-[var(--border)] bg-[var(--background)] text-[var(--foreground)]"
|
||||
/>
|
||||
<p className="text-xs text-[var(--muted)] mt-2">
|
||||
URL of your Kokoro-FastAPI server
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
79
src/components/TTSControls.tsx
Normal file
79
src/components/TTSControls.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { Play, Pause, Square, Loader2, Volume2 } from "lucide-react";
|
||||
|
||||
interface TTSControlsProps {
|
||||
isPlaying: boolean;
|
||||
isPaused: boolean;
|
||||
isLoading: boolean;
|
||||
onPlay: () => void;
|
||||
onPause: () => void;
|
||||
onResume: () => void;
|
||||
onStop: () => void;
|
||||
}
|
||||
|
||||
export function TTSControls({
|
||||
isPlaying,
|
||||
isPaused,
|
||||
isLoading,
|
||||
onPlay,
|
||||
onPause,
|
||||
onResume,
|
||||
onStop,
|
||||
}: TTSControlsProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
{isLoading ? (
|
||||
<button
|
||||
disabled
|
||||
className="p-2 rounded text-[var(--muted)]"
|
||||
title="Loading..."
|
||||
>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
</button>
|
||||
) : isPlaying && !isPaused ? (
|
||||
<>
|
||||
<button
|
||||
onClick={onPause}
|
||||
className="p-2 rounded text-[var(--accent)] hover:bg-[var(--accent)]/10 transition-colors"
|
||||
title="Pause"
|
||||
>
|
||||
<Pause className="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={onStop}
|
||||
className="p-2 rounded text-[var(--muted)] hover:text-[var(--foreground)] hover:bg-[var(--surface)] transition-colors"
|
||||
title="Stop"
|
||||
>
|
||||
<Square className="w-5 h-5" />
|
||||
</button>
|
||||
</>
|
||||
) : isPaused ? (
|
||||
<>
|
||||
<button
|
||||
onClick={onResume}
|
||||
className="p-2 rounded text-[var(--accent)] hover:bg-[var(--accent)]/10 transition-colors"
|
||||
title="Resume"
|
||||
>
|
||||
<Play className="w-5 h-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={onStop}
|
||||
className="p-2 rounded text-[var(--muted)] hover:text-[var(--foreground)] hover:bg-[var(--surface)] transition-colors"
|
||||
title="Stop"
|
||||
>
|
||||
<Square className="w-5 h-5" />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
onClick={onPlay}
|
||||
className="p-2 rounded text-[var(--muted)] hover:text-[var(--foreground)] hover:bg-[var(--surface)] transition-colors"
|
||||
title="Read aloud"
|
||||
>
|
||||
<Volume2 className="w-5 h-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
35
src/hooks/useLocalStorage.ts
Normal file
35
src/hooks/useLocalStorage.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
export function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T | ((prev: T) => T)) => void] {
|
||||
const [storedValue, setStoredValue] = useState<T>(initialValue);
|
||||
const [isHydrated, setIsHydrated] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const item = window.localStorage.getItem(key);
|
||||
if (item) {
|
||||
setStoredValue(JSON.parse(item));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error reading localStorage key "${key}":`, error);
|
||||
}
|
||||
setIsHydrated(true);
|
||||
}, [key]);
|
||||
|
||||
const setValue = (value: T | ((prev: T) => T)) => {
|
||||
try {
|
||||
const valueToStore = value instanceof Function ? value(storedValue) : value;
|
||||
setStoredValue(valueToStore);
|
||||
if (typeof window !== "undefined") {
|
||||
window.localStorage.setItem(key, JSON.stringify(valueToStore));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error setting localStorage key "${key}":`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Return initial value until hydrated to avoid hydration mismatch
|
||||
return [isHydrated ? storedValue : initialValue, setValue];
|
||||
}
|
||||
17
src/hooks/useSettings.ts
Normal file
17
src/hooks/useSettings.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { useLocalStorage } from "./useLocalStorage";
|
||||
import {
|
||||
ReaderSettings,
|
||||
TTSSettings,
|
||||
defaultReaderSettings,
|
||||
defaultTTSSettings,
|
||||
} from "@/lib/types";
|
||||
|
||||
export function useReaderSettings() {
|
||||
return useLocalStorage<ReaderSettings>("reader-settings", defaultReaderSettings);
|
||||
}
|
||||
|
||||
export function useTTSSettings() {
|
||||
return useLocalStorage<TTSSettings>("tts-settings", defaultTTSSettings);
|
||||
}
|
||||
224
src/hooks/useTTS.ts
Normal file
224
src/hooks/useTTS.ts
Normal file
@@ -0,0 +1,224 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { TTSSettings } from "@/lib/types";
|
||||
|
||||
interface UseTTSOptions {
|
||||
settings: TTSSettings;
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface UseTTSReturn {
|
||||
isPlaying: boolean;
|
||||
isPaused: boolean;
|
||||
isLoading: boolean;
|
||||
currentPosition: number;
|
||||
play: () => void;
|
||||
pause: () => void;
|
||||
resume: () => void;
|
||||
stop: () => void;
|
||||
voices: SpeechSynthesisVoice[];
|
||||
}
|
||||
|
||||
export function useTTS({ settings, text }: UseTTSOptions): UseTTSReturn {
|
||||
const [isPlaying, setIsPlaying] = useState(false);
|
||||
const [isPaused, setIsPaused] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [currentPosition, setCurrentPosition] = useState(0);
|
||||
const [voices, setVoices] = useState<SpeechSynthesisVoice[]>([]);
|
||||
|
||||
const utteranceRef = useRef<SpeechSynthesisUtterance | null>(null);
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
const textRef = useRef(text);
|
||||
textRef.current = text;
|
||||
|
||||
// Load browser voices
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined" || !window.speechSynthesis) return;
|
||||
|
||||
const loadVoices = () => {
|
||||
const availableVoices = speechSynthesis.getVoices();
|
||||
setVoices(availableVoices);
|
||||
};
|
||||
|
||||
loadVoices();
|
||||
speechSynthesis.onvoiceschanged = loadVoices;
|
||||
|
||||
return () => {
|
||||
speechSynthesis.onvoiceschanged = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (utteranceRef.current) {
|
||||
speechSynthesis.cancel();
|
||||
}
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const playBrowser = useCallback(() => {
|
||||
if (!window.speechSynthesis) {
|
||||
console.error("Speech synthesis not supported");
|
||||
return;
|
||||
}
|
||||
|
||||
speechSynthesis.cancel();
|
||||
|
||||
const utterance = new SpeechSynthesisUtterance(textRef.current);
|
||||
utterance.rate = settings.speed;
|
||||
|
||||
if (settings.voice) {
|
||||
const voice = voices.find((v) => v.voiceURI === settings.voice);
|
||||
if (voice) {
|
||||
utterance.voice = voice;
|
||||
}
|
||||
}
|
||||
|
||||
utterance.onstart = () => {
|
||||
setIsPlaying(true);
|
||||
setIsPaused(false);
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
utterance.onend = () => {
|
||||
setIsPlaying(false);
|
||||
setIsPaused(false);
|
||||
setCurrentPosition(0);
|
||||
};
|
||||
|
||||
utterance.onerror = (event) => {
|
||||
console.error("TTS error:", event);
|
||||
setIsPlaying(false);
|
||||
setIsPaused(false);
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
utterance.onboundary = (event) => {
|
||||
setCurrentPosition(event.charIndex);
|
||||
};
|
||||
|
||||
utteranceRef.current = utterance;
|
||||
setIsLoading(true);
|
||||
speechSynthesis.speak(utterance);
|
||||
}, [settings.speed, settings.voice, voices]);
|
||||
|
||||
const playKokoro = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${settings.kokoroUrl}/v1/audio/speech`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "kokoro",
|
||||
input: textRef.current,
|
||||
voice: "af_bella",
|
||||
response_format: "mp3",
|
||||
speed: settings.speed,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Kokoro API error: ${response.status}`);
|
||||
}
|
||||
|
||||
const blob = await response.blob();
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
}
|
||||
|
||||
const audio = new Audio(url);
|
||||
audio.playbackRate = 1; // Speed is already applied by Kokoro
|
||||
|
||||
audio.onplay = () => {
|
||||
setIsPlaying(true);
|
||||
setIsPaused(false);
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
audio.onended = () => {
|
||||
setIsPlaying(false);
|
||||
setIsPaused(false);
|
||||
setCurrentPosition(0);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
audio.onerror = () => {
|
||||
console.error("Audio playback error");
|
||||
setIsPlaying(false);
|
||||
setIsLoading(false);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
audioRef.current = audio;
|
||||
await audio.play();
|
||||
} catch (error) {
|
||||
console.error("Kokoro TTS error:", error);
|
||||
setIsLoading(false);
|
||||
alert("Failed to connect to Kokoro. Make sure it's running at " + settings.kokoroUrl);
|
||||
}
|
||||
}, [settings.kokoroUrl, settings.speed]);
|
||||
|
||||
const play = useCallback(() => {
|
||||
if (settings.engine === "browser") {
|
||||
playBrowser();
|
||||
} else {
|
||||
playKokoro();
|
||||
}
|
||||
}, [settings.engine, playBrowser, playKokoro]);
|
||||
|
||||
const pause = useCallback(() => {
|
||||
if (settings.engine === "browser") {
|
||||
speechSynthesis.pause();
|
||||
setIsPaused(true);
|
||||
} else if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
setIsPaused(true);
|
||||
}
|
||||
}, [settings.engine]);
|
||||
|
||||
const resume = useCallback(() => {
|
||||
if (settings.engine === "browser") {
|
||||
speechSynthesis.resume();
|
||||
setIsPaused(false);
|
||||
} else if (audioRef.current) {
|
||||
audioRef.current.play();
|
||||
setIsPaused(false);
|
||||
}
|
||||
}, [settings.engine]);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
if (settings.engine === "browser") {
|
||||
speechSynthesis.cancel();
|
||||
}
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current.currentTime = 0;
|
||||
}
|
||||
setIsPlaying(false);
|
||||
setIsPaused(false);
|
||||
setCurrentPosition(0);
|
||||
}, [settings.engine]);
|
||||
|
||||
return {
|
||||
isPlaying,
|
||||
isPaused,
|
||||
isLoading,
|
||||
currentPosition,
|
||||
play,
|
||||
pause,
|
||||
resume,
|
||||
stop,
|
||||
voices,
|
||||
};
|
||||
}
|
||||
12
src/lib/db/index.ts
Normal file
12
src/lib/db/index.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import Database from "better-sqlite3";
|
||||
import { drizzle } from "drizzle-orm/better-sqlite3";
|
||||
import * as schema from "./schema";
|
||||
import path from "path";
|
||||
|
||||
const dbPath = process.env.DATABASE_PATH || path.join(process.cwd(), "data", "readlater.db");
|
||||
|
||||
const sqlite = new Database(dbPath);
|
||||
sqlite.pragma("journal_mode = WAL");
|
||||
|
||||
export const db = drizzle(sqlite, { schema });
|
||||
export { schema };
|
||||
22
src/lib/db/migrate.ts
Normal file
22
src/lib/db/migrate.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import Database from "better-sqlite3";
|
||||
import { drizzle } from "drizzle-orm/better-sqlite3";
|
||||
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const dbPath = process.env.DATABASE_PATH || path.join(process.cwd(), "data", "readlater.db");
|
||||
|
||||
// Ensure data directory exists
|
||||
const dataDir = path.dirname(dbPath);
|
||||
if (!fs.existsSync(dataDir)) {
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
}
|
||||
|
||||
const sqlite = new Database(dbPath);
|
||||
const db = drizzle(sqlite);
|
||||
|
||||
console.log("Running migrations...");
|
||||
migrate(db, { migrationsFolder: "./drizzle" });
|
||||
console.log("Migrations complete!");
|
||||
|
||||
sqlite.close();
|
||||
24
src/lib/db/schema.ts
Normal file
24
src/lib/db/schema.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
||||
|
||||
export const articles = sqliteTable("articles", {
|
||||
id: text("id").primaryKey(),
|
||||
url: text("url").notNull(),
|
||||
title: text("title").notNull(),
|
||||
author: text("author"),
|
||||
siteName: text("site_name"),
|
||||
excerpt: text("excerpt"),
|
||||
content: text("content").notNull(), // HTML content
|
||||
textContent: text("text_content").notNull(), // Plain text for TTS
|
||||
leadImage: text("lead_image"),
|
||||
wordCount: integer("word_count").default(0),
|
||||
readingProgress: integer("reading_progress").default(0), // 0-100
|
||||
isFavorite: integer("is_favorite", { mode: "boolean" }).default(false),
|
||||
isArchived: integer("is_archived", { mode: "boolean" }).default(false),
|
||||
tags: text("tags").default("[]"), // JSON array of tags
|
||||
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
updatedAt: integer("updated_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
|
||||
readAt: integer("read_at", { mode: "timestamp" }),
|
||||
});
|
||||
|
||||
export type Article = typeof articles.$inferSelect;
|
||||
export type NewArticle = typeof articles.$inferInsert;
|
||||
49
src/lib/types.ts
Normal file
49
src/lib/types.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
export interface Article {
|
||||
id: string;
|
||||
url: string;
|
||||
title: string;
|
||||
author: string | null;
|
||||
siteName: string | null;
|
||||
excerpt: string | null;
|
||||
content: string;
|
||||
textContent: string;
|
||||
leadImage: string | null;
|
||||
wordCount: number;
|
||||
readingProgress: number;
|
||||
isFavorite: boolean;
|
||||
isArchived: boolean;
|
||||
tags: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
readAt: string | null;
|
||||
}
|
||||
|
||||
export interface ReaderSettings {
|
||||
fontSize: number; // 14-32
|
||||
fontFamily: "system" | "serif" | "sans" | "mono";
|
||||
lineHeight: number; // 1.4-2.2
|
||||
maxWidth: number; // 500-900
|
||||
theme: "dark" | "light" | "sepia";
|
||||
}
|
||||
|
||||
export interface TTSSettings {
|
||||
engine: "browser" | "kokoro";
|
||||
speed: number; // 0.5-3.0
|
||||
voice: string;
|
||||
kokoroUrl: string;
|
||||
}
|
||||
|
||||
export const defaultReaderSettings: ReaderSettings = {
|
||||
fontSize: 18,
|
||||
fontFamily: "serif",
|
||||
lineHeight: 1.8,
|
||||
maxWidth: 700,
|
||||
theme: "dark",
|
||||
};
|
||||
|
||||
export const defaultTTSSettings: TTSSettings = {
|
||||
engine: "browser",
|
||||
speed: 1.0,
|
||||
voice: "",
|
||||
kokoroUrl: "http://localhost:8880",
|
||||
};
|
||||
18
src/lib/utils/date.ts
Normal file
18
src/lib/utils/date.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export function formatDistanceToNow(date: string | Date): string {
|
||||
const d = new Date(date);
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - d.getTime();
|
||||
const diffSecs = Math.floor(diffMs / 1000);
|
||||
const diffMins = Math.floor(diffSecs / 60);
|
||||
const diffHours = Math.floor(diffMins / 60);
|
||||
const diffDays = Math.floor(diffHours / 24);
|
||||
const diffWeeks = Math.floor(diffDays / 7);
|
||||
const diffMonths = Math.floor(diffDays / 30);
|
||||
|
||||
if (diffSecs < 60) return "just now";
|
||||
if (diffMins < 60) return `${diffMins}m ago`;
|
||||
if (diffHours < 24) return `${diffHours}h ago`;
|
||||
if (diffDays < 7) return `${diffDays}d ago`;
|
||||
if (diffWeeks < 4) return `${diffWeeks}w ago`;
|
||||
return `${diffMonths}mo ago`;
|
||||
}
|
||||
62
src/lib/utils/extract.ts
Normal file
62
src/lib/utils/extract.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { Readability } from "@mozilla/readability";
|
||||
import { JSDOM } from "jsdom";
|
||||
|
||||
export interface ExtractedArticle {
|
||||
title: string;
|
||||
author: string | null;
|
||||
siteName: string | null;
|
||||
excerpt: string | null;
|
||||
content: string;
|
||||
textContent: string;
|
||||
leadImage: string | null;
|
||||
wordCount: number;
|
||||
}
|
||||
|
||||
export async function extractArticle(url: string): Promise<ExtractedArticle> {
|
||||
// Fetch the page
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
"User-Agent": "Mozilla/5.0 (compatible; ReadLater/1.0)",
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
const dom = new JSDOM(html, { url });
|
||||
const document = dom.window.document;
|
||||
|
||||
// Extract using Readability
|
||||
const reader = new Readability(document);
|
||||
const article = reader.parse();
|
||||
|
||||
if (!article) {
|
||||
throw new Error("Could not extract article content");
|
||||
}
|
||||
|
||||
// Try to find lead image
|
||||
let leadImage: string | null = null;
|
||||
const ogImage = document.querySelector('meta[property="og:image"]');
|
||||
if (ogImage) {
|
||||
leadImage = ogImage.getAttribute("content");
|
||||
}
|
||||
|
||||
const textContent = article.textContent || "";
|
||||
const content = article.content || "";
|
||||
|
||||
// Calculate word count
|
||||
const wordCount = textContent.split(/\s+/).filter(Boolean).length;
|
||||
|
||||
return {
|
||||
title: article.title || "Untitled",
|
||||
author: article.byline || null,
|
||||
siteName: article.siteName || new URL(url).hostname,
|
||||
excerpt: article.excerpt || null,
|
||||
content,
|
||||
textContent,
|
||||
leadImage,
|
||||
wordCount,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user