diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c4c451c --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +NEXT_PUBLIC_SUPABASE_URL= +NEXT_PUBLIC_SUPABASE_ANON_KEY= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..694f9bf --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm run lint + - run: npm run typecheck + - run: npm test + - run: npm run build + env: + NEXT_PUBLIC_SUPABASE_URL: https://example.supabase.co + NEXT_PUBLIC_SUPABASE_ANON_KEY: ci-placeholder diff --git a/.npmrc b/.npmrc deleted file mode 100644 index 521a9f7..0000000 --- a/.npmrc +++ /dev/null @@ -1 +0,0 @@ -legacy-peer-deps=true diff --git a/README.md b/README.md index c4aaf53..56ba971 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,65 @@ -Features: 1] Task Manager:user can add , edit , delete ,complete task; - 2] Notes Section : Use Case: Add quick notes or class summaries.; - 3] Pomodoro Timer Use Case: 25 min work / 5 min break timer to boost focus ; - 4] GPA Calculator : Use Case: Input subjects, grades → calculate GPA ; - 5] Motivational Quote of the Day : Use Case: Keep the user motivated \ No newline at end of file +# StudyVerse + +A study companion for students: dashboard, tasks, notes, pomodoro timer, weekly planner, CGPA calculator and a daily quote. +Built with Next.js 16 (App Router), React 19, Tailwind CSS 4 and Supabase (auth + Postgres). + +Live: https://study-verse-ten.vercel.app + +## Setup + +1. `npm install` +2. Copy `.env.example` to `.env.local` and fill in your Supabase project URL and anon key + (Supabase Dashboard → Project Settings → API). +3. In the Supabase Dashboard → SQL Editor, run the migrations in order: + - `supabase/migrations/0001_schema_and_rls.sql` — tables, row-level security, seeded quotes + - `supabase/migrations/0002_v2.sql` — pomodoro sessions, planner blocks, saved CGPA, note tags + Both are idempotent (safe to re-run). +4. Optional, for "Continue with Google": Supabase Dashboard → Authentication → Providers → Google + (needs a Google Cloud OAuth client ID and secret), then add `https:///auth/callback` + and `http://localhost:3000/auth/callback` under Authentication → URL Configuration → Redirect URLs. +5. `npm run dev` + +## Scripts + +| Command | What it does | +| ------------------- | ---------------------------------------------- | +| `npm run dev` | Dev server | +| `npm run build` | Production build | +| `npm run lint` | ESLint (Next core-web-vitals + TypeScript) | +| `npm run typecheck` | `tsc --noEmit` | +| `npm test` | Node's built-in test runner (`lib/*.test.mjs`) | + +CI runs all of the above on every pull request (`.github/workflows/ci.yml`). + +## Layout + +``` +app/ + layout.tsx fonts, theme bootstrap script, global CSS + globals.css "Paper bento" tokens (light-dark()), component classes (.btn, .card, .tile, .chip …) + (public)/ home, login, register, forgot-password, reset-password — top nav + (app)/ signed-in shell: sidebar on desktop, tab bar on mobile + dashboard/ stats, up-next tasks, week chart, today's plan, mini timer, quote, recent notes + task/ Server Component + Server Actions; ?filter=soon|overdue|done + note/ search (?q=), tags (?tag=), markdown preview + pomodoro/ timer hook in lib/use-pomodoro.ts; settings in localStorage; sessions saved to Supabase + planner/ weekly timetable (Mon–Sun, 06:00–23:00) + gpa/ 10-point or 4.0 scale, saved per user + quotes/ random quote, server-rendered + auth/callback/ OAuth + email-link code exchange + components/ Sidebar, TopNav, ThemeToggle, SubmitButton, GoogleButton +lib/ gpa.mjs, streak.mjs (with tests), time.ts, use-pomodoro.ts +proxy.ts redirects signed-out visitors away from every (app) route +utils/supabase/ browser + server Supabase clients +supabase/migrations/ SQL to run in the Supabase dashboard +``` + +## Theme + +Light and dark share one token set via CSS `light-dark()`. The toggle writes `theme` to `localStorage` +and sets `data-theme` on ``; with no saved choice the system preference applies. + +## Deploy + +Vercel auto-detects Next.js. Set `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_ANON_KEY` +in Project → Settings → Environment Variables. diff --git a/app/(app)/dashboard/greeting.tsx b/app/(app)/dashboard/greeting.tsx new file mode 100644 index 0000000..0109a0f --- /dev/null +++ b/app/(app)/dashboard/greeting.tsx @@ -0,0 +1,24 @@ +'use client' + +import { useSyncExternalStore } from 'react' +import { localHour, localDateLabel } from '@/lib/time' + +const noop = () => () => {} +const hourWord = () => { + const h = localHour() + return h < 5 ? 'Up late' : h < 12 ? 'Good morning' : h < 17 ? 'Good afternoon' : 'Good evening' +} + +// Time-of-day text comes from the viewer's clock, not the server's. +export default function Greeting({ name }: { name: string }) { + const word = useSyncExternalStore(noop, hourWord, () => 'Hello') + const date = useSyncExternalStore(noop, localDateLabel, () => '') + return ( +
+

