mirror of
https://github.com/Tony0410/readlater.git
synced 2026-05-24 22:01:41 +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:
10
.dockerignore
Normal file
10
.dockerignore
Normal file
@@ -0,0 +1,10 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
.gitignore
|
||||
*.md
|
||||
data
|
||||
.env*
|
||||
Dockerfile
|
||||
docker-compose.yml
|
||||
.dockerignore
|
||||
41
.gitignore
vendored
Normal file
41
.gitignore
vendored
Normal file
@@ -0,0 +1,41 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/versions
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# env files (can opt-in for committing if needed)
|
||||
.env*
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
49
Dockerfile
Normal file
49
Dockerfile
Normal file
@@ -0,0 +1,49 @@
|
||||
# Build stage
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
# Copy source files
|
||||
COPY . .
|
||||
|
||||
# Generate database migrations
|
||||
RUN npx drizzle-kit generate
|
||||
|
||||
# Build the application
|
||||
RUN npm run build
|
||||
|
||||
# Production stage
|
||||
FROM node:20-alpine AS runner
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV DATABASE_PATH=/app/data/readlater.db
|
||||
|
||||
# Create non-root user
|
||||
RUN addgroup --system --gid 1001 nodejs
|
||||
RUN adduser --system --uid 1001 nextjs
|
||||
|
||||
# Copy built application
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/.next/standalone ./
|
||||
COPY --from=builder /app/.next/static ./.next/static
|
||||
COPY --from=builder /app/drizzle ./drizzle
|
||||
COPY --from=builder /app/node_modules/drizzle-orm ./node_modules/drizzle-orm
|
||||
COPY --from=builder /app/node_modules/better-sqlite3 ./node_modules/better-sqlite3
|
||||
|
||||
# Create data directory
|
||||
RUN mkdir -p /app/data && chown -R nextjs:nodejs /app/data
|
||||
|
||||
USER nextjs
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
ENV PORT=3000
|
||||
ENV HOSTNAME="0.0.0.0"
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
142
README.md
Normal file
142
README.md
Normal file
@@ -0,0 +1,142 @@
|
||||
# ReadLater
|
||||
|
||||
A self-hosted read-it-later app with text-to-speech support. Save articles, read them later with a clean dark reader interface, and listen to them with high-quality TTS.
|
||||
|
||||
## Features
|
||||
|
||||
- **Save Articles**: Paste URLs or use the bookmarklet to save articles
|
||||
- **Clean Reader**: Distraction-free reading with dark mode (black background, white text)
|
||||
- **Customizable**: Adjust font size, font family, line height, and content width
|
||||
- **Favorites & Archive**: Organize your reading list
|
||||
- **Text-to-Speech**:
|
||||
- Browser TTS (built-in, works offline)
|
||||
- Kokoro TTS (high-quality, self-hosted)
|
||||
- Speed control up to 3x
|
||||
- **Bookmarklet**: One-click saving from any browser
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Using Docker (Recommended)
|
||||
|
||||
```bash
|
||||
# Clone or download the project
|
||||
cd /root/projects/readlater
|
||||
|
||||
# Start with Docker Compose
|
||||
docker compose up -d
|
||||
|
||||
# Access at http://localhost:3000
|
||||
```
|
||||
|
||||
### Manual Installation
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
npm install
|
||||
|
||||
# Run database migrations
|
||||
npm run db:migrate
|
||||
|
||||
# Start development server
|
||||
npm run dev
|
||||
|
||||
# Or build for production
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Adding Articles
|
||||
|
||||
1. **Paste URL**: Use the input field at the top of the app
|
||||
2. **Bookmarklet**: Go to `/bookmarklet` and drag the button to your bookmarks bar
|
||||
|
||||
### Reading
|
||||
|
||||
- Click any article to open the reader
|
||||
- Use the settings panel (gear icon) to customize:
|
||||
- **Theme**: Dark (default), Light, or Sepia
|
||||
- **Font Size**: 14-32px
|
||||
- **Font Family**: Serif, Sans, Mono, or System
|
||||
- **Line Height**: Tight to Loose
|
||||
- **Content Width**: Narrow to Wide
|
||||
|
||||
### Text-to-Speech
|
||||
|
||||
- Click the speaker icon to start reading
|
||||
- Control playback with pause/resume/stop buttons
|
||||
- Adjust speed in settings (0.5x to 3x)
|
||||
|
||||
#### Browser TTS
|
||||
Works out of the box using your browser's built-in speech synthesis.
|
||||
|
||||
#### Kokoro TTS (Optional)
|
||||
For higher quality TTS, uncomment the `kokoro` service in `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
kokoro:
|
||||
image: ghcr.io/remsky/kokoro-fastapi:latest
|
||||
container_name: kokoro-tts
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "8880:8880"
|
||||
```
|
||||
|
||||
Then select "Kokoro" in the TTS settings.
|
||||
|
||||
## Configuration
|
||||
|
||||
### Environment Variables
|
||||
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `DATABASE_PATH` | `./data/readlater.db` | Path to SQLite database |
|
||||
| `PORT` | `3000` | Server port |
|
||||
|
||||
### Data Persistence
|
||||
|
||||
The SQLite database is stored in `./data/readlater.db`. Mount this directory as a volume when using Docker.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Framework**: Next.js 16 with App Router
|
||||
- **Language**: TypeScript
|
||||
- **Database**: SQLite with Drizzle ORM
|
||||
- **Styling**: Tailwind CSS
|
||||
- **Article Extraction**: Mozilla Readability
|
||||
- **TTS**: Web Speech API + Kokoro-FastAPI
|
||||
|
||||
## API Endpoints
|
||||
|
||||
| Endpoint | Method | Description |
|
||||
|----------|--------|-------------|
|
||||
| `/api/articles` | GET | List articles (query: `filter=all\|favorites\|archived`) |
|
||||
| `/api/articles` | POST | Save new article (body: `{url}`) |
|
||||
| `/api/articles/[id]` | GET | Get single article |
|
||||
| `/api/articles/[id]` | PATCH | Update article |
|
||||
| `/api/articles/[id]` | DELETE | Delete article |
|
||||
| `/api/save` | GET | Bookmarklet endpoint (query: `url`) |
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
# Start dev server
|
||||
npm run dev
|
||||
|
||||
# Generate new migration after schema changes
|
||||
npm run db:generate
|
||||
|
||||
# Run migrations
|
||||
npm run db:migrate
|
||||
|
||||
# Open Drizzle Studio (database GUI)
|
||||
npm run db:studio
|
||||
|
||||
# Lint
|
||||
npm run lint
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
BIN
data/readlater.db
Normal file
BIN
data/readlater.db
Normal file
Binary file not shown.
BIN
data/readlater.db-shm
Normal file
BIN
data/readlater.db-shm
Normal file
Binary file not shown.
BIN
data/readlater.db-wal
Normal file
BIN
data/readlater.db-wal
Normal file
Binary file not shown.
30
docker-compose.yml
Normal file
30
docker-compose.yml
Normal file
@@ -0,0 +1,30 @@
|
||||
services:
|
||||
readlater:
|
||||
build: .
|
||||
container_name: readlater
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "6123:3000"
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
environment:
|
||||
- DATABASE_PATH=/app/data/readlater.db
|
||||
|
||||
# Optional: Kokoro TTS for high-quality text-to-speech
|
||||
# Uncomment if you want to use Kokoro instead of browser TTS
|
||||
# kokoro:
|
||||
# image: ghcr.io/remsky/kokoro-fastapi:latest
|
||||
# container_name: kokoro-tts
|
||||
# restart: unless-stopped
|
||||
# ports:
|
||||
# - "8880:8880"
|
||||
# environment:
|
||||
# - PYTHONUNBUFFERED=1
|
||||
# # GPU support (optional, for faster inference)
|
||||
# # deploy:
|
||||
# # resources:
|
||||
# # reservations:
|
||||
# # devices:
|
||||
# # - driver: nvidia
|
||||
# # count: 1
|
||||
# # capabilities: [gpu]
|
||||
10
drizzle.config.ts
Normal file
10
drizzle.config.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
schema: "./src/lib/db/schema.ts",
|
||||
out: "./drizzle",
|
||||
dialect: "sqlite",
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_PATH || "./data/readlater.db",
|
||||
},
|
||||
});
|
||||
19
drizzle/0000_black_lucky_pierre.sql
Normal file
19
drizzle/0000_black_lucky_pierre.sql
Normal file
@@ -0,0 +1,19 @@
|
||||
CREATE TABLE `articles` (
|
||||
`id` text PRIMARY KEY NOT NULL,
|
||||
`url` text NOT NULL,
|
||||
`title` text NOT NULL,
|
||||
`author` text,
|
||||
`site_name` text,
|
||||
`excerpt` text,
|
||||
`content` text NOT NULL,
|
||||
`text_content` text NOT NULL,
|
||||
`lead_image` text,
|
||||
`word_count` integer DEFAULT 0,
|
||||
`reading_progress` integer DEFAULT 0,
|
||||
`is_favorite` integer DEFAULT false,
|
||||
`is_archived` integer DEFAULT false,
|
||||
`tags` text DEFAULT '[]',
|
||||
`created_at` integer,
|
||||
`updated_at` integer,
|
||||
`read_at` integer
|
||||
);
|
||||
152
drizzle/meta/0000_snapshot.json
Normal file
152
drizzle/meta/0000_snapshot.json
Normal file
@@ -0,0 +1,152 @@
|
||||
{
|
||||
"version": "6",
|
||||
"dialect": "sqlite",
|
||||
"id": "49bb8830-0860-4592-97d9-83c44fd350fc",
|
||||
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||
"tables": {
|
||||
"articles": {
|
||||
"name": "articles",
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"primaryKey": true,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"url": {
|
||||
"name": "url",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"title": {
|
||||
"name": "title",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"author": {
|
||||
"name": "author",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"site_name": {
|
||||
"name": "site_name",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"excerpt": {
|
||||
"name": "excerpt",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"content": {
|
||||
"name": "content",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"text_content": {
|
||||
"name": "text_content",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": true,
|
||||
"autoincrement": false
|
||||
},
|
||||
"lead_image": {
|
||||
"name": "lead_image",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"word_count": {
|
||||
"name": "word_count",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"reading_progress": {
|
||||
"name": "reading_progress",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": 0
|
||||
},
|
||||
"is_favorite": {
|
||||
"name": "is_favorite",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": false
|
||||
},
|
||||
"is_archived": {
|
||||
"name": "is_archived",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": false
|
||||
},
|
||||
"tags": {
|
||||
"name": "tags",
|
||||
"type": "text",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false,
|
||||
"default": "'[]'"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
},
|
||||
"read_at": {
|
||||
"name": "read_at",
|
||||
"type": "integer",
|
||||
"primaryKey": false,
|
||||
"notNull": false,
|
||||
"autoincrement": false
|
||||
}
|
||||
},
|
||||
"indexes": {},
|
||||
"foreignKeys": {},
|
||||
"compositePrimaryKeys": {},
|
||||
"uniqueConstraints": {},
|
||||
"checkConstraints": {}
|
||||
}
|
||||
},
|
||||
"views": {},
|
||||
"enums": {},
|
||||
"_meta": {
|
||||
"schemas": {},
|
||||
"tables": {},
|
||||
"columns": {}
|
||||
},
|
||||
"internal": {
|
||||
"indexes": {}
|
||||
}
|
||||
}
|
||||
13
drizzle/meta/_journal.json
Normal file
13
drizzle/meta/_journal.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "sqlite",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "6",
|
||||
"when": 1768632959441,
|
||||
"tag": "0000_black_lucky_pierre",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
18
eslint.config.mjs
Normal file
18
eslint.config.mjs
Normal file
@@ -0,0 +1,18 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
const eslintConfig = defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
// Override default ignores of eslint-config-next.
|
||||
globalIgnores([
|
||||
// Default ignores of eslint-config-next:
|
||||
".next/**",
|
||||
"out/**",
|
||||
"build/**",
|
||||
"next-env.d.ts",
|
||||
]),
|
||||
]);
|
||||
|
||||
export default eslintConfig;
|
||||
16
next.config.ts
Normal file
16
next.config.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
// Allow images from any domain (for article lead images)
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: "https",
|
||||
hostname: "**",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
8702
package-lock.json
generated
Normal file
8702
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
41
package.json
Normal file
41
package.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "readlater",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"start": "next start",
|
||||
"lint": "eslint",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "tsx src/lib/db/migrate.ts",
|
||||
"db:studio": "drizzle-kit studio",
|
||||
"postinstall": "npm run db:migrate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"better-sqlite3": "^12.6.2",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
"jsdom": "^27.4.0",
|
||||
"lucide-react": "^0.562.0",
|
||||
"next": "16.1.3",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"uuid": "^13.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
"@types/better-sqlite3": "^7.6.13",
|
||||
"@types/jsdom": "^27.0.0",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19",
|
||||
"@types/react-dom": "^19",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"drizzle-kit": "^0.31.8",
|
||||
"eslint": "^9",
|
||||
"eslint-config-next": "16.1.3",
|
||||
"tailwindcss": "^4",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5"
|
||||
}
|
||||
}
|
||||
7
postcss.config.mjs
Normal file
7
postcss.config.mjs
Normal file
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
1
public/file.svg
Normal file
1
public/file.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||
|
After Width: | Height: | Size: 391 B |
1
public/globe.svg
Normal file
1
public/globe.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 1.0 KiB |
1
public/next.svg
Normal file
1
public/next.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
1
public/vercel.svg
Normal file
1
public/vercel.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||
|
After Width: | Height: | Size: 128 B |
1
public/window.svg
Normal file
1
public/window.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
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,
|
||||
};
|
||||
}
|
||||
34
tsconfig.json
Normal file
34
tsconfig.json
Normal file
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2017",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts",
|
||||
"**/*.mts"
|
||||
],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user