diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..3afb422 --- /dev/null +++ b/.env.example @@ -0,0 +1,36 @@ +# Study Desk configuration. Every value is optional. +# In Docker, set these as container environment variables instead of using this file. + +# Where the database, uploads and backups live. Default: /data in the container, ./data otherwise. +# DATA_DIR=/data + +# Port and bind address. +# PORT=3726 +# HOST=0.0.0.0 + +# First-run administrator password. If unset, the first visit shows a setup screen that asks +# for the one-time code printed in the log (also written to DATA_DIR/setup-code.txt). +# ADMIN_PASSWORD= + +# Forgot the password? Set this, restart once, sign in, then remove it again. +# RESET_ADMIN_PASSWORD= + +# Secret used to encrypt AI provider API keys at rest. If unset, a random key is generated and +# stored in DATA_DIR/secret.key. Set it explicitly if you want the key kept outside the data folder. +# APP_SECRET= + +# Cookie "Secure" flag: auto (default: on whenever the request arrived over HTTPS), true or false. +# COOKIE_SECURE=auto + +# Trust X-Forwarded-* headers from a reverse proxy (default true). Set false if the container +# is exposed directly to the internet without a proxy. +# TRUST_PROXY=true + +# Largest upload accepted, in megabytes. +# MAX_UPLOAD_MB=100 + +# Number of automatic daily database snapshots to keep. +# BACKUP_KEEP=7 + +# Timezone used for "today", streaks and due dates until you change it in Settings. +# TZ=America/Phoenix diff --git a/.gitignore b/.gitignore index 521e923..7a7fd29 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ coverage/ .DS_Store npm-debug.log* .test-data/ +.claude/ diff --git a/scripts/build-server.mjs b/scripts/build-server.mjs new file mode 100644 index 0000000..2f41883 --- /dev/null +++ b/scripts/build-server.mjs @@ -0,0 +1,14 @@ +// Bundles the server into one file. Dependencies stay external and are installed in the image. +import { build } from 'esbuild'; + +await build({ + entryPoints: ['server/main.ts'], + outfile: 'dist/server/main.js', + bundle: true, + platform: 'node', + format: 'esm', + target: 'node24', + packages: 'external', + sourcemap: true, + logLevel: 'info', +}); diff --git a/scripts/make-icons.mjs b/scripts/make-icons.mjs new file mode 100644 index 0000000..c0f4145 --- /dev/null +++ b/scripts/make-icons.mjs @@ -0,0 +1,60 @@ +// Renders the PNG app icons (no image library needed): a dark tile with two "cards". +import fs from 'node:fs'; +import zlib from 'node:zlib'; + +function png(size, draw) { + const px = Buffer.alloc(size * size * 4); + draw(px, size); + const raw = Buffer.alloc((size * 4 + 1) * size); + for (let y = 0; y < size; y++) px.copy(raw, y * (size * 4 + 1) + 1, y * size * 4, (y + 1) * size * 4); + const chunk = (type, data) => { + const len = Buffer.alloc(4); + len.writeUInt32BE(data.length); + const body = Buffer.concat([Buffer.from(type), data]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(zlib.crc32(body) >>> 0); + return Buffer.concat([len, body, crc]); + }; + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); + ihdr.writeUInt32BE(size, 4); + ihdr[8] = 8; + ihdr[9] = 6; + return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw, { level: 9 })), chunk('IEND', Buffer.alloc(0))]); +} + +const hex = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)]; + +function icon(px, size) { + const s = size / 64; + const set = (x, y, [r, g, b], a = 1) => { + if (x < 0 || y < 0 || x >= size || y >= size) return; + const i = (y * size + x) * 4; + px[i] = px[i] * (1 - a) + r * a; + px[i + 1] = px[i + 1] * (1 - a) + g * a; + px[i + 2] = px[i + 2] * (1 - a) + b * a; + px[i + 3] = 255; + }; + const rrect = (x0, y0, w, h, r, color, rot = 0, cx = 0, cy = 0, alpha = 1) => { + const cos = Math.cos(-rot), sin = Math.sin(-rot); + for (let y = 0; y < size; y++) + for (let x = 0; x < size; x++) { + // rotate the sample point back into the rectangle's frame + const dx = x + 0.5 - cx * s, dy = y + 0.5 - cy * s; + const lx = (dx * cos - dy * sin) / s + cx, ly = (dx * sin + dy * cos) / s + cy; + const qx = Math.max(x0 + r - lx, 0, lx - (x0 + w - r)), qy = Math.max(y0 + r - ly, 0, ly - (y0 + h - r)); + const d = Math.hypot(qx, qy) - r; + const a = Math.max(0, Math.min(1, 0.5 - d * s)); + if (a > 0 && lx >= x0 - 1 && lx <= x0 + w + 1 && ly >= y0 - 1 && ly <= y0 + h + 1) set(x, y, color, a * alpha); + } + }; + rrect(0, 0, 64, 64, 0, hex('#1B1A17')); // full-bleed so maskable crops look right + rrect(14, 17, 30, 36, 4, hex('#FBFAF7'), (-7 * Math.PI) / 180, 29, 35); + rrect(21, 13, 30, 36, 4, hex('#FFE36E')); + rrect(27, 23, 18, 3.4, 1.7, hex('#1B1A17')); + rrect(27, 30.5, 13, 3.4, 1.7, hex('#1B1A17'), 0, 0, 0, 0.55); + rrect(27, 38, 15.5, 3.4, 1.7, hex('#1B1A17'), 0, 0, 0, 0.55); +} + +for (const size of [180, 192, 512]) fs.writeFileSync(`web/public/icon-${size}.png`, png(size, icon)); +console.log('icons written'); diff --git a/server/main.ts b/server/main.ts index 6cee523..6417f64 100644 --- a/server/main.ts +++ b/server/main.ts @@ -17,6 +17,12 @@ function log(level: 'info' | 'warn' | 'error', message: string, extra?: unknown) } async function main(): Promise { + // Optional .env file for running outside Docker. Real environment variables always win. + try { + process.loadEnvFile('.env'); + } catch { + /* no .env file: that is the normal case in a container */ + } const config = loadConfig(); log('info', `Study Desk ${APP_VERSION} starting (data: ${config.dataDir})`); diff --git a/server/routes/documents.ts b/server/routes/documents.ts index c3caaf0..c4492c2 100644 --- a/server/routes/documents.ts +++ b/server/routes/documents.ts @@ -71,12 +71,19 @@ export function documentRoutes(app: AppContext): Hono { r.get('/documents/:id/chunks', (c) => { const doc = getDocument(db, idParam(c)); - const offset = Math.max(0, Number(c.req.query('offset') ?? 0) || 0); + let offset = Math.max(0, Number(c.req.query('offset') ?? 0) || 0); const limit = Math.min(100, Math.max(1, Number(c.req.query('limit') ?? 40) || 40)); + // Deep link to one passage (from search or a citation): start just before it. + const around = Number(c.req.query('around')); + if (Number.isFinite(around) && around > 0) { + const hit = db.get<{ seq: number }>('SELECT seq FROM chunks WHERE id = ? AND document_id = ?', around, doc.id); + if (hit) offset = Math.max(0, hit.seq - 1); + } const chunks = listChunks(db, doc.id, offset, limit); return c.json({ chunks: chunks.map((ch) => ({ id: ch.id, seq: ch.seq, text: ch.text, heading: ch.heading, pageStart: ch.pageStart, pageEnd: ch.pageEnd, label: sourceLabel(ch) })), total: doc.chunk_count, + offset, nextOffset: chunks.length === limit && offset + limit < doc.chunk_count ? offset + limit : null, }); }); diff --git a/vite.config.ts b/vite.config.ts new file mode 100644 index 0000000..e5b63b5 --- /dev/null +++ b/vite.config.ts @@ -0,0 +1,31 @@ +import { fileURLToPath } from 'node:url'; +import tailwindcss from '@tailwindcss/vite'; +import react from '@vitejs/plugin-react'; +import { defineConfig } from 'vite'; + +const api = process.env.API_ORIGIN ?? 'http://localhost:3726'; + +export default defineConfig({ + root: 'web', + plugins: [react(), tailwindcss()], + resolve: { + alias: { + '@shared': fileURLToPath(new URL('./shared', import.meta.url)), + '@': fileURLToPath(new URL('./web/src', import.meta.url)), + }, + }, + server: { + port: 5173, + strictPort: false, + proxy: { + '/api': { target: api, changeOrigin: false }, + '/media': { target: api, changeOrigin: false }, + }, + }, + build: { + outDir: '../dist/web', + emptyOutDir: true, + sourcemap: false, + chunkSizeWarningLimit: 900, + }, +}); diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..0ea95e4 --- /dev/null +++ b/web/index.html @@ -0,0 +1,20 @@ + + + + + + + + + + + + + Study Desk + + + +
+ + + diff --git a/web/public/icon-180.png b/web/public/icon-180.png new file mode 100644 index 0000000..92b493d Binary files /dev/null and b/web/public/icon-180.png differ diff --git a/web/public/icon-192.png b/web/public/icon-192.png new file mode 100644 index 0000000..88c8e74 Binary files /dev/null and b/web/public/icon-192.png differ diff --git a/web/public/icon-512.png b/web/public/icon-512.png new file mode 100644 index 0000000..56ce4d8 Binary files /dev/null and b/web/public/icon-512.png differ diff --git a/web/public/icon.svg b/web/public/icon.svg new file mode 100644 index 0000000..b8fdb4d --- /dev/null +++ b/web/public/icon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/web/public/manifest.webmanifest b/web/public/manifest.webmanifest new file mode 100644 index 0000000..170f661 --- /dev/null +++ b/web/public/manifest.webmanifest @@ -0,0 +1,15 @@ +{ + "name": "Study Desk", + "short_name": "Study Desk", + "description": "Quizzes, spaced-repetition flashcards and study materials.", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#FBFAF7", + "theme_color": "#1B1A17", + "icons": [ + { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }, + { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any maskable" }, + { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable" } + ] +} diff --git a/web/public/robots.txt b/web/public/robots.txt new file mode 100644 index 0000000..1f53798 --- /dev/null +++ b/web/public/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Disallow: / diff --git a/web/public/sw.js b/web/public/sw.js new file mode 100644 index 0000000..cdfaaa3 --- /dev/null +++ b/web/public/sw.js @@ -0,0 +1,50 @@ +/* Study Desk service worker: makes the app installable and keeps the shell available offline. + * API calls are never cached, so study data is always live. */ +const CACHE = 'studydesk-shell-v1'; + +self.addEventListener('install', (event) => { + event.waitUntil(caches.open(CACHE).then((c) => c.addAll(['/', '/icon.svg', '/manifest.webmanifest'])).then(() => self.skipWaiting())); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches + .keys() + .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k)))) + .then(() => self.clients.claim()), + ); +}); + +self.addEventListener('fetch', (event) => { + const req = event.request; + if (req.method !== 'GET') return; + const url = new URL(req.url); + if (url.origin !== self.location.origin || url.pathname.startsWith('/api/') || url.pathname.startsWith('/media/')) return; + + // Hashed build assets never change: serve from cache, fill on first use. + if (url.pathname.startsWith('/assets/')) { + event.respondWith( + caches.match(req).then( + (hit) => + hit || + fetch(req).then((res) => { + if (res.ok) caches.open(CACHE).then((c) => c.put(req, res.clone())); + return res.clone(); + }), + ), + ); + return; + } + + // Pages: always try the network so updates arrive, fall back to the cached shell offline. + if (req.mode === 'navigate') { + event.respondWith( + fetch(req) + .then((res) => { + if (res.ok) caches.open(CACHE).then((c) => c.put('/', res.clone())); + return res.clone(); + }) + .catch(() => caches.match('/').then((hit) => hit || new Response('Study Desk is offline.', { status: 503, headers: { 'Content-Type': 'text/plain' } }))), + ); + } +}); diff --git a/web/public/theme.js b/web/public/theme.js new file mode 100644 index 0000000..edbdabb --- /dev/null +++ b/web/public/theme.js @@ -0,0 +1,10 @@ +// Applies the saved theme before first paint (kept as a file so the CSP can stay script-src 'self'). +(function () { + try { + var saved = localStorage.getItem('sd.theme') || 'system'; + var dark = saved === 'dark' || (saved === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches); + document.documentElement.dataset.theme = dark ? 'dark' : 'light'; + } catch (e) { + document.documentElement.dataset.theme = 'light'; + } +})(); diff --git a/web/src/app/Shell.tsx b/web/src/app/Shell.tsx new file mode 100644 index 0000000..13aee3a --- /dev/null +++ b/web/src/app/Shell.tsx @@ -0,0 +1,615 @@ +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { BookOpen, ChartColumn, FileText, GraduationCap, Layers, Library, LogOut, Monitor, Moon, MoreHorizontal, NotebookPen, Plus, Search, Settings, Sparkles, Sun, X } from 'lucide-react'; +import { lazy, Suspense, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; +import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router'; +import { toast } from 'sonner'; +import { CLASS_COLORS, type ClassColor } from '@shared/content'; +import { api, errorMessage } from '@/lib/api'; +import { assistant, useAssistantState } from '@/lib/assistantStore'; +import { qk, useClasses, useOverview, useRefresh } from '@/lib/queries'; +import type { ClassInfo, SearchHit } from '@/lib/types'; +import { cx, modKey, useDebounced, useHotkeys, useIsDesktop, useTheme, type ThemeChoice } from '@/lib/util'; +import { Brand } from '@/pages/Auth'; +import { Button, ClassDot, Dialog, Field, IconButton, Input, Kbd, Menu, MenuItem, MenuLabel, MenuSeparator, Spinner, Textarea } from '@/ui'; + +const AssistantPanel = lazy(() => import('@/features/AssistantPanel')); + +/* ------------------------------ class dialog ------------------------------ */ + +export function ClassDialog({ open, onOpenChange, existing }: { open: boolean; onOpenChange: (o: boolean) => void; existing?: ClassInfo }) { + const refresh = useRefresh(); + const navigate = useNavigate(); + const [name, setName] = useState(''); + const [code, setCode] = useState(''); + const [description, setDescription] = useState(''); + const [color, setColor] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + if (!open) return; + setName(existing?.name ?? ''); + setCode(existing?.code ?? ''); + setDescription(existing?.description ?? ''); + setColor(existing?.color ?? null); + }, [open, existing]); + + const save = async () => { + if (!name.trim()) return; + setBusy(true); + try { + if (existing) { + await api.patch(`/api/classes/${existing.id}`, { name, code, description, color: color ?? existing.color }); + toast.success('Class updated'); + } else { + const res = await api.post<{ class: ClassInfo }>('/api/classes', { name, code, description, color: color ?? undefined }); + navigate(`/classes/${res.class.id}`); + } + await refresh(); + onOpenChange(false); + } catch (e) { + toast.error(errorMessage(e)); + } finally { + setBusy(false); + } + }; + + return ( + + + + + } + > +
{ + e.preventDefault(); + void save(); + }} + > +
+ + setName(e.target.value)} placeholder="Pharmacology" maxLength={120} /> + + + setCode(e.target.value)} placeholder="NUR 356" maxLength={40} /> + +
+ +