{date}

+

+ {word}, {name} +

+
+ ) +} diff --git a/app/(app)/dashboard/mini-pomodoro.tsx b/app/(app)/dashboard/mini-pomodoro.tsx new file mode 100644 index 0000000..fadda48 --- /dev/null +++ b/app/(app)/dashboard/mini-pomodoro.tsx @@ -0,0 +1,39 @@ +'use client' + +import Link from 'next/link' +import { PlayIcon, PauseIcon, ArrowUpRightIcon } from '@phosphor-icons/react/dist/ssr' +import { Rings } from '@/app/components/motion' +import { usePomodoro, formatTime, PHASE_LABEL } from '@/lib/use-pomodoro' +import { logSession } from '@/app/(app)/pomodoro/actions' +import { celebrate } from '@/lib/celebrate' + +export default function MiniPomodoro() { + const t = usePomodoro((phase, minutes) => { + if (phase !== 'work') return + logSession(minutes, 'work') + celebrate(undefined, true) + }) + return ( +
+
+

Focus timer

+ Open
+
+
+ + {formatTime(t.secondsLeft)} + +
+
+

{PHASE_LABEL[t.phase]}{t.running ? ', running' : ''}

+ {t.running ? ( + + ) : ( + + )} +
+
+
+ ) +} diff --git a/app/(app)/dashboard/page.tsx b/app/(app)/dashboard/page.tsx new file mode 100644 index 0000000..f2b166f --- /dev/null +++ b/app/(app)/dashboard/page.tsx @@ -0,0 +1,56 @@ +import { redirect } from 'next/navigation' +import { createClient } from '@/utils/supabase/server' +import type { Task, Quote, Note, PomodoroSession, PlannerBlock, GpaProfile } from '@/types/db' +import { nowIso, dayNumber, daysAgoIso, utcWeekday, startOfUtcDayIso, endOfUtcDayIso, startOfUtcWeekIso } from '@/lib/time' +import { streakDays } from '@/lib/streak.mjs' +import { gpa } from '@/lib/gpa.mjs' +import DashboardView from './view' + +export const metadata = { title: 'Today' } + +// Tolerates tables that don't exist yet (before 0002_v2.sql runs): an error just means "no rows". +const rows = async (q: PromiseLike<{ data: unknown }>) => ((await q).data ?? []) as T[] + +export default async function DashboardPage() { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + if (!user) redirect('/login?next=/dashboard') + const uid = user.id + const meta = user.user_metadata ?? {} + const name = meta.username || meta.full_name?.split(' ')[0] || meta.name?.split(' ')[0] || user.email?.split('@')[0] || 'there' + const today = utcWeekday() + + const [open, overdue, dueToday, quotes, sessions, blocks, notes, profile] = await Promise.all([ + rows(supabase.from('tasks').select('*').eq('user_id', uid).eq('completed', false).order('due_date', { ascending: true, nullsFirst: false }).limit(6)), + supabase.from('tasks').select('id', { count: 'exact', head: true }).eq('user_id', uid).eq('completed', false).lt('due_date', nowIso()), + rows>(supabase.from('tasks').select('completed').eq('user_id', uid).gte('due_date', startOfUtcDayIso()).lt('due_date', endOfUtcDayIso())), + rows(supabase.from('quotes').select('*').eq('category', 'study').order('text')), + rows(supabase.from('pomodoro_sessions').select('*').eq('user_id', uid).eq('kind', 'work').gte('started_at', daysAgoIso(60))), + rows(supabase.from('planner_blocks').select('*').eq('user_id', uid).eq('weekday', today).order('start_min')), + rows(supabase.from('notes').select('*').eq('user_id', uid).order('updated_at', { ascending: false }).limit(3)), + supabase.from('gpa_profiles').select('*').eq('user_id', uid).maybeSingle(), + ]) + + const dayStart = startOfUtcDayIso() + const weekStart = startOfUtcWeekIso() + const week = Array(7).fill(0) + for (const s of sessions) if (s.started_at >= weekStart) week[utcWeekday(new Date(s.started_at))] += s.minutes + const gp = (profile.data ?? null) as GpaProfile | null + + return ( + s.started_at >= dayStart).reduce((sum, s) => sum + s.minutes, 0)} + dueToday={dueToday} + open={open} + streak={streakDays(sessions.map((s) => s.started_at))} + overdueCount={overdue.count ?? 0} + cgpa={gp ? gpa(gp.semesters.flat(), gp.scale) : null} + week={week} + today={today} + blocks={blocks} + quote={quotes.length ? quotes[dayNumber() % quotes.length] : null} + notes={notes} + /> + ) +} diff --git a/app/(app)/dashboard/today-rings.tsx b/app/(app)/dashboard/today-rings.tsx new file mode 100644 index 0000000..8b7b7a3 --- /dev/null +++ b/app/(app)/dashboard/today-rings.tsx @@ -0,0 +1,41 @@ +'use client' + +import { CountUp, Rings } from '@/app/components/motion' +import { useSettings } from '@/lib/use-pomodoro' +import { fmtMinutes } from '@/lib/time' + +/** The day at a glance: focus minutes against the daily goal, and today's due tasks done. */ +export default function TodayRings({ focus, due, done }: { focus: number; due: number; done: number }) { + const { goal } = useSettings() + return ( +
+ + + +
+
+
+
min of your {fmtMinutes(goal)} goal
+
+
+
+
+ {due ? ( + <> of {due} done + ) : ( + Nothing due today. Enjoy it. + )} +
+
+
+
+ ) +} diff --git a/app/(app)/dashboard/up-next.tsx b/app/(app)/dashboard/up-next.tsx new file mode 100644 index 0000000..921e5d5 --- /dev/null +++ b/app/(app)/dashboard/up-next.tsx @@ -0,0 +1,24 @@ +'use client' + +import { AnimatePresence, motion } from 'motion/react' +import type { Task } from '@/types/db' +import { SPRING } from '@/app/components/motion' +import { TaskRow, useTaskMutations } from '@/app/(app)/task/task-list' + +// Ticking a task off here removes it from the list with a short exit; the server catches up behind it. +export default function UpNext({ tasks }: { tasks: Task[] }) { + const { items, toggle } = useTaskMutations(tasks) + const open = items.filter((t) => !t.completed) + if (open.length === 0) return

