Vite/React + shadcn/ui frontend with Superhuman-style keyboard nav (j/k/o/v/e/s/u, feed switching, localStorage caching for instant loads) backed by an Express API that polls the HN Firebase API into Postgres and serves cached feeds/comments. Instrumented with OpenTelemetry (traces/metrics/logs via OTLP/HTTP).
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
PORT=3012
|
||||
POSTGRES_HOST=127.0.0.1
|
||||
POSTGRES_PORT=5433
|
||||
POSTGRES_DB=hnreader
|
||||
POSTGRES_USER=hnreader
|
||||
POSTGRES_PASSWORD=changeme
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
|
||||
@@ -0,0 +1,31 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ['**']
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Typecheck
|
||||
run: npx tsc -b
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
.env
|
||||
.env.docker
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
# HN Reader
|
||||
|
||||
A lightweight, keyboard-driven Hacker News reader. Navigate like
|
||||
Superhuman/Linear: `j`/`k` to move, `o`/`Enter` to read, `e` to
|
||||
archive, `s` to star, numbers to switch feeds. Feed data is cached in
|
||||
`localStorage` for instant loads, then revalidated in the background.
|
||||
|
||||
Press `?` in the app for the full shortcut list.
|
||||
|
||||
## Stack
|
||||
|
||||
- **Frontend**: Vite + React + TypeScript, [shadcn/ui](https://ui.shadcn.com) (Radix primitives, Tailwind v4, Nova preset)
|
||||
- **Backend**: Express (`server/`), polls the [HN Firebase API](https://github.com/HackerNews/API) every 5 minutes and caches stories in Postgres
|
||||
- **Database**: Postgres 16 (Docker), schema in `scripts/init.sql`
|
||||
- **Observability**: OpenTelemetry traces/metrics/logs shipped via OTLP/HTTP
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
src/ React SPA (feeds, keyboard nav, comments dialog)
|
||||
server/ Express API + HN sync job + OTel bootstrap
|
||||
scripts/ DB schema, backup script
|
||||
docker-compose.yml Postgres container for this app
|
||||
.gitea/workflows/ CI: lint, typecheck, build
|
||||
```
|
||||
|
||||
The API caches HN's top/new/best/ask/show/job feeds (100 items each)
|
||||
in Postgres so the frontend never talks to Hacker News directly.
|
||||
Per-story read/starred/archived state lives in `story_state` and is
|
||||
returned inline with each feed response.
|
||||
|
||||
## Local development
|
||||
|
||||
```bash
|
||||
cp .env.example .env # fill in POSTGRES_PASSWORD
|
||||
docker compose up -d # start Postgres
|
||||
npm install
|
||||
npm run dev:server # API on :3012 (loaded from .env)
|
||||
npm run dev # Vite dev server on :3012, proxies /api
|
||||
```
|
||||
|
||||
## Production
|
||||
|
||||
Runs as the `app-54d6877c` systemd unit: builds are not automated on
|
||||
deploy, so after pulling changes run `npm run build` then restart the
|
||||
service (`sudo systemctl restart app-54d6877c`). The compiled SPA is
|
||||
served as static files by the same Express process that serves `/api`,
|
||||
on port **3012**.
|
||||
|
||||
Nightly Postgres backups run via the `app-54d6877c-backup.timer`
|
||||
systemd timer (`scripts/backup.sh`), keeping 7 days of `pg_dump`
|
||||
snapshots in `~/backups`.
|
||||
|
||||
## Design system
|
||||
|
||||
Built with `shadcn/ui` (`components.json`, Radix base, Nova preset).
|
||||
Components live under `src/components/ui` and are added with
|
||||
`npx shadcn@latest add <component>` — nothing here is hand-rolled, so
|
||||
swapping in a custom registry later (e.g. a `privatecloud` registry)
|
||||
is a matter of updating `components.json`'s `registries` field and
|
||||
re-running `add` against it.
|
||||
|
||||
## Observability
|
||||
|
||||
The API sends traces, metrics, and logs to an OTLP/HTTP collector at
|
||||
`OTEL_EXPORTER_OTLP_ENDPOINT` (defaults to `http://localhost:4318`),
|
||||
instrumenting HTTP, Express, and Postgres calls automatically via
|
||||
`@opentelemetry/auto-instrumentations-node`. View it in Grafana at
|
||||
`localhost:3400`.
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "radix-nova",
|
||||
"rsc": false,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/index.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"iconLibrary": "lucide",
|
||||
"rtl": false,
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"menuColor": "default",
|
||||
"menuAccent": "subtle",
|
||||
"registries": {}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: hn-reader-postgres
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: hnreader
|
||||
POSTGRES_USER: hnreader
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
ports:
|
||||
- "127.0.0.1:5433:5432"
|
||||
volumes:
|
||||
- hn-reader-pgdata:/var/lib/postgresql/data
|
||||
- ./scripts/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U hnreader -d hnreader"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
volumes:
|
||||
hn-reader-pgdata:
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>HN Reader</title>
|
||||
<meta name="description" content="A fast, keyboard-driven Hacker News reader." />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+10058
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"name": "hn-reader-54d6877c",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:server": "node server/index.js",
|
||||
"build": "tsc -b && vite build",
|
||||
"start": "NODE_ENV=production node server/index.js",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/geist": "^5.3.0",
|
||||
"@opentelemetry/api": "^1.9.1",
|
||||
"@opentelemetry/api-logs": "^0.221.0",
|
||||
"@opentelemetry/auto-instrumentations-node": "^0.79.0",
|
||||
"@opentelemetry/exporter-logs-otlp-http": "^0.221.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
|
||||
"@opentelemetry/exporter-trace-otlp-http": "^0.221.0",
|
||||
"@opentelemetry/resources": "^2.10.0",
|
||||
"@opentelemetry/sdk-logs": "^0.221.0",
|
||||
"@opentelemetry/sdk-metrics": "^2.10.0",
|
||||
"@opentelemetry/sdk-node": "^0.221.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.43.0",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cors": "^2.8.6",
|
||||
"dotenv": "^17.4.2",
|
||||
"express": "^5.2.1",
|
||||
"lucide-react": "^1.26.0",
|
||||
"next-themes": "^0.4.6",
|
||||
"pg": "^8.22.0",
|
||||
"radix-ui": "^1.6.7",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"shadcn": "^4.14.1",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"tw-animate-css": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.3",
|
||||
"oxlint": "^1.71.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.1.1"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Nightly Postgres backup for the HN Reader app. Invoked by app-54d6877c-backup.timer.
|
||||
set -euo pipefail
|
||||
|
||||
BACKUP_DIR="/home/exedev/backups"
|
||||
RETENTION_DAYS=7
|
||||
TIMESTAMP="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
FILE="$BACKUP_DIR/hn-reader-$TIMESTAMP.sql.gz"
|
||||
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
|
||||
docker exec hn-reader-postgres pg_dump -U hnreader -d hnreader | gzip > "$FILE"
|
||||
|
||||
find "$BACKUP_DIR" -name 'hn-reader-*.sql.gz' -mtime +"$RETENTION_DAYS" -delete
|
||||
|
||||
echo "Backed up hn-reader database to $FILE"
|
||||
@@ -0,0 +1,38 @@
|
||||
-- Schema for hn-reader: cached Hacker News stories + local read state.
|
||||
-- Single-user app: no user table, state is keyed directly by story id.
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stories (
|
||||
id BIGINT PRIMARY KEY, -- Hacker News item id
|
||||
type TEXT NOT NULL DEFAULT 'story',
|
||||
title TEXT NOT NULL,
|
||||
url TEXT,
|
||||
domain TEXT,
|
||||
by_user TEXT,
|
||||
score INTEGER NOT NULL DEFAULT 0,
|
||||
descendants INTEGER NOT NULL DEFAULT 0, -- comment count
|
||||
story_text TEXT, -- self-text for Ask HN / Show HN
|
||||
hn_created_at TIMESTAMPTZ NOT NULL,
|
||||
fetched_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- Which feed(s) a story currently ranks in, and at what rank, so the
|
||||
-- frontend can render top/new/best/ask/show/job lists from one table.
|
||||
CREATE TABLE IF NOT EXISTS feed_items (
|
||||
feed TEXT NOT NULL, -- top | new | best | ask | show | job
|
||||
rank INTEGER NOT NULL,
|
||||
story_id BIGINT NOT NULL REFERENCES stories(id) ON DELETE CASCADE,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (feed, rank)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS feed_items_story_idx ON feed_items(story_id);
|
||||
|
||||
-- Per-story local state: read/starred/archived, superhuman-style.
|
||||
CREATE TABLE IF NOT EXISTS story_state (
|
||||
story_id BIGINT PRIMARY KEY REFERENCES stories(id) ON DELETE CASCADE,
|
||||
read BOOLEAN NOT NULL DEFAULT false,
|
||||
starred BOOLEAN NOT NULL DEFAULT false,
|
||||
archived BOOLEAN NOT NULL DEFAULT false,
|
||||
read_at TIMESTAMPTZ,
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,11 @@
|
||||
const { Pool } = require('pg')
|
||||
|
||||
const pool = new Pool({
|
||||
host: process.env.POSTGRES_HOST || '127.0.0.1',
|
||||
port: Number(process.env.POSTGRES_PORT || 5433),
|
||||
database: process.env.POSTGRES_DB || 'hnreader',
|
||||
user: process.env.POSTGRES_USER || 'hnreader',
|
||||
password: process.env.POSTGRES_PASSWORD,
|
||||
})
|
||||
|
||||
module.exports = { pool }
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
const { pool } = require('./db')
|
||||
const { log } = require('./otel')
|
||||
|
||||
const HN_BASE = 'https://hacker-news.firebaseio.com/v0'
|
||||
|
||||
const FEEDS = {
|
||||
top: 'topstories',
|
||||
new: 'newstories',
|
||||
best: 'beststories',
|
||||
ask: 'askstories',
|
||||
show: 'showstories',
|
||||
job: 'jobstories',
|
||||
}
|
||||
|
||||
const ITEMS_PER_FEED = 100
|
||||
const FETCH_CONCURRENCY = 20
|
||||
|
||||
async function fetchJson(url) {
|
||||
const res = await fetch(url)
|
||||
if (!res.ok) throw new Error(`HN API ${res.status} for ${url}`)
|
||||
return res.json()
|
||||
}
|
||||
|
||||
function domainOf(url) {
|
||||
if (!url) return null
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, '')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function mapWithConcurrency(items, limit, fn) {
|
||||
const results = new Array(items.length)
|
||||
let next = 0
|
||||
async function worker() {
|
||||
while (next < items.length) {
|
||||
const i = next++
|
||||
results[i] = await fn(items[i], i)
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
|
||||
return results
|
||||
}
|
||||
|
||||
async function fetchItem(id) {
|
||||
return fetchJson(`${HN_BASE}/item/${id}.json`)
|
||||
}
|
||||
|
||||
async function syncFeed(feedKey) {
|
||||
const endpoint = FEEDS[feedKey]
|
||||
const ids = (await fetchJson(`${HN_BASE}/${endpoint}.json`)).slice(0, ITEMS_PER_FEED)
|
||||
|
||||
const items = await mapWithConcurrency(ids, FETCH_CONCURRENCY, async (id) => {
|
||||
try {
|
||||
return await fetchItem(id)
|
||||
} catch (err) {
|
||||
log('ERROR', 'failed to fetch HN item', { id, error: String(err) })
|
||||
return null
|
||||
}
|
||||
})
|
||||
|
||||
const client = await pool.connect()
|
||||
try {
|
||||
await client.query('BEGIN')
|
||||
let rank = 0
|
||||
for (const item of items) {
|
||||
if (!item || item.deleted || item.dead) continue
|
||||
await client.query(
|
||||
`INSERT INTO stories (id, type, title, url, domain, by_user, score, descendants, story_text, hn_created_at, fetched_at)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9, to_timestamp($10), now())
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
title = EXCLUDED.title,
|
||||
url = EXCLUDED.url,
|
||||
domain = EXCLUDED.domain,
|
||||
score = EXCLUDED.score,
|
||||
descendants = EXCLUDED.descendants,
|
||||
story_text = EXCLUDED.story_text,
|
||||
fetched_at = now()`,
|
||||
[
|
||||
item.id,
|
||||
item.type || 'story',
|
||||
item.title || '(untitled)',
|
||||
item.url || null,
|
||||
domainOf(item.url),
|
||||
item.by || null,
|
||||
item.score || 0,
|
||||
item.descendants || 0,
|
||||
item.text || null,
|
||||
item.time || Math.floor(Date.now() / 1000),
|
||||
]
|
||||
)
|
||||
await client.query(
|
||||
`INSERT INTO story_state (story_id) VALUES ($1) ON CONFLICT (story_id) DO NOTHING`,
|
||||
[item.id]
|
||||
)
|
||||
await client.query(
|
||||
`INSERT INTO feed_items (feed, rank, story_id, updated_at) VALUES ($1,$2,$3, now())
|
||||
ON CONFLICT (feed, rank) DO UPDATE SET story_id = EXCLUDED.story_id, updated_at = now()`,
|
||||
[feedKey, rank, item.id]
|
||||
)
|
||||
rank++
|
||||
}
|
||||
// Drop stale ranks past what we just wrote (feed shrank).
|
||||
await client.query('DELETE FROM feed_items WHERE feed = $1 AND rank >= $2', [feedKey, rank])
|
||||
await client.query('COMMIT')
|
||||
log('INFO', 'synced feed', { feed: feedKey, count: rank })
|
||||
} catch (err) {
|
||||
await client.query('ROLLBACK')
|
||||
throw err
|
||||
} finally {
|
||||
client.release()
|
||||
}
|
||||
}
|
||||
|
||||
async function syncAll() {
|
||||
for (const feedKey of Object.keys(FEEDS)) {
|
||||
try {
|
||||
await syncFeed(feedKey)
|
||||
} catch (err) {
|
||||
log('ERROR', 'feed sync failed', { feed: feedKey, error: String(err) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_COMMENT_NODES = 300
|
||||
|
||||
async function fetchCommentsTree(storyId, maxDepth = 6) {
|
||||
let count = 0
|
||||
|
||||
async function walk(id, depth) {
|
||||
if (count >= MAX_COMMENT_NODES) return null
|
||||
const item = await fetchItem(id)
|
||||
count++
|
||||
if (!item || item.deleted || item.dead) return null
|
||||
|
||||
let kids = []
|
||||
if (item.kids && depth < maxDepth && count < MAX_COMMENT_NODES) {
|
||||
const childItems = await mapWithConcurrency(
|
||||
item.kids,
|
||||
FETCH_CONCURRENCY,
|
||||
(kidId) => walk(kidId, depth + 1)
|
||||
)
|
||||
kids = childItems.filter(Boolean)
|
||||
}
|
||||
|
||||
return {
|
||||
id: item.id,
|
||||
by: item.by || null,
|
||||
text: item.text || null,
|
||||
time: item.time || null,
|
||||
kids,
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all((await fetchItem(storyId)).kids?.slice(0, 40).map((id) => walk(id, 1)) || [])
|
||||
.then((list) => list.filter(Boolean))
|
||||
}
|
||||
|
||||
module.exports = { FEEDS, syncAll, syncFeed, fetchItem, fetchCommentsTree }
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
require('dotenv').config({ quiet: true })
|
||||
require('./otel') // must load before express/pg are used, for auto-instrumentation
|
||||
|
||||
const path = require('path')
|
||||
const express = require('express')
|
||||
const cors = require('cors')
|
||||
const { pool } = require('./db')
|
||||
const { log } = require('./otel')
|
||||
const { FEEDS, syncAll, fetchCommentsTree } = require('./hn')
|
||||
|
||||
const PORT = Number(process.env.PORT || 3012)
|
||||
const SYNC_INTERVAL_MS = 5 * 60 * 1000
|
||||
|
||||
const app = express()
|
||||
app.use(cors())
|
||||
app.use(express.json())
|
||||
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
try {
|
||||
await pool.query('SELECT 1')
|
||||
res.json({ ok: true })
|
||||
} catch (err) {
|
||||
res.status(503).json({ ok: false, error: String(err) })
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/api/feed/:feed', async (req, res) => {
|
||||
const { feed } = req.params
|
||||
if (!FEEDS[feed]) return res.status(404).json({ error: 'unknown feed' })
|
||||
|
||||
const limit = Math.min(Number(req.query.limit) || 100, 100)
|
||||
const includeArchived = req.query.includeArchived === 'true'
|
||||
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT s.id, s.type, s.title, s.url, s.domain, s.by_user, s.score, s.descendants,
|
||||
s.story_text, s.hn_created_at, fi.rank,
|
||||
COALESCE(st.read, false) AS read,
|
||||
COALESCE(st.starred, false) AS starred,
|
||||
COALESCE(st.archived, false) AS archived
|
||||
FROM feed_items fi
|
||||
JOIN stories s ON s.id = fi.story_id
|
||||
LEFT JOIN story_state st ON st.story_id = s.id
|
||||
WHERE fi.feed = $1 ${includeArchived ? '' : 'AND COALESCE(st.archived, false) = false'}
|
||||
ORDER BY fi.rank ASC
|
||||
LIMIT $2`,
|
||||
[feed, limit]
|
||||
)
|
||||
res.json({ feed, items: rows })
|
||||
} catch (err) {
|
||||
log('ERROR', 'feed query failed', { feed, error: String(err) })
|
||||
res.status(500).json({ error: 'internal error' })
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/api/story/:id', async (req, res) => {
|
||||
const id = Number(req.params.id)
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT s.*, COALESCE(st.read, false) AS read,
|
||||
COALESCE(st.starred, false) AS starred,
|
||||
COALESCE(st.archived, false) AS archived
|
||||
FROM stories s
|
||||
LEFT JOIN story_state st ON st.story_id = s.id
|
||||
WHERE s.id = $1`,
|
||||
[id]
|
||||
)
|
||||
if (!rows.length) return res.status(404).json({ error: 'not found' })
|
||||
res.json(rows[0])
|
||||
} catch (err) {
|
||||
log('ERROR', 'story query failed', { id, error: String(err) })
|
||||
res.status(500).json({ error: 'internal error' })
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/api/story/:id/comments', async (req, res) => {
|
||||
const id = Number(req.params.id)
|
||||
try {
|
||||
const comments = await fetchCommentsTree(id)
|
||||
res.json({ id, comments })
|
||||
} catch (err) {
|
||||
log('ERROR', 'comments fetch failed', { id, error: String(err) })
|
||||
res.status(502).json({ error: 'failed to fetch comments' })
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/api/story/:id/state', async (req, res) => {
|
||||
const id = Number(req.params.id)
|
||||
const { read, starred, archived } = req.body || {}
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO story_state (story_id, read, starred, archived, read_at, updated_at)
|
||||
VALUES ($1, COALESCE($2, false), COALESCE($3, false), COALESCE($4, false),
|
||||
CASE WHEN $2 THEN now() ELSE NULL END, now())
|
||||
ON CONFLICT (story_id) DO UPDATE SET
|
||||
read = COALESCE($2, story_state.read),
|
||||
starred = COALESCE($3, story_state.starred),
|
||||
archived = COALESCE($4, story_state.archived),
|
||||
read_at = CASE WHEN COALESCE($2, story_state.read) AND NOT story_state.read
|
||||
THEN now() ELSE story_state.read_at END,
|
||||
updated_at = now()
|
||||
RETURNING *`,
|
||||
[id, read, starred, archived]
|
||||
)
|
||||
res.json(rows[0])
|
||||
} catch (err) {
|
||||
log('ERROR', 'state update failed', { id, error: String(err) })
|
||||
res.status(500).json({ error: 'internal error' })
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/api/sync', async (_req, res) => {
|
||||
syncAll().catch((err) => log('ERROR', 'manual sync failed', { error: String(err) }))
|
||||
res.json({ ok: true, started: true })
|
||||
})
|
||||
|
||||
// Serve the built frontend in production.
|
||||
const distDir = path.join(__dirname, '..', 'dist')
|
||||
app.use(express.static(distDir))
|
||||
app.get(/^(?!\/api).*/, (_req, res) => {
|
||||
res.sendFile(path.join(distDir, 'index.html'))
|
||||
})
|
||||
|
||||
app.listen(PORT, () => {
|
||||
log('INFO', 'hn-reader-api listening', { port: PORT })
|
||||
})
|
||||
|
||||
syncAll()
|
||||
.then(() => log('INFO', 'initial sync complete'))
|
||||
.catch((err) => log('ERROR', 'initial sync failed', { error: String(err) }))
|
||||
|
||||
setInterval(() => {
|
||||
syncAll().catch((err) => log('ERROR', 'periodic sync failed', { error: String(err) }))
|
||||
}, SYNC_INTERVAL_MS)
|
||||
@@ -0,0 +1,59 @@
|
||||
// OpenTelemetry bootstrap: sends traces, metrics and logs to the LGTM
|
||||
// stack's OTLP/HTTP collector at http://localhost:4318. Must be required
|
||||
// before any other module so auto-instrumentation can patch http/express/pg.
|
||||
const { NodeSDK } = require('@opentelemetry/sdk-node')
|
||||
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node')
|
||||
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http')
|
||||
const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-http')
|
||||
const { OTLPLogExporter } = require('@opentelemetry/exporter-logs-otlp-http')
|
||||
const { PeriodicExportingMetricReader } = require('@opentelemetry/sdk-metrics')
|
||||
const { BatchLogRecordProcessor } = require('@opentelemetry/sdk-logs')
|
||||
const { resourceFromAttributes } = require('@opentelemetry/resources')
|
||||
const { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } = require('@opentelemetry/semantic-conventions')
|
||||
const { logs } = require('@opentelemetry/api-logs')
|
||||
|
||||
const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4318'
|
||||
|
||||
const resource = resourceFromAttributes({
|
||||
[ATTR_SERVICE_NAME]: 'hn-reader-api',
|
||||
[ATTR_SERVICE_VERSION]: '1.0.0',
|
||||
})
|
||||
|
||||
const sdk = new NodeSDK({
|
||||
resource,
|
||||
traceExporter: new OTLPTraceExporter({ url: `${endpoint}/v1/traces` }),
|
||||
metricReader: new PeriodicExportingMetricReader({
|
||||
exporter: new OTLPMetricExporter({ url: `${endpoint}/v1/metrics` }),
|
||||
exportIntervalMillis: 15000,
|
||||
}),
|
||||
logRecordProcessors: [
|
||||
new BatchLogRecordProcessor(new OTLPLogExporter({ url: `${endpoint}/v1/logs` })),
|
||||
],
|
||||
instrumentations: [
|
||||
getNodeAutoInstrumentations({
|
||||
'@opentelemetry/instrumentation-fs': { enabled: false },
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
sdk.start()
|
||||
|
||||
process.on('SIGTERM', () => sdk.shutdown().finally(() => process.exit(0)))
|
||||
|
||||
const otelLogger = logs.getLogger('hn-reader-api')
|
||||
|
||||
// Small structured logger: prints to stdout (captured by journald) and
|
||||
// emits an OTLP log record so logs show up alongside traces in Grafana.
|
||||
function log(severity, message, attributes = {}) {
|
||||
const line = `[${severity}] ${message} ${Object.keys(attributes).length ? JSON.stringify(attributes) : ''}`
|
||||
if (severity === 'ERROR') console.error(line)
|
||||
else console.log(line)
|
||||
|
||||
otelLogger.emit({
|
||||
severityText: severity,
|
||||
body: message,
|
||||
attributes,
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = { log }
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"type": "commonjs"
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { Keyboard, Loader2, RotateCw } from 'lucide-react'
|
||||
import { Toaster, toast } from 'sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { FeedTabs } from '@/components/FeedTabs'
|
||||
import { StoryList } from '@/components/StoryList'
|
||||
import { CommentsDialog } from '@/components/CommentsDialog'
|
||||
import { ShortcutsDialog } from '@/components/ShortcutsDialog'
|
||||
import { useFeed } from '@/hooks/useFeed'
|
||||
import { useHotkeys } from '@/hooks/useHotkeys'
|
||||
import { updateStoryState } from '@/lib/api'
|
||||
import type { FeedKey, Story } from '@/types/story'
|
||||
|
||||
const FEED_ORDER: FeedKey[] = ['top', 'new', 'best', 'ask', 'show', 'job']
|
||||
const LAST_FEED_KEY = 'hn-reader:v1:last-feed'
|
||||
|
||||
function isFeedKey(v: string | null): v is FeedKey {
|
||||
return !!v && (FEED_ORDER as string[]).includes(v)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [feed, setFeed] = useState<FeedKey>(() => {
|
||||
const saved = localStorage.getItem(LAST_FEED_KEY)
|
||||
return isFeedKey(saved) ? saved : 'top'
|
||||
})
|
||||
const [selectedIndex, setSelectedIndex] = useState(0)
|
||||
const [commentsStory, setCommentsStory] = useState<Story | null>(null)
|
||||
const [commentsOpen, setCommentsOpen] = useState(false)
|
||||
const [shortcutsOpen, setShortcutsOpen] = useState(false)
|
||||
|
||||
const { items, loading, refresh, patchStory } = useFeed(feed)
|
||||
|
||||
const visible = useMemo(() => items.filter((s) => !s.archived), [items])
|
||||
const selected = visible[selectedIndex] ?? null
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(LAST_FEED_KEY, feed)
|
||||
setSelectedIndex(0)
|
||||
}, [feed])
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedIndex >= visible.length) {
|
||||
setSelectedIndex(Math.max(0, visible.length - 1))
|
||||
}
|
||||
}, [visible.length, selectedIndex])
|
||||
|
||||
useEffect(() => {
|
||||
if (selected) {
|
||||
document
|
||||
.getElementById(`story-${selected.id}`)
|
||||
?.scrollIntoView({ block: 'nearest' })
|
||||
}
|
||||
}, [selected])
|
||||
|
||||
const markRead = useCallback(
|
||||
(story: Story) => {
|
||||
if (story.read) return
|
||||
patchStory(story.id, { read: true })
|
||||
updateStoryState(story.id, { read: true }).catch(() => {})
|
||||
},
|
||||
[patchStory]
|
||||
)
|
||||
|
||||
const openComments = useCallback(
|
||||
(story: Story) => {
|
||||
markRead(story)
|
||||
setCommentsStory(story)
|
||||
setCommentsOpen(true)
|
||||
},
|
||||
[markRead]
|
||||
)
|
||||
|
||||
const openExternal = useCallback(
|
||||
(story: Story) => {
|
||||
markRead(story)
|
||||
const url = story.url ?? `https://news.ycombinator.com/item?id=${story.id}`
|
||||
window.open(url, '_blank', 'noopener,noreferrer')
|
||||
},
|
||||
[markRead]
|
||||
)
|
||||
|
||||
const archive = useCallback(
|
||||
(story: Story) => {
|
||||
patchStory(story.id, { archived: true })
|
||||
updateStoryState(story.id, { archived: true }).catch(() => {})
|
||||
toast('Archived', { description: story.title })
|
||||
},
|
||||
[patchStory]
|
||||
)
|
||||
|
||||
const toggleStar = useCallback(
|
||||
(story: Story) => {
|
||||
const starred = !story.starred
|
||||
patchStory(story.id, { starred })
|
||||
updateStoryState(story.id, { starred }).catch(() => {})
|
||||
},
|
||||
[patchStory]
|
||||
)
|
||||
|
||||
const toggleRead = useCallback(
|
||||
(story: Story) => {
|
||||
const read = !story.read
|
||||
patchStory(story.id, { read })
|
||||
updateStoryState(story.id, { read }).catch(() => {})
|
||||
},
|
||||
[patchStory]
|
||||
)
|
||||
|
||||
const move = useCallback(
|
||||
(delta: number) => {
|
||||
setSelectedIndex((i) => Math.min(Math.max(i + delta, 0), visible.length - 1))
|
||||
},
|
||||
[visible.length]
|
||||
)
|
||||
|
||||
useHotkeys(
|
||||
{
|
||||
j: () => move(1),
|
||||
ArrowDown: () => move(1),
|
||||
k: () => move(-1),
|
||||
ArrowUp: () => move(-1),
|
||||
o: () => selected && openComments(selected),
|
||||
Enter: () => selected && openComments(selected),
|
||||
v: () => selected && openExternal(selected),
|
||||
e: () => selected && archive(selected),
|
||||
s: () => selected && toggleStar(selected),
|
||||
u: () => selected && toggleRead(selected),
|
||||
r: () => refresh(),
|
||||
'?': () => setShortcutsOpen((v) => !v),
|
||||
Escape: () => {
|
||||
setCommentsOpen(false)
|
||||
setShortcutsOpen(false)
|
||||
},
|
||||
'1': () => setFeed('top'),
|
||||
'2': () => setFeed('new'),
|
||||
'3': () => setFeed('best'),
|
||||
'4': () => setFeed('ask'),
|
||||
'5': () => setFeed('show'),
|
||||
'6': () => setFeed('job'),
|
||||
},
|
||||
[selected, move, openComments, openExternal, archive, toggleStar, toggleRead, refresh]
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex min-h-svh w-full max-w-2xl flex-col border-x border-border bg-background">
|
||||
<Toaster position="bottom-center" />
|
||||
|
||||
<header className="sticky top-0 z-10 flex items-center justify-between gap-2 border-b border-border bg-background/95 px-3 py-2 backdrop-blur sm:px-4">
|
||||
<h1 className="text-sm font-semibold tracking-tight">HN Reader</h1>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button variant="ghost" size="icon" onClick={() => refresh()} aria-label="Refresh">
|
||||
{loading ? <Loader2 className="size-4 animate-spin" /> : <RotateCw className="size-4" />}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setShortcutsOpen(true)}
|
||||
aria-label="Keyboard shortcuts"
|
||||
>
|
||||
<Keyboard className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<FeedTabs active={feed} onChange={setFeed} />
|
||||
|
||||
<main className="flex-1">
|
||||
{visible.length === 0 && loading && (
|
||||
<div className="flex items-center justify-center gap-2 py-16 text-sm text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" /> Loading stories…
|
||||
</div>
|
||||
)}
|
||||
{visible.length === 0 && !loading && (
|
||||
<p className="py-16 text-center text-sm text-muted-foreground">
|
||||
Nothing here. Press <kbd>r</kbd> to refresh.
|
||||
</p>
|
||||
)}
|
||||
<StoryList
|
||||
items={visible}
|
||||
selectedId={selected?.id ?? null}
|
||||
onSelect={(id) => {
|
||||
const idx = visible.findIndex((s) => s.id === id)
|
||||
if (idx >= 0) setSelectedIndex(idx)
|
||||
}}
|
||||
onOpenComments={openComments}
|
||||
/>
|
||||
</main>
|
||||
|
||||
<CommentsDialog story={commentsStory} open={commentsOpen} onOpenChange={setCommentsOpen} />
|
||||
<ShortcutsDialog open={shortcutsOpen} onOpenChange={setShortcutsOpen} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ExternalLink, Loader2 } from 'lucide-react'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
} from '@/components/ui/dialog'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { fetchComments } from '@/lib/api'
|
||||
import { getCachedComments, setCachedComments } from '@/lib/cache'
|
||||
import { sanitizeHnHtml } from '@/lib/sanitize'
|
||||
import { timeAgo } from '@/lib/time'
|
||||
import type { Comment, Story } from '@/types/story'
|
||||
|
||||
export function CommentsDialog({
|
||||
story,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
story: Story | null
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}) {
|
||||
const [comments, setComments] = useState<Comment[] | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!story || !open) return
|
||||
const cached = getCachedComments(story.id)
|
||||
setComments(cached ?? null)
|
||||
setLoading(!cached)
|
||||
fetchComments(story.id)
|
||||
.then(({ comments: fresh }) => {
|
||||
setComments(fresh)
|
||||
setCachedComments(story.id, fresh)
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false))
|
||||
}, [story, open])
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="flex h-[85vh] max-w-2xl flex-col gap-0 p-0">
|
||||
{story && (
|
||||
<>
|
||||
<DialogHeader className="gap-1 border-b px-5 py-4 text-left">
|
||||
<DialogTitle className="text-base leading-snug font-semibold">
|
||||
{story.title}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="flex flex-wrap items-center gap-x-2 text-xs">
|
||||
<span>
|
||||
{story.score} points by {story.by_user} · {timeAgo(story.hn_created_at)} ago
|
||||
</span>
|
||||
{story.url && (
|
||||
<a
|
||||
href={story.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-primary hover:underline"
|
||||
>
|
||||
{story.domain} <ExternalLink className="size-3" />
|
||||
</a>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className="flex-1 px-5 py-3">
|
||||
{story.story_text && (
|
||||
<div
|
||||
className="prose-hn mb-4 text-sm"
|
||||
dangerouslySetInnerHTML={{ __html: sanitizeHnHtml(story.story_text) }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{loading && !comments?.length && (
|
||||
<div className="flex items-center gap-2 py-8 text-sm text-muted-foreground">
|
||||
<Loader2 className="size-4 animate-spin" /> Loading comments…
|
||||
</div>
|
||||
)}
|
||||
|
||||
{comments && comments.length === 0 && !loading && (
|
||||
<p className="py-8 text-sm text-muted-foreground">No comments yet.</p>
|
||||
)}
|
||||
|
||||
{comments?.map((c) => <CommentNode key={c.id} comment={c} />)}
|
||||
</ScrollArea>
|
||||
</>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function CommentNode({ comment, depth = 0 }: { comment: Comment; depth?: number }) {
|
||||
if (!comment.text) return null
|
||||
return (
|
||||
<div className={depth > 0 ? 'mt-3 border-l-2 border-border pl-3' : 'mt-3'}>
|
||||
<div className="mb-1 text-xs text-muted-foreground">
|
||||
<span className="font-medium text-foreground">{comment.by}</span>
|
||||
{comment.time && <> · {timeAgo(new Date(comment.time * 1000).toISOString())} ago</>}
|
||||
</div>
|
||||
<div
|
||||
className="prose-hn text-sm break-words"
|
||||
dangerouslySetInnerHTML={{ __html: sanitizeHnHtml(comment.text) }}
|
||||
/>
|
||||
{comment.kids?.map((k) => <CommentNode key={k.id} comment={k} depth={depth + 1} />)}
|
||||
{depth === 0 && <Separator className="mt-3" />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { FeedKey } from '@/types/story'
|
||||
|
||||
const FEEDS: { key: FeedKey; label: string; shortcut: string }[] = [
|
||||
{ key: 'top', label: 'Top', shortcut: '1' },
|
||||
{ key: 'new', label: 'New', shortcut: '2' },
|
||||
{ key: 'best', label: 'Best', shortcut: '3' },
|
||||
{ key: 'ask', label: 'Ask', shortcut: '4' },
|
||||
{ key: 'show', label: 'Show', shortcut: '5' },
|
||||
{ key: 'job', label: 'Jobs', shortcut: '6' },
|
||||
]
|
||||
|
||||
export function FeedTabs({
|
||||
active,
|
||||
onChange,
|
||||
}: {
|
||||
active: FeedKey
|
||||
onChange: (feed: FeedKey) => void
|
||||
}) {
|
||||
return (
|
||||
<nav className="flex gap-1 overflow-x-auto px-2 py-1.5 sm:px-3" aria-label="Feeds">
|
||||
{FEEDS.map((f) => (
|
||||
<button
|
||||
key={f.key}
|
||||
type="button"
|
||||
onClick={() => onChange(f.key)}
|
||||
className={cn(
|
||||
'shrink-0 rounded-md px-2.5 py-1 text-sm font-medium transition-colors',
|
||||
active === f.key
|
||||
? 'bg-primary text-primary-foreground'
|
||||
: 'text-muted-foreground hover:bg-accent hover:text-foreground'
|
||||
)}
|
||||
>
|
||||
{f.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
|
||||
const SHORTCUTS: [string, string][] = [
|
||||
['j / ↓', 'Next story'],
|
||||
['k / ↑', 'Previous story'],
|
||||
['o / Enter', 'Open comments'],
|
||||
['v', 'Open link in new tab'],
|
||||
['e', 'Archive story'],
|
||||
['s', 'Star / unstar'],
|
||||
['u', 'Toggle read / unread'],
|
||||
['r', 'Refresh feed'],
|
||||
['1 – 6', 'Switch feed (Top/New/Best/Ask/Show/Jobs)'],
|
||||
['Esc', 'Close dialog'],
|
||||
['?', 'Toggle this help'],
|
||||
]
|
||||
|
||||
export function ShortcutsDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-sm">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Keyboard shortcuts</DialogTitle>
|
||||
</DialogHeader>
|
||||
<dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-2 text-sm">
|
||||
{SHORTCUTS.map(([key, desc]) => (
|
||||
<div key={key} className="contents">
|
||||
<dt>
|
||||
<kbd className="rounded border bg-muted px-1.5 py-0.5 font-mono text-xs">
|
||||
{key}
|
||||
</kbd>
|
||||
</dt>
|
||||
<dd className="text-muted-foreground">{desc}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { forwardRef } from 'react'
|
||||
import { Star, MessageSquare, ArrowUp } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { timeAgo } from '@/lib/time'
|
||||
import type { Story } from '@/types/story'
|
||||
|
||||
interface StoryListProps {
|
||||
items: Story[]
|
||||
selectedId: string | null
|
||||
onSelect: (id: string) => void
|
||||
onOpenComments: (story: Story) => void
|
||||
}
|
||||
|
||||
export function StoryList({ items, selectedId, onSelect, onOpenComments }: StoryListProps) {
|
||||
return (
|
||||
<ul className="divide-y divide-border" role="listbox" aria-label="Stories">
|
||||
{items.map((story) => (
|
||||
<StoryRow
|
||||
key={story.id}
|
||||
story={story}
|
||||
selected={story.id === selectedId}
|
||||
onSelect={onSelect}
|
||||
onOpenComments={onOpenComments}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
interface StoryRowProps {
|
||||
story: Story
|
||||
selected: boolean
|
||||
onSelect: (id: string) => void
|
||||
onOpenComments: (story: Story) => void
|
||||
}
|
||||
|
||||
const StoryRow = forwardRef<HTMLLIElement, StoryRowProps>(function StoryRow(
|
||||
{ story, selected, onSelect, onOpenComments },
|
||||
ref
|
||||
) {
|
||||
return (
|
||||
<li
|
||||
ref={ref}
|
||||
id={`story-${story.id}`}
|
||||
role="option"
|
||||
aria-selected={selected}
|
||||
data-selected={selected || undefined}
|
||||
onClick={() => {
|
||||
onSelect(story.id)
|
||||
onOpenComments(story)
|
||||
}}
|
||||
className={cn(
|
||||
'flex cursor-pointer items-start gap-3 border-l-2 border-l-transparent px-3 py-2.5 sm:px-4',
|
||||
selected && 'border-l-primary bg-accent',
|
||||
story.read && !selected && 'opacity-55'
|
||||
)}
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="truncate text-[15px] leading-snug font-medium text-foreground">
|
||||
{story.title}
|
||||
</span>
|
||||
{story.starred && (
|
||||
<Star className="size-3.5 shrink-0 fill-current text-amber-500" aria-label="starred" />
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs text-muted-foreground">
|
||||
{story.domain && <span className="truncate">{story.domain}</span>}
|
||||
<span className="inline-flex items-center gap-0.5">
|
||||
<ArrowUp className="size-3" />
|
||||
{story.score}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-0.5">
|
||||
<MessageSquare className="size-3" />
|
||||
{story.descendants}
|
||||
</span>
|
||||
<span>{story.by_user}</span>
|
||||
<span>{timeAgo(story.hn_created_at)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { ThemeProvider as NextThemesProvider } from 'next-themes'
|
||||
import type { ComponentProps } from 'react'
|
||||
|
||||
export function ThemeProvider({ children, ...props }: ComponentProps<typeof NextThemesProvider>) {
|
||||
return (
|
||||
<NextThemesProvider attribute="class" defaultTheme="system" enableSystem {...props}>
|
||||
{children}
|
||||
</NextThemesProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const badgeVariants = cva(
|
||||
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
|
||||
destructive:
|
||||
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
|
||||
outline:
|
||||
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
|
||||
ghost:
|
||||
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot.Root : "span"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
data-variant={variant}
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants }
|
||||
@@ -0,0 +1,67 @@
|
||||
import * as React from "react"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { Slot } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const buttonVariants = cva(
|
||||
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/80",
|
||||
outline:
|
||||
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
|
||||
ghost:
|
||||
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
|
||||
destructive:
|
||||
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default:
|
||||
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
|
||||
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
|
||||
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
|
||||
icon: "size-8",
|
||||
"icon-xs":
|
||||
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
|
||||
"icon-sm":
|
||||
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
|
||||
"icon-lg": "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant = "default",
|
||||
size = "default",
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot.Root : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,166 @@
|
||||
import * as React from "react"
|
||||
import { Dialog as DialogPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { XIcon } from "lucide-react"
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
showCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close data-slot="dialog-close" asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="absolute top-2 right-2"
|
||||
size="icon-sm"
|
||||
>
|
||||
<XIcon
|
||||
/>
|
||||
<span className="sr-only">Close</span>
|
||||
</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogFooter({
|
||||
className,
|
||||
showCloseButton = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showCloseButton?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close asChild>
|
||||
<Button variant="outline">Close</Button>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn(
|
||||
"font-heading text-base leading-none font-medium",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn(
|
||||
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,53 @@
|
||||
import * as React from "react"
|
||||
import { ScrollArea as ScrollAreaPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
)
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
data-orientation={orientation}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="relative flex-1 rounded-full bg-border"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
)
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar }
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Separator as SeparatorPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
@@ -0,0 +1,13 @@
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("animate-pulse rounded-md bg-muted", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client"
|
||||
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
import { CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon, Loader2Icon } from "lucide-react"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: (
|
||||
<CircleCheckIcon className="size-4" />
|
||||
),
|
||||
info: (
|
||||
<InfoIcon className="size-4" />
|
||||
),
|
||||
warning: (
|
||||
<TriangleAlertIcon className="size-4" />
|
||||
),
|
||||
error: (
|
||||
<OctagonXIcon className="size-4" />
|
||||
),
|
||||
loading: (
|
||||
<Loader2Icon className="size-4 animate-spin" />
|
||||
),
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
toastOptions={{
|
||||
classNames: {
|
||||
toast: "cn-toast",
|
||||
},
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -0,0 +1,55 @@
|
||||
import * as React from "react"
|
||||
import { Tooltip as TooltipPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 inline-flex w-fit max-w-xs origin-(--radix-tooltip-content-transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger }
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { fetchFeed, triggerSync } from '@/lib/api'
|
||||
import { getCachedFeed, setCachedFeed } from '@/lib/cache'
|
||||
import type { FeedKey, Story } from '@/types/story'
|
||||
|
||||
export function useFeed(feed: FeedKey) {
|
||||
const [items, setItems] = useState<Story[]>(() => getCachedFeed(feed) ?? [])
|
||||
const [loading, setLoading] = useState(items.length === 0)
|
||||
const feedRef = useRef(feed)
|
||||
feedRef.current = feed
|
||||
|
||||
const load = useCallback((f: FeedKey) => {
|
||||
setItems(getCachedFeed(f) ?? [])
|
||||
setLoading((getCachedFeed(f) ?? []).length === 0)
|
||||
fetchFeed(f)
|
||||
.then(({ items: fresh }) => {
|
||||
if (feedRef.current !== f) return
|
||||
setItems(fresh)
|
||||
setCachedFeed(f, fresh)
|
||||
})
|
||||
.catch(() => {
|
||||
// network hiccup — cached data (if any) stays on screen
|
||||
})
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load(feed)
|
||||
}, [feed, load])
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
await triggerSync()
|
||||
// give the backend a moment to write the refreshed feed, then reload
|
||||
setTimeout(() => load(feedRef.current), 1500)
|
||||
}, [load])
|
||||
|
||||
const patchStory = useCallback((id: string, patch: Partial<Story>) => {
|
||||
setItems((prev) => {
|
||||
const next = prev.map((s) => (s.id === id ? { ...s, ...patch } : s))
|
||||
setCachedFeed(feedRef.current, next)
|
||||
return next
|
||||
})
|
||||
}, [])
|
||||
|
||||
return { items, loading, refresh, patchStory }
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useEffect } from 'react'
|
||||
|
||||
type Handler = (e: KeyboardEvent) => void
|
||||
|
||||
// Superhuman-style single-key shortcuts. Ignored while typing in an input
|
||||
// so pressing "j"/"k" in the search box doesn't hijack the cursor.
|
||||
export function useHotkeys(bindings: Record<string, Handler>, deps: unknown[]) {
|
||||
useEffect(() => {
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
const target = e.target as HTMLElement | null
|
||||
const typing =
|
||||
target &&
|
||||
(target.tagName === 'INPUT' ||
|
||||
target.tagName === 'TEXTAREA' ||
|
||||
target.isContentEditable)
|
||||
if (typing && e.key !== 'Escape') return
|
||||
|
||||
const handler = bindings[e.key]
|
||||
if (handler) {
|
||||
e.preventDefault()
|
||||
handler(e)
|
||||
}
|
||||
}
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
return () => window.removeEventListener('keydown', onKeyDown)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, deps)
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
@import "@fontsource-variable/geist";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme inline {
|
||||
--font-heading: var(--font-sans);
|
||||
--font-sans: 'Geist Variable', sans-serif;
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-ring: var(--ring);
|
||||
--color-input: var(--input);
|
||||
--color-border: var(--border);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-card: var(--card);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-background: var(--background);
|
||||
--radius-sm: calc(var(--radius) * 0.6);
|
||||
--radius-md: calc(var(--radius) * 0.8);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) * 1.4);
|
||||
--radius-2xl: calc(var(--radius) * 1.8);
|
||||
--radius-3xl: calc(var(--radius) * 2.2);
|
||||
--radius-4xl: calc(var(--radius) * 2.6);
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.87 0 0);
|
||||
--chart-2: oklch(0.556 0 0);
|
||||
--chart-3: oklch(0.439 0 0);
|
||||
--chart-4: oklch(0.371 0 0);
|
||||
--chart-5: oklch(0.269 0 0);
|
||||
--radius: 0.625rem;
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.87 0 0);
|
||||
--chart-2: oklch(0.556 0 0);
|
||||
--chart-3: oklch(0.439 0 0);
|
||||
--chart-4: oklch(0.371 0 0);
|
||||
--chart-5: oklch(0.269 0 0);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
html {
|
||||
@apply font-sans;
|
||||
}
|
||||
}
|
||||
|
||||
.prose-hn p {
|
||||
margin: 0 0 0.6em;
|
||||
}
|
||||
.prose-hn p:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.prose-hn a {
|
||||
color: var(--primary);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
.prose-hn pre {
|
||||
overflow-x: auto;
|
||||
background: var(--muted);
|
||||
padding: 0.5em;
|
||||
border-radius: 0.375rem;
|
||||
}
|
||||
.prose-hn code {
|
||||
font-family: ui-monospace, monospace;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { Comment, FeedKey, Story } from '@/types/story'
|
||||
|
||||
async function json<T>(res: Response): Promise<T> {
|
||||
if (!res.ok) throw new Error(`request failed: ${res.status}`)
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
export function fetchFeed(feed: FeedKey): Promise<{ feed: FeedKey; items: Story[] }> {
|
||||
return fetch(`/api/feed/${feed}`).then((res) => json(res))
|
||||
}
|
||||
|
||||
export function fetchComments(id: string): Promise<{ id: string; comments: Comment[] }> {
|
||||
return fetch(`/api/story/${id}/comments`).then((res) => json(res))
|
||||
}
|
||||
|
||||
export function updateStoryState(
|
||||
id: string,
|
||||
patch: Partial<Pick<Story, 'read' | 'starred' | 'archived'>>
|
||||
): Promise<Story> {
|
||||
return fetch(`/api/story/${id}/state`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(patch),
|
||||
}).then((res) => json(res))
|
||||
}
|
||||
|
||||
export function triggerSync(): Promise<{ ok: boolean }> {
|
||||
return fetch('/api/sync', { method: 'POST' }).then((res) => json(res))
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { FeedKey, Story } from '@/types/story'
|
||||
|
||||
// localStorage cache so switching feeds and reopening the app is instant
|
||||
// (stale-while-revalidate), the same trick Linear/Superhuman use to feel
|
||||
// fast on a slow network.
|
||||
const VERSION = 'v1'
|
||||
const feedKey = (feed: FeedKey) => `hn-reader:${VERSION}:feed:${feed}`
|
||||
const commentsKey = (id: string) => `hn-reader:${VERSION}:comments:${id}`
|
||||
|
||||
export function getCachedFeed(feed: FeedKey): Story[] | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(feedKey(feed))
|
||||
return raw ? (JSON.parse(raw) as Story[]) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function setCachedFeed(feed: FeedKey, items: Story[]) {
|
||||
try {
|
||||
localStorage.setItem(feedKey(feed), JSON.stringify(items))
|
||||
} catch {
|
||||
// storage full or unavailable — safe to ignore, cache is best-effort
|
||||
}
|
||||
}
|
||||
|
||||
export function getCachedComments(id: string) {
|
||||
try {
|
||||
const raw = localStorage.getItem(commentsKey(id))
|
||||
return raw ? JSON.parse(raw) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export function setCachedComments(id: string, comments: unknown) {
|
||||
try {
|
||||
localStorage.setItem(commentsKey(id), JSON.stringify(comments))
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
const ALLOWED_TAGS = new Set(['A', 'P', 'I', 'B', 'EM', 'STRONG', 'CODE', 'PRE'])
|
||||
|
||||
// HN item text/comment text is HTML from an external API. Rebuild it from
|
||||
// a small tag allowlist instead of trusting it directly, to keep
|
||||
// dangerouslySetInnerHTML from becoming an XSS vector.
|
||||
export function sanitizeHnHtml(html: string): string {
|
||||
const doc = new DOMParser().parseFromString(html, 'text/html')
|
||||
|
||||
function clean(node: Node): string {
|
||||
if (node.nodeType === Node.TEXT_NODE) {
|
||||
return node.textContent ?? ''
|
||||
}
|
||||
if (node.nodeType !== Node.ELEMENT_NODE) return ''
|
||||
|
||||
const el = node as Element
|
||||
const inner = Array.from(el.childNodes).map(clean).join('')
|
||||
if (!ALLOWED_TAGS.has(el.tagName)) return inner
|
||||
|
||||
if (el.tagName === 'A') {
|
||||
const href = el.getAttribute('href') || ''
|
||||
const safe = /^https?:\/\//i.test(href)
|
||||
return safe
|
||||
? `<a href="${href.replace(/"/g, '"')}" target="_blank" rel="noopener noreferrer nofollow">${inner}</a>`
|
||||
: inner
|
||||
}
|
||||
|
||||
const tag = el.tagName.toLowerCase()
|
||||
return `<${tag}>${inner}</${tag}>`
|
||||
}
|
||||
|
||||
return Array.from(doc.body.childNodes).map(clean).join('')
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export function timeAgo(iso: string): string {
|
||||
const seconds = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000)
|
||||
const units: [string, number][] = [
|
||||
['y', 31536000],
|
||||
['mo', 2592000],
|
||||
['d', 86400],
|
||||
['h', 3600],
|
||||
['m', 60],
|
||||
]
|
||||
for (const [label, secs] of units) {
|
||||
const value = Math.floor(seconds / secs)
|
||||
if (value >= 1) return `${value}${label}`
|
||||
}
|
||||
return 'now'
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import { ThemeProvider } from './components/theme-provider.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<ThemeProvider>
|
||||
<App />
|
||||
</ThemeProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
export type FeedKey = 'top' | 'new' | 'best' | 'ask' | 'show' | 'job'
|
||||
|
||||
export interface Story {
|
||||
id: string
|
||||
type: string
|
||||
title: string
|
||||
url: string | null
|
||||
domain: string | null
|
||||
by_user: string | null
|
||||
score: number
|
||||
descendants: number
|
||||
story_text: string | null
|
||||
hn_created_at: string
|
||||
rank: number
|
||||
read: boolean
|
||||
starred: boolean
|
||||
archived: boolean
|
||||
}
|
||||
|
||||
export interface Comment {
|
||||
id: number
|
||||
by: string | null
|
||||
text: string | null
|
||||
time: number | null
|
||||
kids: Comment[]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
],
|
||||
"compilerOptions": {
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import path from 'path'
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 3012,
|
||||
strictPort: true,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3013',
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user