All done. Add a task when something comes up.

+ return ( +
    + + {open.map((t) => ( + + toggle(t)} compact /> + + ))} + +
+ ) +} diff --git a/app/(app)/dashboard/view.tsx b/app/(app)/dashboard/view.tsx new file mode 100644 index 0000000..bb183f9 --- /dev/null +++ b/app/(app)/dashboard/view.tsx @@ -0,0 +1,138 @@ +import Link from 'next/link' +import type { CSSProperties } from 'react' +import { ArrowRightIcon, PlusIcon } from '@phosphor-icons/react/dist/ssr' +import type { Task, Quote, Note, PlannerBlock } from '@/types/db' +import { fmtMinutes, hhmm } from '@/lib/time' +import { CountUp } from '@/app/components/motion' +import { CAT_TONE } from '@/lib/categories' +import Greeting from './greeting' +import TodayRings from './today-rings' +import MiniPomodoro from './mini-pomodoro' +import WeekChart from './week-chart' +import UpNext from './up-next' + +const delay = (i: number) => ({ '--i': i }) as CSSProperties +// Markdown symbols read as noise in a two-line preview. +const plain = (md: string) => md.replace(/^\s*(#{1,6}|[-+*>]|\d+\.)\s+/gm, '').replace(/[*_`~]/g, '') +const NOTE_TONES = ['bg-yellow', 'bg-pink', 'bg-mint'] +const NOTE_TILT = ['-1.5deg', '1deg', '-0.5deg'] + +export type DashboardData = { + name: string + focusToday: number + dueToday: { completed: boolean }[] + open: Task[] + streak: number + overdueCount: number + cgpa: number | null + week: number[] + today: number + blocks: PlannerBlock[] + quote: Quote | null + notes: Note[] +} + +/** Pure view of the Today screen; page.tsx does the fetching. */ +export default function DashboardView({ name, focusToday, dueToday, open, streak, overdueCount, cgpa, week, today, blocks, quote, notes }: DashboardData) { + return ( +
+
+ +
+ +
+
+

Today so far

+ t.completed).length} /> +
+ +
+ +
+
+ +

Focus streak

{streak === 1 ? 'day' : 'days'}

+
+ + +

Overdue

{overdueCount === 1 ? 'task' : 'tasks'}

+ + + +

CGPA

{cgpa === null ? Not saved yet : }

+ +
+ +
+
+

Up next

+ All tasks
+ +
+ +
+
+

Focus this week

+ {fmtMinutes(week.reduce((a, b) => a + b, 0))} +
+ +
+ +
+
+

Today's plan

+ Planner
+ {blocks.length === 0 ? ( +
+ No study blocks today. +
+ ) : ( +
    + {blocks.map((b) => ( +
  1. + {hhmm(b.start_min)} + {b.subject} +
  2. + ))} +
+ )} +
+ +
+ {quote ? ( + <> +

“{quote.text}”

+ {quote.author &&

{quote.author}

} + + ) : ( +

Quotes will show up here.

+ )} +
+ +
+
+

Recent notes

+ All notes
+ {notes.length === 0 ? ( + + Write your first note + + ) : ( +
+ {notes.map((n, i) => ( + +

{n.title}

+

{plain(n.content)}

+ + ))} +
+ )} +
+
+
+ ) +} diff --git a/app/(app)/dashboard/week-chart.tsx b/app/(app)/dashboard/week-chart.tsx new file mode 100644 index 0000000..82a4458 --- /dev/null +++ b/app/(app)/dashboard/week-chart.tsx @@ -0,0 +1,26 @@ +import type { CSSProperties } from 'react' + +const DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] + +// Seven chunky bars of focus minutes, Monday first. Pure CSS: bars spring up on first paint. +export default function WeekChart({ minutes, todayIndex }: { minutes: number[]; todayIndex: number }) { + const max = Math.max(60, ...minutes) + const summary = DAYS.map((d, i) => `${d} ${minutes[i]} minutes`).join(', ') + return ( +
+
+ {minutes.map((m, i) => ( +
+
+
+ ))} +
+ +
+ ) +} diff --git a/app/(app)/gpa/actions.ts b/app/(app)/gpa/actions.ts new file mode 100644 index 0000000..0ae4ab5 --- /dev/null +++ b/app/(app)/gpa/actions.ts @@ -0,0 +1,19 @@ +'use server' + +import { revalidatePath } from 'next/cache' +import { requireUser } from '@/utils/supabase/server' +import { SCALES } from '@/lib/gpa.mjs' +import type { Course } from '@/types/db' + +export async function saveGpa(scale: string, semesters: Course[][]) { + if (!(scale in SCALES)) return { error: 'Unknown grade scale.' } + const clean = semesters + .slice(0, 20) + .map((sem) => sem.slice(0, 30).map((c) => ({ credits: String(c.credits ?? ''), grade: String(c.grade ?? '') }))) + const { supabase, uid } = await requireUser() + const { error } = await supabase + .from('gpa_profiles') + .upsert({ user_id: uid, scale, semesters: clean, updated_at: new Date().toISOString() }) + if (error) return { error: error.message } + revalidatePath('/dashboard') +} diff --git a/app/(app)/gpa/calculator.tsx b/app/(app)/gpa/calculator.tsx new file mode 100644 index 0000000..a3ed137 --- /dev/null +++ b/app/(app)/gpa/calculator.tsx @@ -0,0 +1,105 @@ +'use client' + +import { useState, useTransition } from 'react' +import { AnimatePresence, motion } from 'motion/react' +import { PlusIcon, TrashIcon, FloppyDiskIcon, CheckIcon } from '@phosphor-icons/react/dist/ssr' +import { gpa, SCALES } from '@/lib/gpa.mjs' +import type { Course } from '@/types/db' +import { CountUp, Rings, Segmented, SPRING } from '@/app/components/motion' +import { saveGpa } from './actions' +import { celebrate } from '@/lib/celebrate' + +type Scale = keyof typeof SCALES + +const blank = (): Course => ({ credits: '', grade: '' }) +const MAX: Record = { '10': 10, '4': 4 } + +export default function Calculator({ initialScale, initialSemesters }: { initialScale: Scale; initialSemesters: Course[][] }) { + const [scale, setScale] = useState(initialScale) + const [semesters, setSemesters] = useState(initialSemesters.length ? initialSemesters : [[blank()]]) + const [status, setStatus] = useState<{ ok: boolean; text: string } | null>(null) + const [pending, startTransition] = useTransition() + const grades = Object.keys(SCALES[scale]) + + const edit = (next: (s: Course[][]) => Course[][]) => { setStatus(null); setSemesters(next) } + const update = (si: number, ci: number, field: keyof Course, value: string) => + edit((s) => s.map((sem, i) => (i !== si ? sem : sem.map((c, j) => (j !== ci ? c : { ...c, [field]: value }))))) + const addCourse = (si: number) => edit((s) => s.map((sem, i) => (i !== si ? sem : [...sem, blank()]))) + const removeCourse = (si: number, ci: number) => + edit((s) => s.map((sem, i) => (i !== si ? sem : sem.filter((_, j) => j !== ci))).filter((sem) => sem.length)) + const switchScale = (next: Scale) => { + setScale(next) + const valid = new Set(Object.keys(SCALES[next])) + edit((s) => s.map((sem) => sem.map((c) => (valid.has(c.grade) ? c : { ...c, grade: '' })))) + } + const save = () => + startTransition(async () => { + const res = await saveGpa(scale, semesters) + if (res?.error) return setStatus({ ok: false, text: `${res.error}. Try again.` }) + setStatus({ ok: true, text: 'Saved' }) + celebrate({ x: 0.8, y: 0.5 }) + }) + + const cgpa = gpa(semesters.flat(), scale) + const credits = semesters.flat().reduce((sum, c) => sum + (c.grade && c.credits ? Number(c.credits) : 0), 0) + + return ( +
+
+ + {semesters.map((courses, si) => { + const sgpa = gpa(courses, scale) + return ( + +
+

Semester {si + 1}

+ {sgpa !== null && SGPA {sgpa.toFixed(2)}} +
+ + {courses.map((course, ci) => ( +
+ + + +
+ ))} + +
+ ) + })} +
+ +
+ + +
+ ) +} diff --git a/app/(app)/gpa/page.tsx b/app/(app)/gpa/page.tsx new file mode 100644 index 0000000..5691683 --- /dev/null +++ b/app/(app)/gpa/page.tsx @@ -0,0 +1,26 @@ +import { redirect } from 'next/navigation' +import { createClient } from '@/utils/supabase/server' +import type { GpaProfile } from '@/types/db' +import Calculator from './calculator' + +export const metadata = { title: 'CGPA' } + +export default async function GpaPage() { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + if (!user) redirect('/login?next=/gpa') + + // Missing table (before 0002_v2.sql) just means "nothing saved yet". + const { data } = await supabase.from('gpa_profiles').select('*').eq('user_id', user.id).maybeSingle() + const profile = (data ?? null) as GpaProfile | null + + return ( +
+
+

Your CGPA

+

Credit-weighted across every semester.

+
+ +
+ ) +} diff --git a/app/(app)/layout.tsx b/app/(app)/layout.tsx new file mode 100644 index 0000000..259da74 --- /dev/null +++ b/app/(app)/layout.tsx @@ -0,0 +1,19 @@ +import type { ReactNode } from 'react' +import { redirect } from 'next/navigation' +import { createClient } from '@/utils/supabase/server' +import Sidebar from '@/app/components/Sidebar' + +export default async function AppLayout({ children }: { children: ReactNode }) { + const supabase = await createClient() + const { data: { user } } = await supabase.auth.getUser() + if (!user) redirect('/login') + const meta = user.user_metadata ?? {} + const name = meta.username || meta.full_name?.split(' ')[0] || meta.name?.split(' ')[0] || user.email?.split('@')[0] || 'there' + + return ( +
+ +
{children}
+
+ ) +} diff --git a/app/(app)/note/actions.ts b/app/(app)/note/actions.ts new file mode 100644 index 0000000..5413d3f --- /dev/null +++ b/app/(app)/note/actions.ts @@ -0,0 +1,43 @@ +'use server' + +import { revalidatePath } from 'next/cache' +import { requireUser } from '@/utils/supabase/server' + +export type Result = { error?: string } | undefined + +const text = (fd: FormData, key: string) => String(fd.get(key) ?? '').trim() +const tags = (fd: FormData) => + [...new Set(text(fd, 'tags').split(',').map((t) => t.trim().toLowerCase()).filter(Boolean))].slice(0, 10) + +function parse(fd: FormData) { + const fields = { title: text(fd, 'title'), content: text(fd, 'content'), tags: tags(fd) } + if (!fields.title || !fields.content) return { error: 'Title and content are required.' } + return { fields } +} + +async function run( + mutate: (ctx: Awaited>) => PromiseLike<{ error: { message: string } | null }>, +): Promise { + const { error } = await mutate(await requireUser()) + if (error) return { error: error.message } + revalidatePath('/note') + revalidatePath('/dashboard') +} + +export async function addNote(fd: FormData): Promise { + const p = parse(fd) + if ('error' in p) return p + return run(({ supabase, uid }) => supabase.from('notes').insert({ ...p.fields, user_id: uid })) +} + +export async function updateNote(id: string, fd: FormData): Promise { + const p = parse(fd) + if ('error' in p) return p + return run(({ supabase, uid }) => + supabase.from('notes').update({ ...p.fields, updated_at: new Date().toISOString() }).eq('id', id).eq('user_id', uid), + ) +} + +export async function deleteNote(id: string): Promise { + return run(({ supabase, uid }) => supabase.from('notes').delete().eq('id', id).eq('user_id', uid)) +} diff --git a/app/(app)/note/note-list.tsx b/app/(app)/note/note-list.tsx new file mode 100644 index 0000000..7efdffe --- /dev/null +++ b/app/(app)/note/note-list.tsx @@ -0,0 +1,147 @@ +'use client' + +import { useOptimistic, useState, useTransition } from 'react' +import Link from 'next/link' +import ReactMarkdown from 'react-markdown' +import { AnimatePresence, motion } from 'motion/react' +import { PencilSimpleIcon, TrashIcon, PlusIcon, EyeIcon, PencilLineIcon } from '@phosphor-icons/react/dist/ssr' +import type { Note } from '@/types/db' +import SubmitButton from '@/app/components/SubmitButton' +import { SPRING } from '@/app/components/motion' +import { addNote, updateNote, deleteNote, type Result } from './actions' + +type Action = (fd: FormData) => Promise + +// Each note gets a stable sticky-note colour, tilt and tape from its id. +const STICKY = ['bg-yellow', 'bg-pink', 'bg-mint', 'bg-sky', 'bg-orange'] +const TAPE = ['var(--color-sky)', 'var(--color-yellow)', 'var(--color-pink)', 'var(--color-mint)'] +const TILT = ['-2deg', '1.5deg', '-1deg', '2deg', '0.5deg'] +const hash = (id: string) => [...id].reduce((a, c) => (a * 31 + c.charCodeAt(0)) >>> 0, 7) + +function NoteForm({ note, action, onDone }: { note?: Note; action: Action; onDone: () => void }) { + const [error, setError] = useState('') + const [content, setContent] = useState(note?.content ?? '') + const [preview, setPreview] = useState(false) + const id = note?.id ?? 'new' + + const submit = async (fd: FormData) => { + fd.set('content', content) + const res = await action(fd) + if (res?.error) return setError(res.error) + setError('') + onDone() + } + + return ( +
+ {error &&

{error}

} +
+ + +
+
+
+ + +
+ {preview ? ( +
{content ? {content} : Nothing to preview yet.}
+ ) : ( +