Compare commits

...
61 Commits
Author SHA1 Message Date
ginnoir 51c8d3c92d chore: release v0.5.1
Release / build-and-push (push) Has been cancelled
2026-06-03 19:55:57 -05:00
ginnoir 62c3d33350 fix: dashboard switcher, platform-aware search shortcut, mobile search, static topbar
- Always show dashboard tab strip + add button (was gated behind length > 1)
- Search shortcut now shows Ctrl+K on Windows/Linux, ⌘K on Mac
- Add icon-only search button in topbar for mobile viewports
- Lock html/body overflow and use 100dvh to prevent topbar scrolling off-screen on mobile
2026-06-03 19:55:00 -05:00
ginnoir 2408d37f8e chore: release v0.5.0
Release / build-and-push (push) Has been cancelled
2026-06-03 19:20:37 -05:00
ginnoir f47c1c3a23 fix: replace settings mobile tabs with 2-col grid and remove fab 2026-06-03 19:17:17 -05:00
ginnoir 6e92648a41 feat: mobile experience overhaul — touch targets, calendar mobile layout, swipe gestures 2026-06-03 18:50:15 -05:00
ginnoir 6802ae08db fix: db:seed script points to seed.mjs not nonexistent seed.ts 2026-06-03 16:19:29 -05:00
ginnoir b935ff209c chore: release v0.4.10
Release / build-and-push (push) Has been cancelled
2026-06-03 16:16:01 -05:00
ginnoir 3fb5ddc5dd chore: upgrade node 22 to 24 lts 2026-06-03 16:15:00 -05:00
ginnoir ca536b5c33 chore: release v0.4.9
Release / build-and-push (push) Has been cancelled
2026-06-03 16:00:38 -05:00
ginnoir ec2f3930ad feat: proper logo, favicon, and pwa icons
- replace placeholder house svg with clean geometric house mark
  on indigo-700 (#4338CA) — roof triangle, body, door cutout
- add favicon.svg with prefers-color-scheme dark variant
- add icon-16/32 sizes; regenerate all pngs from svg via sharp
- update BrandMark component to use inline svg house instead of 'f'
- wire favicon + sized pngs into layout metadata
- fix middleware to allow icon/manifest/favicon paths without auth
  (android launcher fetches icons in a cookieless system context)
- fix getCurrentSession() to redirect to /login instead of throwing
  when session cookie is stale/invalid
2026-06-03 15:59:34 -05:00
ginnoir 10cad3df17 chore: release v0.4.8
Release / build-and-push (push) Has been cancelled
2026-06-02 20:26:57 -05:00
ginnoir 77db935329 chore: register 0018_container_images in drizzle migration journal 2026-06-02 20:19:57 -05:00
ginnoir c6a34f7471 feat: share links visible on plants/containers; container image gallery
- Fix ShareButton silently swallowing errors from createShareLink; now
  shows inline error text so failures are visible to the user
- Add getShareLinksForEntity server action and EntityShareLink type to
  _core/share.ts
- Add ShareLinkList component — renders active share links per entity
  with per-row Revoke; renders nothing when empty
- Wire ShareLinkList into plant and container detail pages (loaded
  server-side in parallel with the entity fetch)
- Add images jsonb column to garden_containers schema + migration 0018
- Add addContainerImage / removeContainerImage / setContainerPrimaryImage
  server actions mirroring the plant image pattern (10-image cap, first
  upload auto-sets cover)
- Update ContainerDetailDto, listContainers, getContainer to include images
- Rewrite ContainerDetail with Info/Gallery tabs; Gallery tab mirrors
  plant gallery (3-col grid, star/X overlays, upload button, counter)
- Update ContainerShareData and container renderSharedView to show cover
  image hero and secondary image grid on public share pages
2026-06-02 20:15:29 -05:00
ginnoir 076e35aced docs: add contributing guide, env reference, and operations runbook 2026-06-02 19:53:18 -05:00
ginnoir 8bf00c326d docs: update decisions index and task index for garden module and adr backfill
Populates the decisions index with the two existing ADRs (list SSE/notify,
release workflow). Adds task 09 to the phase 1 list and adds the phase 8
garden module task entries to the task index.
2026-06-02 19:52:55 -05:00
ginnoir 6a1ec8bb7b docs: add professional readme with full feature coverage and release pipeline hook
Replaces the 8-line placeholder with a complete README covering all four
modules, platform capabilities, quick start, dev setup, configuration
reference, and deployment links. Badges use dynamic shields.io URLs so
version/CI status update automatically on each release.

Wires README review into the release pipeline via a release-it
before:git:release hook and a new item in the pre-deploy checklist.
2026-06-02 19:52:24 -05:00
ginnoir fe4673f1cd chore: replace personal domains and ips with generic placeholders 2026-06-02 19:33:49 -05:00
ginnoir 4ec1f34150 chore: gitignore maintainer deploy scripts, scrub personal domain from dev.mjs 2026-06-02 19:30:27 -05:00
ginnoir 7938425850 chore: gitignore maintainer-specific production deploy files
deploy/compose.yaml, deploy/Caddyfile, and deploy/Caddyfile.dev.snippet
contain homelab-specific config and are not useful as public templates.
Public-facing equivalents: compose.example.yaml and Caddyfile.snippet.
2026-06-02 19:22:31 -05:00
ginnoir 13d94b3751 chore(deploy): separate maintainer config from public deployment templates
- rename Caddyfile.snippet → Caddyfile (maintainer's full production file)
- restore Caddyfile.snippet as a minimal public reference (famapp blocks only)
- add compose.example.yaml: standalone famapp + authentik template for new
  deployers; compose.yaml remains the maintainer's homelab monolith
- update deploy/README.md: file table, setup steps referencing example files
- apply-compose.ps1: point Caddy push at deploy/Caddyfile (not snippet)
2026-06-02 19:19:27 -05:00
ginnoir aae3e30843 fix(deploy): separate reactive resume auth_secret from famapp
- rename AUTH_SECRET to RESUME_AUTH_SECRET in production .env and compose
  app service — famapp's AUTH_SECRET is now unambiguous
- remove orphaned stale AUTH_SECRET entry from .env
- apply-compose.ps1: pull + restart famapp immediately after pushing compose
  rather than waiting for watchtower; uses dc alias via bash -ic
- update .env.production.example to reflect corrected variable names
2026-06-02 19:12:34 -05:00
ginnoir 23a14e1650 chore: replace placeholder deploy config with actual production files
- deploy/compose.yaml: replace generated placeholder with actual monolith
  compose (Foundry, Caddy, media stack, famapp, Authentik, Watchtower, etc.)
- deploy/Caddyfile.snippet: replace with full production Caddyfile
- .env.production.example: update variable names to match production
  (famapp_MINIO_ROOT_USER/PASSWORD/BUCKET, CF_API_TOKEN, etc.)
- scripts/apply-compose.ps1: add -Compose/-Caddy flags; push Caddyfile
  and reload caddy in addition to compose restart
2026-06-02 19:03:53 -05:00
ginnoir cce3bac5b2 chore: repo cleanup and prod sync tooling
- Remove stale deploy/docker-entrypoint.sh (Dockerfile copies root version)
- Remove scripts/seed.ts (superseded by seed.mjs)
- Add src/app/error.tsx and global-error.tsx (untracked error boundaries)
- Gitignore deploy/.prod/ for synced production configs
- Add scripts/sync-prod.ps1 to pull compose/env/Caddyfile from valhalla
- Add scripts/apply-compose.ps1 to push compose changes and restart services
2026-06-02 18:51:59 -05:00
ginnoir 31c5805b34 chore: release v0.4.7 2026-06-02 18:30:48 -05:00
ginnoir 989bae8f1e feat(garden): add share button to plant and container detail views 2026-06-02 18:30:28 -05:00
ginnoir 090366422d chore: release v0.4.6
Release / build-and-push (push) Has been cancelled
2026-06-02 18:16:26 -05:00
ginnoir 4049a73c6b fix(garden): accept relative urls for plant image uploads
Zod v4 changed .url() to use the WHATWG URL spec, which rejects relative
paths like /api/uploads/... that our upload API returns. Relax image URL
validators to z.string().min(1) since these are internal paths.
2026-06-02 18:15:12 -05:00
ginnoir 272d3cbbe6 chore: release v0.4.5
Release / build-and-push (push) Has been cancelled
2026-06-02 04:27:39 -05:00
ginnoir b5a966e3a9 feat(bangs): add bang counter dashboard widget
Adds a new "bangs" module with a dashboard widget that tracks household
bang events. The widget shows the total count, a configurable recent-bang
list, and an "Add Bang" button that accepts a backdatable date.

On submission, a full celebration sequence fires: screen flash, widget
shake, count pop animation, synthesized firework sound (Web Audio API),
50 full-screen emoji particles via portal, canvas-confetti star bursts,
side cannons, and a timed sequence of 7 firework bursts.

- New bang_events table (migration 0017)
- canvas-confetti dependency for fireworks/confetti effects
- CSS keyframe animations: shake, countPop, emojiFloat
- Fixes pre-existing Drizzle snapshot chain collision (0007/0008)
- Adds OpenPlantBook env vars to compose.yaml
2026-06-02 04:26:22 -05:00
ginnoir 48063e4b7f chore: release v0.4.4
Release / build-and-push (push) Has been cancelled
2026-06-02 03:48:52 -05:00
ginnoir 6eab68560e fix(garden): remove trailing slashes from openplantbook api urls and update label
Trailing slashes on /plant/search/ and /plant/detail/ caused Django to
return an HTML redirect page instead of JSON. SDK uses no trailing slashes.

Also updates the helper text to reference OpenPlantBook instead of Perenual.
2026-06-02 03:48:38 -05:00
ginnoir 7d0f02996f chore: release v0.4.3
Release / build-and-push (push) Has been cancelled
2026-06-02 03:25:03 -05:00
ginnoir 32e97b0677 fix(garden): replace perenual with openplantbook for species lookup
Perenual's free tier does not serve care instructions. OpenPlantBook
provides watering, sunlight, and other care data at no cost.

- OAuth2 client_credentials token fetch with module-level cache
- Search via /api/v1/plant/search/, detail via /api/v1/plant/detail/{pid}/?include=care
- SpeciesSuggestion shape unchanged; no frontend or schema changes required
- Env vars: OPENPLANTBOOK_CLIENT_ID + OPENPLANTBOOK_CLIENT_SECRET (replaces PERENUAL_API_KEY)
2026-06-02 03:24:20 -05:00
ginnoir e0b423aad5 chore: remove dead code and unused dependencies
- Delete src/placeholder.ts (empty stub with no references)
- Remove zod-to-json-schema dep (not imported anywhere in src/)
- Remove @eslint/eslintrc devDep (project uses flat config with @eslint/js)
- Remove @types/react-grid-layout devDep (react-grid-layout v2 ships own types)
2026-06-02 02:37:56 -05:00
ginnoir 389ff6040b ci: cache next.js build output and parallelize checks with build 2026-06-02 02:05:34 -05:00
ginnoir 65d36bab4e fix: drive bottom nav from module registry so all modules appear on mobile
Release / build-and-push (push) Has been cancelled
The bottom nav was hardcoded; the sidebar already read from the module
registry. Converted BottomNav to a server component that calls
getRegistry() using the same pattern as Sidebar, so any module with a
nav field automatically populates both nav surfaces.

Bumps version to 0.4.2.
2026-06-02 01:55:36 -05:00
ginnoir 298e6b868d chore: register migration 0016 in drizzle journal
Release / build-and-push (push) Has been cancelled
2026-06-02 00:27:10 -05:00
ginnoir 6d45b7e836 chore: bump version to 0.4.0
Release / build-and-push (push) Has been cancelled
2026-06-02 00:00:03 -05:00
ginnoir 7f2c5a44dd feat: garden care reminder bodies, task sync, upload cleanup
- care reminders now fire with plant-specific body ("Time to water Pothos")
  via title/body columns on the reminders table (migration 0016)
- bi-directional task sync: checking off a garden-linked task list item
  creates a care log; logging care from garden marks the linked task done
  (list_items.metadata stores gardenPlantId + gardenCareType linkage)
- upload error response no longer leaks debug detail; error message
  corrected from "5 MB" to "100 MB"
2026-06-01 23:58:00 -05:00
ginnoir dd980c6932 fix: garden ui polish - form styles, back nav, species dropdown, upload limit 2026-06-01 23:38:52 -05:00
ginnoir 6b25d67537 feat: garden dashboard widgets and manifest completion (task 75)
- getCareDueWidgetRows query: schedule rows due within N days, filtered
  by optional container list, ordered by next_due_at
- getGardenOverviewStats query: plant/container/overdue counts + next care
- CareDueWidget: compact list sorted by urgency, inline log-care button,
  truncates at 10 rows with View all link
- GardenOverviewWidget: stat row (plants, containers, overdue) + next care
  line + garden link
- plant-widget.tsx server component: InlineLogButton uses form action to
  call logCare without client JS or navigation
- manifest: garden.care-due and garden.overview widgets registered;
  resolveConfigOptions returns container list for care-due config picker
- quickAdds: icons updated (leaf/box/droplets), log-care URL ->
  /garden?logCare=1
2026-06-01 22:43:53 -05:00
ginnoir 080d26816e test: add reproducer for garden dashboard widgets (task 75) 2026-06-01 22:41:25 -05:00
ginnoir 0b0deff700 feat: garden calendar + lists integrations (task 74)
- calendar-bridge.ts and lists-bridge.ts isolate cross-module deps
- scheduleOnCalendar action: creates event from care schedule with 30-min
  slot, title convention (Water/Fertilize/Repot/Prune/custom), reminder opt
- pushOverdueToTaskList action: inserts one task per overdue (plant+schedule)
  pair into the default task list, skips duplicate text entries
- CareScheduleEditor: per-row calendar 📅 button opens inline form with
  calendar select + optional reminder minutes + success link to /calendar
- Garden page header: PushOverdueButton with auto-dismissing feedback toast
2026-06-01 20:33:15 -05:00
ginnoir eabcebdb00 test: add reproducer for garden integrations (task 74) 2026-06-01 20:30:18 -05:00
ginnoir 0fef3d4ab6 feat: garden care tracking - logs, schedules, reminders (task 73)
- logCare/deleteCareLog actions with schedule update and reminder wiring
- upsertCareSchedule/deleteCareSchedule/toggleCareSchedule actions
- updateScheduleAfterCare helper cancels old reminder, schedules new one
- getCareLogs/getCareSchedules/getOverduePlants/getCareDueSoon queries
- CareLogForm, CareScheduleEditor, CareHistoryList components
- Plant detail Care tab wired up with schedule editor + log form + history
- Log plant care quick-add added to garden manifest
2026-06-01 20:23:43 -05:00
ginnoir fe282ba470 test: add reproducer for garden care tracking (task 73) 2026-06-01 20:23:30 -05:00
ginnoir f3e38c576c feat: garden plants crud (task 72)
- perenual species lookup with 24h db cache (api key optional)
- /api/garden/species-search route handler
- createPlant / updatePlant / deletePlant server actions
- addPlantImage / removePlantImage / setPrimaryImage actions (max 10)
- listPlants query grouped by container with last-watered subquery
- getPlant query with care log summary and active schedules
- plant-form client component with species autofill and image upload
- plant-list server component grouped by container with unassigned bucket
- plant-detail client component with info/gallery/care tabs
- species-search debounced combobox component
- /garden/plants/new, /[id], /[id]/edit pages
- garden.plant entity registered with search and share support
- /garden page updated to containers/plants tabs (default: containers)
2026-06-01 20:13:20 -05:00
ginnoir a86f5471ce test: add reproducer for garden plants crud (task 72) 2026-06-01 20:04:22 -05:00
ginnoir 5f6b756342 feat: garden containers crud (task 71)
- add listContainers/getContainer/searchContainers queries
- add createContainer/updateContainer/deleteContainer server actions with logActivity
- add ContainerList, ContainerDetail, ContainerForm client components
- add /garden, /garden/containers/[id], /garden/containers/new pages
- register garden.container entity with share + search in manifest
- add sprout icon to NavIcon registry
- add garden e2e test spec
2026-06-01 19:28:34 -05:00
ginnoir 2fd0677c5f feat: add garden module infrastructure (task 70)
- Add MinIO service to compose.yaml with named volume
- Add generic /api/uploads POST+GET route with auth, 5 MB, image/* guards
- Add src/lib/minio.ts singleton client with ensureBucket helper
- Add garden Drizzle schema: containers, plants, care_logs, care_schedules, species_cache
- Register garden module in src/modules/index.ts and src/lib/db.ts
- Apply migration 0015_garden_schema.sql
- Add MINIO_* and PERENUAL_API_KEY to .env.example
- Add task briefs 70-75 for the full garden feature arc
- Add uploads.spec.ts E2E test (RED → GREEN on route auth guard)
2026-06-01 19:23:19 -05:00
ginnoir 5dcd49d4c9 fix: remove duplicate changelog header and drop release-it header config 2026-06-01 18:47:47 -05:00
ginnoir 29795e0d51 chore: format pre-existing files missed by lint-staged 2026-06-01 18:46:53 -05:00
ginnoir 8921cb0444 chore: release v0.3.0
Release / build-and-push (push) Has been cancelled
2026-06-01 18:43:13 -05:00
ginnoir e3d2b5a364 chore: sync version to v0.2.0 and load .env for release scripts 2026-06-01 18:41:32 -05:00
ginnoir ed310d042f docs: add github_token to .env.example 2026-06-01 18:34:57 -05:00
ginnoir 30af9f63bf chore: add release workflow (commitlint, husky, lint-staged, release-it) 2026-06-01 18:33:37 -05:00
ginnoir e9bb2a5444 feat: expand theme system to 10 full-skin palettes with light and dark modes 2026-06-01 18:25:58 -05:00
ginnoir a95f10fcde fix: scope rail nav-label hiding to sidebar and fall back fab-only to sidebar on desktop 2026-06-01 18:00:49 -05:00
ginnoir b255aaeac1 fix: refresh server components after nav style change to fix broken layout 2026-06-01 17:53:21 -05:00
ginnoir 19308be768 feat: add dev startup script, fix push notifications, and scope test sends to device
- pnpm dev:local/dev:reset: orchestrate DB container, migrations, seed, and Next.js dev server in one command; Caddy snippet + docs for HTTPS via dev.ginnoir.com
- Fix dev login on HTTPS: set both authjs.session-token and __Secure-authjs.session-token so Auth.js finds the session regardless of cookie name resolution
- Suppress hydration mismatch on <html> caused by pre-paint script changing data-nav before React hydrates
- VAPID startup warning if keys not configured; remove dead NEXT_PUBLIC_VAPID_PUBLIC_KEY var
- PushOptIn: hydrate subscription state on mount; reuse existing subscription on iOS to avoid redundant prompts
- sendPushToEndpoint: new function to send to a single device endpoint
- sendTestNotification: scoped to the calling device's endpoint (ownership-verified) instead of all user subscriptions
2026-06-01 17:45:20 -05:00
ginnoirandClaude Opus 4.7 9612a54e52 Apply paper-and-ink design system across all surfaces
Release / build-and-push (push) Has been cancelled
Replaces the generic shadcn/ui gray theme + horizontal top-bar shell with
the paper-and-ink language from the Claude Design handoff bundle: warm
off-white paper, near-black ink, Source Serif 4 + Inter, hairline borders,
muted ink accents (clay/indigo/sage/plum/ochre) used functionally for
calendars and share scopes.

Theme switcher expanded from 2 dimensions (theme × mode) to 7: palette ×
mode × fontPair × density × dashLayout × calView × navStyle. All exposed
in Settings → Appearance and persisted on the users row. Pre-paint script
applies all four data-* attributes from localStorage so reload doesn't
flash.

App shell restructured to a CSS-grid driven by data-nav on <html>: sidebar
on desktop, bottom-nav + FAB under 760px. Four desktop nav modes wired
(sidebar/rail/top/fab-only). Topbar gets a search-→-CommandPalette button,
notification bell, "+ New" quick-add, avatar.

Dashboard, calendar, lists, notes, settings, login, public share viewer,
and quick-add sheet all reskinned. Dashboard editor gains a Preset menu
(classic/split/glance) that fills the layout from the registered widgets.
FullCalendar wrapped in .fc-skin and inherits all paper-and-ink tokens via
CSS variable overrides. Public share viewer (/s/<token>) rebuilt around
ShareFrame: expiration banner, brand strip, eyebrow chip, 38px serif
title, mini-day + mini-map cards, share-rows.

Schema: drops users.theme; adds theme_palette, theme_font_pair,
theme_density, theme_dash_layout, theme_cal_view, theme_nav_style with
defaults that match the design (clay / serif-sans / regular / classic /
month / rail-desktop). Migration 0014_paper_ink_theme.

Middleware sets x-pathname so the AppShell server component can render
bare for /s/* and /login without a route-group refactor.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 01:03:21 -05:00
174 changed files with 15979 additions and 1410 deletions
+15 -3
View File
@@ -1,5 +1,5 @@
# Public app URL (used for OIDC redirect URIs, share links, etc.)
NEXT_PUBLIC_APP_URL=https://fam.ginnoir.com
NEXT_PUBLIC_APP_URL=https://fam.yourdomain.com
# Postgres
DATABASE_URL=postgres://famapp:famapp@localhost:5432/famapp
@@ -15,14 +15,13 @@ DEV_LOGIN_NAME=Dev User
DEV_HOUSEHOLD_NAME=Home
# OIDC (Authentik)
AUTH_OIDC_ISSUER=https://auth.ginnoir.com/application/o/famapp/
AUTH_OIDC_ISSUER=https://auth.yourdomain.com/application/o/famapp/
AUTH_OIDC_CLIENT_ID=replace-me
AUTH_OIDC_CLIENT_SECRET=replace-me
# Web Push (generate with: pnpm vapid:generate — copy all three lines to .env)
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
NEXT_PUBLIC_VAPID_PUBLIC_KEY=
VAPID_SUBJECT=mailto:you@example.com
# ntfy (optional fallback channel; leave blank to disable)
@@ -31,3 +30,16 @@ NTFY_TOPIC=
# Logging
LOG_LEVEL=info
# GitHub (required for pnpm release — creates a GitHub Release)
GITHUB_TOKEN=
# MinIO object storage (used for plant/container image uploads)
MINIO_ENDPOINT=http://localhost:9000
MINIO_ROOT_USER=famapp
MINIO_ROOT_PASSWORD=changeme
MINIO_BUCKET=garden
# OpenPlantBook plant species API (https://open.plantbook.io — free account required)
OPENPLANTBOOK_CLIENT_ID=
OPENPLANTBOOK_CLIENT_SECRET=
+23 -17
View File
@@ -1,51 +1,57 @@
# ── famapp ────────────────────────────────────────────────────────────────────
# These vars are consumed by the famapp service in docker-compose.yml.
# Image tag to deploy. Pin to a specific version after first deploy
# (e.g. ghcr.io/ginnoir/famapp:v0.1.0). `latest` is fine for staging/initial.
FAMAPP_IMAGE=ghcr.io/ginnoir/famapp:latest
# `always` pulls on every `up`; set `missing` if you want to skip pulls.
FAMAPP_PULL_POLICY=always
# Authentik image tag. Bump in lockstep with Authentik release notes.
AUTHENTIK_IMAGE_TAG=2024.12.3
# Run drizzle migrations on container start. Leave true.
RUN_MIGRATIONS=true
# Public URL for the app — used by Auth.js for OIDC redirect URIs.
AUTH_URL=https://fam.ginnoir.com
# Public URL for the app
AUTH_URL=https://fam.yourdomain.com
# famapp Postgres credentials (used to build DATABASE_URL inside compose.yaml)
# famapp Postgres
FAMAPP_DB_USER=famapp
FAMAPP_DB_PASSWORD=replace-with-strong-password
FAMAPP_DB_NAME=famapp
# Auth.js session secret — generate with: openssl rand -base64 32
# NOTE: Reactive Resume uses RESUME_AUTH_SECRET; AUTH_SECRET is famapp-only.
AUTH_SECRET=replace-with-openssl-rand-base64-32
# OIDC provider (Authentik) — fill in after bootstrapping Authentik
AUTH_OIDC_ISSUER=https://auth.ginnoir.com/application/o/famapp/
AUTH_OIDC_ISSUER=https://auth.yourdomain.com/application/o/famapp/
AUTH_OIDC_CLIENT_ID=replace-me
AUTH_OIDC_CLIENT_SECRET=replace-me
# Web Push VAPID keys — generate with: pnpm vapid:generate (run from the repo)
# Web Push VAPID keys — generate with: pnpm vapid:generate
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
# Must be "mailto:<address>" or a URL
VAPID_SUBJECT=mailto:3nigma.matt@gmail.com
VAPID_SUBJECT=mailto:your-email@example.com
# ntfy push fallback — uses your existing ntfy instance at ntfy.ginnoir.com
# Leave NTFY_URL blank to disable ntfy fanout.
NTFY_URL=https://ntfy.ginnoir.com
# ntfy push fallback
NTFY_URL=https://ntfy.yourdomain.com
NTFY_TOPIC=famapp
# Log level: error | warn | info | debug
LOG_LEVEL=info
# ── Authentik ─────────────────────────────────────────────────────────────────
# MinIO object storage (garden image uploads)
famapp_MINIO_ROOT_USER=famapp
famapp_MINIO_ROOT_PASSWORD=replace-with-strong-password
famapp_MINIO_BUCKET=garden
# Authentik Postgres credentials (separate DB per Matt's rule)
# OpenPlantBook API (optional — used for plant species lookup)
famapp_OPENPLANTBOOK_CLIENT_ID=
famapp_OPENPLANTBOOK_CLIENT_SECRET=
# ── Authentik ─────────────────────────────────────────────────────────────────
AUTHENTIK_DB_USER=authentik
AUTHENTIK_DB_PASSWORD=replace-with-strong-password
AUTHENTIK_DB_NAME=authentik
# Authentik secret key — generate with: openssl rand -base64 60
AUTHENTIK_SECRET_KEY=replace-with-openssl-rand-base64-60
# ── Cloudflare (Caddy DNS-01 TLS) ─────────────────────────────────────────────
CF_API_TOKEN=replace-with-cloudflare-api-token
+26 -4
View File
@@ -6,7 +6,7 @@ on:
pull_request:
jobs:
verify:
checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@@ -17,7 +17,7 @@ jobs:
- uses: actions/setup-node@v4
with:
node-version: 22
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
@@ -28,10 +28,32 @@ jobs:
- run: pnpm format:check
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 10.33.3
- uses: actions/setup-node@v4
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- uses: actions/cache@v4
with:
path: .next/cache
key: ${{ runner.os }}-nextjs-${{ hashFiles('pnpm-lock.yaml') }}-${{ hashFiles('src/**/*.ts', 'src/**/*.tsx', 'src/**/*.css') }}
restore-keys: |
${{ runner.os }}-nextjs-${{ hashFiles('pnpm-lock.yaml') }}-
${{ runner.os }}-nextjs-
- run: pnpm build
env:
# Build only — no DB connection. Provide a placeholder so any
# module-level reads of DATABASE_URL don't crash the build.
DATABASE_URL: postgres://placeholder:placeholder@localhost:5432/placeholder
AUTH_SECRET: ci-placeholder-secret
NEXT_PUBLIC_APP_URL: http://localhost:3000
+11
View File
@@ -48,3 +48,14 @@ tests/.auth/
# Backups
deploy/backups/data/
# Production configs and deploy scripts — maintainer-specific, never commit
deploy/.prod/
deploy/compose.yaml
deploy/Caddyfile
deploy/Caddyfile.dev.snippet
scripts/apply-compose.ps1
scripts/sync-prod.ps1
# Design handoff bundle (reference only, not committed)
.design-tmp/
+1
View File
@@ -0,0 +1 @@
pnpm commitlint --edit "$1"
+1
View File
@@ -0,0 +1 @@
pnpm lint-staged
+1 -1
View File
@@ -1 +1 @@
22
24
+35
View File
@@ -0,0 +1,35 @@
{
"npm": {
"publish": false
},
"git": {
"commitMessage": "chore: release v${version}",
"tagName": "v${version}",
"requireBranch": "main"
},
"github": {
"release": true,
"releaseName": "v${version}"
},
"hooks": {
"before:git:release": "echo 'Check: README.md reflects current modules and env vars before tagging'"
},
"plugins": {
"@release-it/conventional-changelog": {
"preset": {
"name": "conventionalcommits",
"types": [
{ "type": "feat", "section": "Features" },
{ "type": "fix", "section": "Bug Fixes" },
{ "type": "perf", "section": "Performance" },
{ "type": "refactor", "section": "Refactoring" },
{ "type": "docs", "section": "Documentation" },
{ "type": "chore", "section": "Maintenance", "hidden": true },
{ "type": "ci", "section": "CI/CD", "hidden": true },
{ "type": "test", "section": "Tests", "hidden": true }
]
},
"infile": "CHANGELOG.md"
}
}
}
+2 -2
View File
@@ -31,7 +31,7 @@ Codex and Claude Code both work on this project. Keep `AGENTS.md`, `CLAUDE.md`,
| Realtime | Postgres `LISTEN/NOTIFY` → SSE | Simpler than WebSockets, fine for two users |
| Reverse proxy | Caddy (existing) | `fam.ginnoir.com` → famapp:3000, `auth.ginnoir.com` → authentik |
| Package manager | pnpm | Fast, content-addressed store, strict deps |
| Runtime | Node 22 LTS | In `node:22-alpine` container |
| Runtime | Node 24 LTS | In `node:24-alpine` container |
| Host | Ubuntu Server 24.04 x64, Docker + Compose | Existing self-host stack |
Domain: `fam.ginnoir.com`. SSO: `auth.ginnoir.com`.
@@ -106,7 +106,7 @@ All household-scoped entity tables include `household_id`. Sub-entities (`calend
```yaml
# compose.yaml (sketch — final lives in /deploy)
services:
famapp: # node:22-alpine, Next.js
famapp: # node:24-alpine, Next.js
famapp-db: # postgres:16
authentik-server:
authentik-worker:
+79 -3
View File
@@ -1,10 +1,86 @@
# Changelog
One line per release. "What's in prod" = the highest tag listed under a date that's been deployed.
## [0.5.1](https://github.com/ginnoir/famapp/compare/v0.5.0...v0.5.1) (2026-06-03)
Format: `## vX.Y.Z — YYYY-MM-DD`
### Bug Fixes
## Unreleased
- **dashboard:** always show tab strip and add-dashboard button regardless of dashboard count
- **search:** show Ctrl+K on Windows/Linux instead of ⌘K
- **mobile:** add search icon button in topbar for mobile viewports
- **mobile:** lock html/body overflow and use 100dvh to prevent topbar scrolling off-screen
## [0.5.0](https://github.com/ginnoir/famapp/compare/v0.4.10...v0.5.0) (2026-06-03)
### Features
- **mobile:** full mobile experience overhaul — bottom nav, touch targets, calendar mobile layout with day/week/agenda views and calendars bottom sheet, bidirectional swipe gestures on list items (right to complete, left to delete), iOS safe-area and keyboard support, input zoom prevention
- **mobile:** settings navigation replaced with 2-column icon grid (no horizontal scroll)
- **mobile:** remove floating action button in favour of persistent topbar quick-add button
## [0.4.10](https://github.com/ginnoir/famapp/compare/v0.4.9...v0.4.10) (2026-06-03)
## [0.4.8](https://github.com/ginnoir/famapp/compare/v0.4.6...v0.4.8) (2026-06-03)
### Features
- **garden:** add share button to plant and container detail views ([989bae8](https://github.com/ginnoir/famapp/commit/989bae8f1e2d5577da3e8777b6a35320c6da274c))
- share links visible on plants/containers; container image gallery ([c6a34f7](https://github.com/ginnoir/famapp/commit/c6a34f74717505e39ac4a88077728efa9fc50478))
### Bug Fixes
- **deploy:** separate reactive resume auth_secret from famapp ([aae3e30](https://github.com/ginnoir/famapp/commit/aae3e30843f54406244b637073aaf5e9ccc6b1d3))
### Documentation
- add contributing guide, env reference, and operations runbook ([076e35a](https://github.com/ginnoir/famapp/commit/076e35aced9303973da71ddd0ebded13f6c98833))
- add professional readme with full feature coverage and release pipeline hook ([6a1ec8b](https://github.com/ginnoir/famapp/commit/6a1ec8bb7be7ce64e82e5a4cee6b9f4ef92c7af8))
- update decisions index and task index for garden module and adr backfill ([8bf00c3](https://github.com/ginnoir/famapp/commit/8bf00c326db591851bdf8eee2fcedbfbed53d076))
## [0.4.6](https://github.com/ginnoir/famapp/compare/v0.4.5...v0.4.6) (2026-06-02)
### Bug Fixes
- **garden:** accept relative urls for plant image uploads ([6ca2e52](https://github.com/ginnoir/famapp/commit/6ca2e52e0a63d94826d9b1e208bcdded9c75fb07))
## [0.4.5](https://github.com/ginnoir/famapp/compare/v0.4.4...v0.4.5) (2026-06-02)
### Features
- **bangs:** add bang counter dashboard widget ([c850521](https://github.com/ginnoir/famapp/commit/c850521f3e993a5410f37cf29eb635cbc9540fd1))
## [0.4.4](https://github.com/ginnoir/famapp/compare/v0.4.3...v0.4.4) (2026-06-02)
### Bug Fixes
- **garden:** remove trailing slashes from openplantbook api urls and update label ([c744921](https://github.com/ginnoir/famapp/commit/c744921e6cfcf0269992cfd9afea47cc55082602))
## [0.4.3](https://github.com/ginnoir/famapp/compare/v0.4.2...v0.4.3) (2026-06-02)
### Bug Fixes
- **garden:** replace perenual with openplantbook for species lookup ([8722c20](https://github.com/ginnoir/famapp/commit/8722c205e6257a0590b48d0a858ad71d56ab07ac))
All notable changes to famapp are documented here.
## [0.3.0](https://github.com/ginnoir/famapp/compare/v0.2.0...v0.3.0) (2026-06-01)
### Features
- add dev startup script, fix push notifications, and scope test sends to device ([0c12b05](https://github.com/ginnoir/famapp/commit/0c12b05d0989630b3ec1445f65048bd766d5f8d1))
- expand theme system to 10 full-skin palettes with light and dark modes ([c3c8ae3](https://github.com/ginnoir/famapp/commit/c3c8ae37a280206186dfde82ecb270aea5e0c512))
### Bug Fixes
- refresh server components after nav style change to fix broken layout ([f55d685](https://github.com/ginnoir/famapp/commit/f55d685a794a539d2d6256d97c1a9c4e5fa3b8bf))
- scope rail nav-label hiding to sidebar and fall back fab-only to sidebar on desktop ([671b5fa](https://github.com/ginnoir/famapp/commit/671b5fae469b3cfcafe08b20ee2ce8ac15eef994))
### Documentation
- add github_token to .env.example ([5630537](https://github.com/ginnoir/famapp/commit/563053727908186a9816416fdf54c914002011de))
## Pre-release history
Changes from before the release workflow was established (2026-06-01):
- Production deployment scaffolding: tag-based release workflow (GHCR), migration entrypoint in container, prod-side dev-login startup assertion, image-pinned compose, pre-deploy checklist.
- famapp/authentik-server now expose host ports (3010/9200) so existing Caddy stack can proxy by IP, matching the existing homelab pattern.
+2 -2
View File
@@ -31,7 +31,7 @@ Codex and Claude Code both work on this project. Keep `AGENTS.md`, `CLAUDE.md`,
| Realtime | Postgres `LISTEN/NOTIFY` → SSE | Simpler than WebSockets, fine for two users |
| Reverse proxy | Caddy (existing) | `fam.ginnoir.com` → famapp:3000, `auth.ginnoir.com` → authentik |
| Package manager | pnpm | Fast, content-addressed store, strict deps |
| Runtime | Node 22 LTS | In `node:22-alpine` container |
| Runtime | Node 24 LTS | In `node:24-alpine` container |
| Host | Ubuntu Server 24.04 x64, Docker + Compose | Existing self-host stack |
Domain: `fam.ginnoir.com`. SSO: `auth.ginnoir.com`.
@@ -106,7 +106,7 @@ All household-scoped entity tables include `household_id`. Sub-entities (`calend
```yaml
# compose.yaml (sketch — final lives in /deploy)
services:
famapp: # node:22-alpine, Next.js
famapp: # node:24-alpine, Next.js
famapp-db: # postgres:16
authentik-server:
authentik-worker:
+4 -3
View File
@@ -1,7 +1,7 @@
# syntax=docker/dockerfile:1
# ── Stage 1: fetch dependencies ───────────────────────────────────────────────
FROM node:22-alpine AS deps
FROM node:24-alpine AS deps
RUN corepack enable && corepack prepare pnpm@10.33.3 --activate
WORKDIR /app
COPY package.json pnpm-lock.yaml .npmrc ./
@@ -16,10 +16,11 @@ ENV CI=true
ENV NEXT_TELEMETRY_DISABLED=1
COPY . .
RUN pnpm install --offline --frozen-lockfile
RUN pnpm build
RUN --mount=type=cache,id=famapp-nextjs,target=/app/.next/cache \
pnpm build
# ── Stage 3: production runtime ───────────────────────────────────────────────
FROM node:22-alpine AS runner
FROM node:24-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
+155 -5
View File
@@ -1,8 +1,158 @@
# famapp
Self-hosted family coordination: shared calendar, lists, notes.
Self-hosted family coordination web app. Shared calendar, lists, notes, and garden tracker — installable as a PWA, protected by OIDC single sign-on.
- **Plan & architecture:** [`CLAUDE.md`](CLAUDE.md)
- **Current progress:** [`STATUS.md`](STATUS.md)
- **Task briefs (for sub-sessions):** [`docs/tasks/`](docs/tasks/)
- **Architecture decisions:** [`docs/decisions/`](docs/decisions/)
[![CI](https://github.com/ginnoir/famapp/actions/workflows/ci.yml/badge.svg)](https://github.com/ginnoir/famapp/actions/workflows/ci.yml)
[![Latest release](https://img.shields.io/github/v/release/ginnoir/famapp?sort=semver)](https://github.com/ginnoir/famapp/releases)
[![Docker image](https://img.shields.io/badge/image-ghcr.io%2Fginnoir%2Ffamapp-blue?logo=docker)](https://github.com/ginnoir/famapp/pkgs/container/famapp)
[![Node ≥ 22](https://img.shields.io/badge/node-%E2%89%A522-brightgreen?logo=node.js)](https://nodejs.org)
---
## Features
### Modules
| Module | What it does |
| ------------ | ------------------------------------------------------------------------------------------ |
| **Calendar** | Month / week / day views, drag-to-create, household and private calendars, event reminders |
| **Lists** | Shopping and task lists with real-time sync, reorder, keyboard-first item entry |
| **Notes** | Markdown notes with pinning, safe preview, and optional remind-at scheduling |
| **Garden** | Plant and container tracking, care schedules, care logs, species lookup via OpenPlantBook |
### Platform capabilities
| Capability | Detail |
| ---------------------- | ------------------------------------------------------------------------------------------- |
| **Dashboard** | Per-user named dashboards, drag-resize widget grid, configurable widget instances |
| **Quick-add** | `Cmd/Ctrl+K` command palette and `+` FAB — every module registers its own actions |
| **Share links** | Any entity produces a temporary public link (`/s/<token>`), scoped read or read-write |
| **Activity log** | Household-scoped feed of every create / update / delete across all modules |
| **Reminders** | Generic reminder engine ticked every 30 s; notes and calendar events both use it |
| **Push notifications** | VAPID web push + in-app inbox + optional ntfy fallback |
| **Themes** | Two palettes (`default` / `warm`) × light / dark / system, zero flash on load |
| **PWA / offline** | Installable on iOS and Android, offline shell, stale-while-revalidate caching |
| **Structured logging** | JSON logs via pino in production, pretty-printed in dev, `LOG_LEVEL` configurable |
| **Nightly backups** | `pg_dump` cron for both databases, 14-day daily / 8-week weekly / 6-month monthly retention |
---
## Requirements
- **Docker** with the Compose plugin (v2)
- **Caddy** (or any reverse proxy that handles HTTPS)
- **Authentik** — famapp delegates all authentication to an Authentik OIDC provider; see the [bootstrap guide](deploy/authentik/README.md)
- A domain with DNS pointing to your host
---
## Quick start
Full details are in [`deploy/README.md`](deploy/README.md). The short version:
```bash
# 1. Clone and enter the repo
git clone https://github.com/ginnoir/famapp.git /srv/famapp
cd /srv/famapp
# 2. Create your environment file
cp .env.production.example deploy/.env
# Edit deploy/.env — see Configuration below for required values
# 3. Configure your reverse proxy
# Add deploy/Caddyfile.snippet to your Caddyfile, then reload Caddy
# 4. Bootstrap Authentik and record the OIDC client id/secret in deploy/.env
# See deploy/authentik/README.md
# 5. Start the stack
docker compose -f deploy/compose.example.yaml up -d
```
The container runs database migrations automatically on start. The first user to sign in becomes the household owner; a second sign-in joins the same household as a member.
Pin `FAMAPP_IMAGE` in `deploy/.env` after the first deploy:
```
FAMAPP_IMAGE=ghcr.io/ginnoir/famapp:v0.4.7
```
---
## Development setup
Requires Node ≥ 22 and pnpm 10.
```bash
git clone https://github.com/ginnoir/famapp.git
cd famapp
pnpm install
# Copy the example env and fill in dev values (set ENABLE_DEV_LOGIN=true)
cp .env.example .env
# Start the local database, run migrations, seed, and launch the dev server
pnpm dev:local
```
Then open `http://localhost:3000/login` and click **Dev login**.
Additional dev commands:
| Command | Purpose |
| --------------------- | ---------------------------------------------- |
| `pnpm dev:reset` | Drop and reseed the local database |
| `pnpm db:studio` | Open Drizzle Studio against the local database |
| `pnpm db:generate` | Generate a new migration after schema changes |
| `pnpm typecheck` | Run `tsc --noEmit` |
| `pnpm lint` | ESLint |
| `pnpm test:e2e` | Playwright E2E suite |
| `pnpm vapid:generate` | Print VAPID key env vars to stdout |
| `pnpm gen:icons` | Regenerate PWA icons from `public/icon.svg` |
See [`docs/dev-login.md`](docs/dev-login.md) for push notification and E2E testing setup.
---
## Configuration
Copy `.env.production.example` to `deploy/.env` and fill in values. Key variables:
| Variable | Required | How to generate |
| -------------------------------- | -------- | -------------------------------------------------------------------- |
| `AUTH_URL` | Yes | Public HTTPS URL for the app (e.g. `https://fam.yourdomain.com`) |
| `AUTH_SECRET` | Yes | `openssl rand -base64 32` |
| `AUTH_OIDC_ISSUER` | Yes | From Authentik — `https://auth.yourdomain.com/application/o/famapp/` |
| `AUTH_OIDC_CLIENT_ID` | Yes | From Authentik application |
| `AUTH_OIDC_CLIENT_SECRET` | Yes | From Authentik application |
| `FAMAPP_DB_PASSWORD` | Yes | Strong random password |
| `AUTHENTIK_DB_PASSWORD` | Yes | Strong random password |
| `AUTHENTIK_SECRET_KEY` | Yes | `openssl rand -base64 60` |
| `VAPID_PUBLIC_KEY` | Push | `pnpm vapid:generate` |
| `VAPID_PRIVATE_KEY` | Push | `pnpm vapid:generate` |
| `VAPID_SUBJECT` | Push | `mailto:your-email@example.com` |
| `NTFY_URL` / `NTFY_TOPIC` | Optional | ntfy push fallback |
| `famapp_OPENPLANTBOOK_CLIENT_ID` | Optional | OpenPlantBook API — plant species lookup |
| `LOG_LEVEL` | Optional | `error` / `warn` / `info` / `debug` (default: `info`) |
---
## Architecture
famapp uses an extensibility-first module system: every feature lives under `src/modules/<name>/` and declares its tables, routes, dashboard widgets, quick-add actions, and share/reminder/search behaviors via a manifest. Core services (sharing, push, reminders, activity log, search) operate generically — adding a new module does not require touching core code.
See [`CLAUDE.md`](CLAUDE.md) for the full architecture brief and [`docs/decisions/`](docs/decisions/) for ADRs.
---
## Deployment
| Resource | Link |
| -------------------- | -------------------------------------------------------------------------------- |
| Full host setup | [`deploy/README.md`](deploy/README.md) |
| Authentik bootstrap | [`deploy/authentik/README.md`](deploy/authentik/README.md) |
| Backup / restore | [`deploy/backups/README.md`](deploy/backups/README.md) |
| Pre-deploy checklist | [`docs/tasks/09-pre-deploy-checklist.md`](docs/tasks/09-pre-deploy-checklist.md) |
| Changelog | [`CHANGELOG.md`](CHANGELOG.md) |
Cutting a release: tag `vX.Y.Z` on `main` and push — CI builds and pushes `ghcr.io/ginnoir/famapp:vX.Y.Z` automatically.
+12
View File
@@ -0,0 +1,12 @@
export default {
extends: ["@commitlint/config-conventional"],
rules: {
"type-enum": [
2,
"always",
["feat", "fix", "refactor", "docs", "test", "chore", "perf", "ci", "revert"],
],
"subject-case": [2, "always", "lower-case"],
"subject-max-length": [2, "always", 100],
},
};
+7 -6
View File
@@ -1,10 +1,11 @@
# famapp — paste into your existing Caddyfile.
# famapp runs on 3010, authentik-server on 9200 (both bound to the host by deploy/compose.yaml).
# Add these blocks to your existing Caddyfile.
# Assumes famapp and authentik-server are reachable by Caddy
# (e.g. on a shared Docker network).
fam.ginnoir.com {
reverse_proxy 192.168.1.69:3010
fam.yourdomain.com {
reverse_proxy famapp:3000
}
auth.ginnoir.com {
reverse_proxy 192.168.1.69:9200
auth.yourdomain.com {
reverse_proxy authentik-server:9000
}
+19 -5
View File
@@ -2,16 +2,30 @@
Trunk-based: `main` is always green. Production deploys only from version tags (`vX.Y.Z`). The dev-login flow is retained for local development behind a double gate (`NODE_ENV !== "production"` **and** `ENABLE_DEV_LOGIN=true`); a startup assertion in `src/lib/dev-login-config.ts` makes a misconfigured prod fail loud instead of silently exposing it.
## Files in this directory
| File | Purpose |
| ----------------------- | -------------------------------------------------------------------------- |
| `compose.example.yaml` | **Start here.** Standalone famapp + Authentik stack for new deployments. |
| `compose.yaml` | Maintainer's production compose (full homelab monolith — not a template). |
| `Caddyfile.snippet` | Reverse proxy blocks to add to your Caddyfile. |
| `Caddyfile.dev.snippet` | Dev machine proxy block (maintainer-specific). |
| `Caddyfile` | Maintainer's full production Caddyfile (not a template). |
| `authentik/README.md` | Authentik bootstrap guide. |
| `backups/` | Backup container scripts (used by `famapp-backup` in the example compose). |
## One-time host setup
1. Install Docker + Compose plugin on the host.
2. `git clone` this repo to e.g. `/srv/famapp`.
3. Copy `.env.production.example``/srv/famapp/deploy/.env` and fill in real values.
3. Copy `deploy/compose.example.yaml``/srv/famapp/deploy/compose.yaml`.
4. Copy `.env.production.example``/srv/famapp/deploy/.env` and fill in real values.
- `openssl rand -base64 32` for `AUTH_SECRET`.
- `openssl rand -base64 60` for `AUTHENTIK_SECRET_KEY`.
- `pnpm vapid:generate` (locally) for the three VAPID lines.
4. Bootstrap Authentik per `deploy/authentik/README.md`. Save the OIDC client id/secret into `.env`.
5. Wire Caddy with `deploy/Caddyfile.snippet`.
- `openssl rand -hex 64` for the MinIO passwords.
- `pnpm vapid:generate` (locally, from the repo) for the three VAPID lines.
5. Bootstrap Authentik per `deploy/authentik/README.md`. Save the OIDC client id/secret into `.env`.
6. Wire Caddy (or any reverse proxy) using `deploy/Caddyfile.snippet`.
## Cutting a release
@@ -28,7 +42,7 @@ git push origin v0.1.0
```bash
cd /srv/famapp/deploy
# pin to the tag you just cut
echo 'FAMAPP_IMAGE=ghcr.io/ginnoir/famapp:v0.1.0' >> .env # or edit in place
sed -i 's|FAMAPP_IMAGE=.*|FAMAPP_IMAGE=ghcr.io/ginnoir/famapp:v0.1.0|' .env
docker compose pull famapp
docker compose up -d famapp
docker compose logs -f famapp # watch migrations + boot
+7 -7
View File
@@ -6,13 +6,13 @@ Run these steps once after the first `docker compose up -d` in the `deploy/` dir
## 1. Set the admin password
Visit `https://auth.ginnoir.com/if/flow/initial-setup/` and set the **akadmin** password.
Visit `https://auth.yourdomain.com/if/flow/initial-setup/` and set the **akadmin** password.
---
## 2. Create the OIDC provider
1. Log in to the Authentik Admin UI at `https://auth.ginnoir.com/if/admin/`.
1. Log in to the Authentik Admin UI at `https://auth.yourdomain.com/if/admin/`.
2. Go to **Applications → Providers → Create**.
3. Choose **OAuth2/OpenID Provider**.
4. Configure:
@@ -21,7 +21,7 @@ Visit `https://auth.ginnoir.com/if/flow/initial-setup/` and set the **akadmin**
- **Client type:** `Confidential`
- **Client ID:** (auto-generated — copy this)
- **Client Secret:** (auto-generated — copy this)
- **Redirect URIs:** `https://fam.ginnoir.com/api/auth/callback/authentik`
- **Redirect URIs:** `https://fam.yourdomain.com/api/auth/callback/authentik`
- **Signing Key:** `authentik Self-signed Certificate`
- **Token validity:** 24 hours (or your preference)
5. Save and note the **Issuer URL** shown on the provider detail page.
@@ -29,13 +29,13 @@ Visit `https://auth.ginnoir.com/if/flow/initial-setup/` and set the **akadmin**
The issuer URL will look like:
```
https://auth.ginnoir.com/application/o/famapp/
https://auth.yourdomain.com/application/o/famapp/
```
Set this (and the client ID/secret) in famapp's `.env` / production secrets:
```env
AUTH_OIDC_ISSUER=https://auth.ginnoir.com/application/o/famapp/
AUTH_OIDC_ISSUER=https://auth.yourdomain.com/application/o/famapp/
AUTH_OIDC_CLIENT_ID=<client-id>
AUTH_OIDC_CLIENT_SECRET=<client-secret>
```
@@ -49,7 +49,7 @@ AUTH_OIDC_CLIENT_SECRET=<client-secret>
- **Name:** `famapp`
- **Slug:** `famapp`
- **Provider:** select the `famapp` provider created above
- **Launch URL:** `https://fam.ginnoir.com`
- **Launch URL:** `https://fam.yourdomain.com`
3. Save.
---
@@ -68,7 +68,7 @@ AUTH_OIDC_CLIENT_SECRET=<client-secret>
Each user can enroll a passkey from their Authentik profile:
1. Sign in as the user at `https://auth.ginnoir.com`.
1. Sign in as the user at `https://auth.yourdomain.com`.
2. Go to **Settings → MFA Devices → Add → WebAuthn Device**.
3. Follow the browser prompt to register a Touch ID / Face ID / hardware key.
+196
View File
@@ -0,0 +1,196 @@
# Standalone famapp deployment template.
# Copy this to compose.yaml (or reference with -f), fill in .env from
# .env.production.example, then: docker compose up -d
#
# Caddy (or any reverse proxy) should sit in front — see Caddyfile.snippet.
# If Caddy runs in a separate compose stack, add famapp to that stack's
# external network instead of exposing ports directly.
name: famapp
networks:
famapp_net:
volumes:
famapp_db_data:
authentik_db_data:
authentik_redis_data:
garden_uploads:
backups:
services:
famapp:
image: ${FAMAPP_IMAGE:-ghcr.io/ginnoir/famapp:latest}
pull_policy: ${FAMAPP_PULL_POLICY:-always}
restart: unless-stopped
environment:
NODE_ENV: production
AUTH_URL: ${AUTH_URL}
DATABASE_URL: postgres://${FAMAPP_DB_USER}:${FAMAPP_DB_PASSWORD}@famapp-db:5432/${FAMAPP_DB_NAME}
AUTH_SECRET: ${AUTH_SECRET}
AUTH_OIDC_ISSUER: ${AUTH_OIDC_ISSUER}
AUTH_OIDC_CLIENT_ID: ${AUTH_OIDC_CLIENT_ID}
AUTH_OIDC_CLIENT_SECRET: ${AUTH_OIDC_CLIENT_SECRET}
VAPID_PUBLIC_KEY: ${VAPID_PUBLIC_KEY}
VAPID_PRIVATE_KEY: ${VAPID_PRIVATE_KEY}
VAPID_SUBJECT: ${VAPID_SUBJECT}
NTFY_URL: ${NTFY_URL:-}
NTFY_TOPIC: ${NTFY_TOPIC:-}
LOG_LEVEL: ${LOG_LEVEL:-info}
RUN_MIGRATIONS: ${RUN_MIGRATIONS:-true}
MINIO_ENDPOINT: http://famapp-minio:9000
MINIO_ROOT_USER: ${famapp_MINIO_ROOT_USER}
MINIO_ROOT_PASSWORD: ${famapp_MINIO_ROOT_PASSWORD}
MINIO_BUCKET: ${famapp_MINIO_BUCKET:-garden}
OPENPLANTBOOK_CLIENT_ID: ${famapp_OPENPLANTBOOK_CLIENT_ID:-}
OPENPLANTBOOK_CLIENT_SECRET: ${famapp_OPENPLANTBOOK_CLIENT_SECRET:-}
ports:
- "${FAMAPP_PORT:-3000}:3000"
depends_on:
famapp-db:
condition: service_healthy
famapp-minio:
condition: service_healthy
networks:
- famapp_net
famapp-db:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_USER: ${FAMAPP_DB_USER}
POSTGRES_PASSWORD: ${FAMAPP_DB_PASSWORD}
POSTGRES_DB: ${FAMAPP_DB_NAME}
volumes:
- famapp_db_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${FAMAPP_DB_USER} -d ${FAMAPP_DB_NAME}"]
interval: 10s
timeout: 5s
retries: 5
networks:
- famapp_net
famapp-minio:
image: minio/minio:latest
command: server /data --console-address ":9001"
restart: unless-stopped
environment:
MINIO_ROOT_USER: ${famapp_MINIO_ROOT_USER}
MINIO_ROOT_PASSWORD: ${famapp_MINIO_ROOT_PASSWORD}
volumes:
- garden_uploads:/data
ports:
- "9000:9000"
- "9001:9001"
healthcheck:
test: ["CMD-SHELL", "curl -sf http://localhost:9000/minio/health/live || exit 1"]
interval: 30s
timeout: 20s
retries: 3
start_period: 30s
networks:
- famapp_net
famapp-backup:
image: alpine:3.20
restart: unless-stopped
environment:
FAMAPP_DB_HOST: famapp-db
FAMAPP_DB_PORT: "5432"
FAMAPP_DB_USER: ${FAMAPP_DB_USER}
FAMAPP_DB_PASSWORD: ${FAMAPP_DB_PASSWORD}
FAMAPP_DB_NAME: ${FAMAPP_DB_NAME}
AUTHENTIK_DB_HOST: authentik-db
AUTHENTIK_DB_PORT: "5432"
AUTHENTIK_DB_USER: ${AUTHENTIK_DB_USER:-authentik}
AUTHENTIK_DB_PASSWORD: ${AUTHENTIK_DB_PASSWORD}
AUTHENTIK_DB_NAME: ${AUTHENTIK_DB_NAME:-authentik}
volumes:
- backups:/backups
- ./backups:/scripts:ro
depends_on:
famapp-db:
condition: service_healthy
authentik-db:
condition: service_healthy
networks:
- famapp_net
entrypoint: ["sh", "/scripts/entrypoint.sh"]
authentik-server:
image: ghcr.io/goauthentik/server:${AUTHENTIK_IMAGE_TAG:-2024.12.3}
restart: unless-stopped
command: server
environment:
AUTHENTIK_REDIS__HOST: authentik-redis
AUTHENTIK_POSTGRESQL__HOST: authentik-db
AUTHENTIK_POSTGRESQL__USER: ${AUTHENTIK_DB_USER:-authentik}
AUTHENTIK_POSTGRESQL__PASSWORD: ${AUTHENTIK_DB_PASSWORD}
AUTHENTIK_POSTGRESQL__NAME: ${AUTHENTIK_DB_NAME:-authentik}
AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY}
AUTHENTIK_ERROR_REPORTING__ENABLED: "false"
ports:
- "9200:9000"
depends_on:
authentik-db:
condition: service_healthy
authentik-redis:
condition: service_healthy
networks:
- famapp_net
authentik-worker:
image: ghcr.io/goauthentik/server:${AUTHENTIK_IMAGE_TAG:-2024.12.3}
restart: unless-stopped
command: worker
environment:
AUTHENTIK_REDIS__HOST: authentik-redis
AUTHENTIK_POSTGRESQL__HOST: authentik-db
AUTHENTIK_POSTGRESQL__USER: ${AUTHENTIK_DB_USER:-authentik}
AUTHENTIK_POSTGRESQL__PASSWORD: ${AUTHENTIK_DB_PASSWORD}
AUTHENTIK_POSTGRESQL__NAME: ${AUTHENTIK_DB_NAME:-authentik}
AUTHENTIK_SECRET_KEY: ${AUTHENTIK_SECRET_KEY}
AUTHENTIK_ERROR_REPORTING__ENABLED: "false"
depends_on:
authentik-db:
condition: service_healthy
authentik-redis:
condition: service_healthy
networks:
- famapp_net
authentik-db:
image: postgres:16-alpine
restart: unless-stopped
environment:
POSTGRES_USER: ${AUTHENTIK_DB_USER:-authentik}
POSTGRES_PASSWORD: ${AUTHENTIK_DB_PASSWORD}
POSTGRES_DB: ${AUTHENTIK_DB_NAME:-authentik}
volumes:
- authentik_db_data:/var/lib/postgresql/data
healthcheck:
test:
[
"CMD-SHELL",
"pg_isready -U ${AUTHENTIK_DB_USER:-authentik} -d ${AUTHENTIK_DB_NAME:-authentik}",
]
interval: 10s
timeout: 5s
retries: 5
networks:
- famapp_net
authentik-redis:
image: redis:7-alpine
restart: unless-stopped
command: --save 60 1 --loglevel warning
volumes:
- authentik_redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
networks:
- famapp_net
-11
View File
@@ -1,11 +0,0 @@
#!/bin/sh
set -e
if [ "${RUN_MIGRATIONS:-true}" = "true" ]; then
echo "running migrations..."
node /app/scripts/migrate.mjs
else
echo "skipping migrations (RUN_MIGRATIONS=$RUN_MIGRATIONS)"
fi
exec node /app/server.js
+14
View File
@@ -11,5 +11,19 @@ services:
volumes:
- famapp-db-data:/var/lib/postgresql/data
minio:
image: minio/minio:latest
command: server /data --console-address ":9001"
restart: unless-stopped
environment:
MINIO_ROOT_USER: famapp
MINIO_ROOT_PASSWORD: changeme
ports:
- "9000:9000"
- "9001:9001"
volumes:
- famapp-minio-data:/data
volumes:
famapp-db-data:
famapp-minio-data:
+158
View File
@@ -0,0 +1,158 @@
# Contributing
## Prerequisites
- **Node.js** 24 LTS (`node --version` should print `v24.x.x`)
- **pnpm** 10 (`pnpm --version` should print `10.x.x`)
- **Docker** with the Compose plugin (used for the local Postgres + MinIO containers)
## Setup
```bash
git clone https://github.com/ginnoir/famapp.git
cd famapp
pnpm install
cp .env.example .env
# Edit .env — minimum required for local dev:
# NEXT_PUBLIC_APP_URL=http://127.0.0.1:3000
# DATABASE_URL=postgres://famapp:famapp@localhost:5432/famapp
# ENABLE_DEV_LOGIN=true
# AUTH_SECRET=<any-32-char-string-for-local>
```
Start everything (database + migrations + seed + dev server):
```bash
pnpm dev:local
```
Then open `http://localhost:3000/login` and click **Dev login**. See `docs/dev-login.md` for the full local setup including HTTPS/PWA testing.
## Available scripts
<!-- AUTO-GENERATED from package.json scripts -->
| Command | Description |
| --------------------- | ----------------------------------------------------------------------------------------- |
| `pnpm dev` | Next.js dev server (localhost only) |
| `pnpm dev:network` | Dev server bound to `0.0.0.0` (LAN access for phone testing) |
| `pnpm dev:local` | Full local stack — starts DB container, runs migrations, seeds, launches dev server |
| `pnpm dev:reset` | Tear down local DB and start fresh (destructive — deletes all local data) |
| `pnpm build` | Production Next.js build |
| `pnpm start` | Start the production build locally |
| `pnpm lint` | ESLint check |
| `pnpm lint:fix` | ESLint with auto-fix |
| `pnpm format` | Prettier — format all files |
| `pnpm format:check` | Prettier — check only (used in CI) |
| `pnpm typecheck` | TypeScript type check (`tsc --noEmit`) |
| `pnpm test:e2e` | Playwright end-to-end tests |
| `pnpm db:generate` | Generate a new Drizzle migration from schema changes |
| `pnpm db:migrate` | Apply pending Drizzle migrations |
| `pnpm db:seed` | Seed the database with dev fixtures |
| `pnpm db:studio` | Open Drizzle Studio (local DB browser) |
| `pnpm gen:icons` | Regenerate PWA icon set from source |
| `pnpm vapid:generate` | Generate VAPID key pair for Web Push |
| `pnpm release` | Interactive release (prompts for semver bump, tags, publishes changelog + GitHub Release) |
| `pnpm release:patch` | Non-interactive patch release |
| `pnpm release:minor` | Non-interactive minor release |
| `pnpm release:major` | Non-interactive major release |
| `pnpm release:dry` | Dry-run release — preview without writing |
<!-- END AUTO-GENERATED -->
## Running tests
### Type check + lint (CI equivalent)
```bash
pnpm typecheck
pnpm lint
pnpm format:check
```
### End-to-end tests
The app must be running first (`pnpm dev:local`). Generate a Playwright auth state file, then run tests:
```powershell
# Generate auth state (run once after starting the app)
New-Item -ItemType Directory -Force tests\.auth | Out-Null
@'
const { chromium } = require('@playwright/test');
(async () => {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('http://127.0.0.1:3000/login');
await page.getByRole('button', { name: 'Dev login' }).click();
await page.waitForURL('http://127.0.0.1:3000/');
await page.context().storageState({ path: 'tests/.auth/dev-user.json' });
await browser.close();
})();
'@ | node -
# Run tests
$env:PLAYWRIGHT_STORAGE_STATE='tests/.auth/dev-user.json'
pnpm test:e2e
```
### Writing tests
- Unit tests: Vitest under `tests/unit/` — only where it pays off (utilities, pure logic).
- E2E tests: Playwright under `tests/e2e/` — one happy-path test per module. Do not write brittle selector-heavy tests for trivial CRUD.
## Code style
- **TypeScript strict** — no `any` without a written reason.
- **No comments** unless the _why_ is non-obvious. Names carry intent.
- **Immutable** — always return new objects; never mutate in place.
- **Module isolation** — a module imports from `_core` and `lib/` only; never from a sibling module.
- **File size** — 200400 lines typical, 800 hard cap.
Formatting and lint run automatically on staged files via `lint-staged` at commit time. You can also run them manually with `pnpm lint:fix` and `pnpm format`.
## Commit format
Commits must follow [Conventional Commits](https://www.conventionalcommits.org/). `commitlint` enforces this at the `commit-msg` hook.
```
<type>: <short description>
[optional body]
```
Allowed types: `feat`, `fix`, `refactor`, `docs`, `test`, `chore`, `perf`, `ci`, `revert`
Examples:
```
feat: add plant species search to garden module
fix: calendar event end time off by one day
chore: bump next to 15.6
```
## Adding a module
Every feature lives under `src/modules/<name>/`. A new module needs:
- `schema.ts` — Drizzle tables
- `server/` — server actions and queries
- `components/` — React components
- `manifest.ts` — registers the module with the core registry (nav, entity types, dashboard widget, quick-add actions)
See `CLAUDE.md` for the full architectural brief. The module loader in `src/modules/_core/` discovers manifests automatically — no changes to core code required for a new module.
## Schema changes
1. Edit the relevant `schema.ts`.
2. Run `pnpm db:generate` to create a new migration file under `drizzle/`.
3. Commit the migration alongside the schema change.
4. Never edit a shipped migration — always add a new one.
## PR checklist
- [ ] `pnpm typecheck` passes
- [ ] `pnpm lint` passes
- [ ] `pnpm build` succeeds
- [ ] New Drizzle migration committed if schema changed
- [ ] E2E test added or updated if a user-visible flow changed
- [ ] `docs/tasks/09-pre-deploy-checklist.md` reviewed if touching auth or env
+112
View File
@@ -0,0 +1,112 @@
# Environment Variables
<!-- AUTO-GENERATED from .env.example and deploy/compose.example.yaml -->
## Quick start
```bash
cp .env.example .env
# Fill in required values, then:
pnpm dev:local
```
## Core
| Variable | Required | Description | Example / Default |
| --------------------- | -------- | ------------------------------------------------------------------ | ------------------------------------------------ |
| `NEXT_PUBLIC_APP_URL` | Yes | Public URL of the app — used in OIDC redirect URIs and share links | `https://fam.yourdomain.com` |
| `DATABASE_URL` | Yes | Postgres connection string | `postgres://famapp:famapp@localhost:5432/famapp` |
| `AUTH_SECRET` | Yes | Auth.js signing secret — generate with `openssl rand -base64 32` | — |
## OIDC (Authentik)
Required in production. Obtain from the Authentik admin panel after bootstrapping the provider — see `deploy/authentik/README.md`.
| Variable | Required | Description | Example |
| ------------------------- | ---------- | --------------------------------- | --------------------------------------------------- |
| `AUTH_OIDC_ISSUER` | Yes (prod) | Authentik OIDC issuer URL | `https://auth.yourdomain.com/application/o/famapp/` |
| `AUTH_OIDC_CLIENT_ID` | Yes (prod) | OIDC client ID from Authentik | — |
| `AUTH_OIDC_CLIENT_SECRET` | Yes (prod) | OIDC client secret from Authentik | — |
## Dev login
Local development only. Never set `ENABLE_DEV_LOGIN=true` in production — a startup assertion in `src/lib/dev-login-config.ts` will crash the container if you do.
| Variable | Required | Description | Default |
| -------------------- | -------- | ------------------------------------------------- | ------------------ |
| `ENABLE_DEV_LOGIN` | No | Show a one-click **Dev login** button on `/login` | `false` |
| `DEV_LOGIN_EMAIL` | No | Email for the auto-created dev session | `dev@famapp.local` |
| `DEV_LOGIN_NAME` | No | Display name for the dev user | `Dev User` |
| `DEV_HOUSEHOLD_NAME` | No | Household created for the dev user | `Home` |
See `docs/dev-login.md` for the full local run procedure.
## Web Push (VAPID)
All three are required together. Generate them once with `pnpm vapid:generate` and copy all three lines into `.env`.
| Variable | Required | Description |
| ------------------- | -------- | --------------------------------------------- | ------------------------ |
| `VAPID_PUBLIC_KEY` | Yes | VAPID public key — also passed to the browser |
| `VAPID_PRIVATE_KEY` | Yes | VAPID private key — server only |
| `VAPID_SUBJECT` | Yes | Contact URI for push servers | `mailto:you@example.com` |
## ntfy (optional)
Leave both blank to disable the ntfy notification channel. Web Push is the primary channel.
| Variable | Required | Description | Example |
| ------------ | -------- | ------------------------ | ----------------- |
| `NTFY_URL` | No | ntfy server base URL | `https://ntfy.sh` |
| `NTFY_TOPIC` | No | ntfy topic to publish to | `famapp-alerts` |
## Logging
| Variable | Required | Description | Values |
| ----------- | -------- | ------------------ | ----------------------------------------------------------- |
| `LOG_LEVEL` | No | Pino log verbosity | `trace`, `debug`, `info`, `warn`, `error` (default: `info`) |
## MinIO object storage
Required when the garden module is enabled. The dev compose stack starts a local MinIO instance automatically via `pnpm dev:local`.
| Variable | Required | Description | Default |
| --------------------- | -------- | ------------------------------------ | ----------------------- |
| `MINIO_ENDPOINT` | Yes | MinIO server base URL | `http://localhost:9000` |
| `MINIO_ROOT_USER` | Yes | MinIO root access key | `famapp` |
| `MINIO_ROOT_PASSWORD` | Yes | MinIO root secret key | `changeme` |
| `MINIO_BUCKET` | No | Bucket used for garden image uploads | `garden` |
## OpenPlantBook
Optional. Enables plant species lookup in the garden module. Free account at <https://open.plantbook.io>.
| Variable | Required | Description |
| ----------------------------- | -------- | -------------------- |
| `OPENPLANTBOOK_CLIENT_ID` | No | OAuth2 client ID |
| `OPENPLANTBOOK_CLIENT_SECRET` | No | OAuth2 client secret |
## Release tooling
Only needed on the machine that cuts releases (`pnpm release`).
| Variable | Required | Description |
| -------------- | ------------- | ------------------------------------------------ |
| `GITHUB_TOKEN` | Yes (release) | Personal access token — creates a GitHub Release |
## Production-only compose variables
Used by `deploy/compose.example.yaml`. Set in `deploy/.env` on the server — not in the local `.env`.
| Variable | Description |
| ------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `FAMAPP_IMAGE` | Docker image tag to deploy (e.g. `ghcr.io/ginnoir/famapp:v0.4.7`) |
| `FAMAPP_PORT` | Host port to bind (default: `3000`) |
| `FAMAPP_PULL_POLICY` | Docker pull policy (default: `always`) |
| `FAMAPP_DB_USER` / `FAMAPP_DB_PASSWORD` / `FAMAPP_DB_NAME` | Postgres credentials for the famapp database |
| `AUTHENTIK_DB_USER` / `AUTHENTIK_DB_PASSWORD` / `AUTHENTIK_DB_NAME` | Postgres credentials for the Authentik database |
| `AUTHENTIK_SECRET_KEY` | Authentik signing key — generate with `openssl rand -base64 60` |
| `AUTHENTIK_IMAGE_TAG` | Authentik server image tag (default: `2024.12.3`) |
| `RUN_MIGRATIONS` | Set `false` to skip auto-migration on start (default: `true`) |
<!-- END AUTO-GENERATED -->
+158
View File
@@ -0,0 +1,158 @@
# Runbook
Operational reference for famapp in production. See `deploy/README.md` for the one-time host setup and `docs/tasks/09-pre-deploy-checklist.md` for the pre-deploy checklist.
## Cutting a release
From `main` on the dev machine, with a clean working tree:
```bash
pnpm release:patch # or :minor / :major
# — bumps package.json version
# — prepends to CHANGELOG.md
# — creates and pushes a signed git tag (v0.x.y)
# — creates a GitHub Release with generated notes
# Requires GITHUB_TOKEN in .env
```
CI (`release.yml`) then builds and pushes the Docker image to GHCR:
- `ghcr.io/ginnoir/famapp:v0.x.y`
- `ghcr.io/ginnoir/famapp:0.x` (minor alias)
- `ghcr.io/ginnoir/famapp:latest`
## Deploying a release
On the home server, in `/srv/famapp/deploy/`:
```bash
# Pin the new tag
sed -i 's|FAMAPP_IMAGE=.*|FAMAPP_IMAGE=ghcr.io/ginnoir/famapp:v0.x.y|' .env
# Pull and restart only the app container
docker compose pull famapp
docker compose up -d famapp
# Watch the boot log — migrations run before the server starts
docker compose logs -f famapp
```
The container entrypoint runs `node scripts/migrate.mjs` automatically. A healthy boot ends with a log line like `ready on http://0.0.0.0:3000`.
## Health check
```bash
# Container status
docker compose ps
# App response (200 = healthy)
curl -sf https://fam.yourdomain.com/ -o /dev/null -w "%{http_code}\n"
# Recent app logs
docker compose logs --tail=100 famapp
# Database connectivity
docker compose exec famapp-db pg_isready -U famapp -d famapp
```
## Rollback
1. Find the previous working tag in `CHANGELOG.md` or `docker images`.
2. Pin it in `deploy/.env`:
```bash
sed -i 's|FAMAPP_IMAGE=.*|FAMAPP_IMAGE=ghcr.io/ginnoir/famapp:v0.x.y|' .env
```
3. Restart the container:
```bash
docker compose up -d famapp
```
If the rollback target predates a migration that has already been applied to the database, restore from backup first — see **Backups** below. To skip auto-migration on a given start (rarely needed):
```bash
RUN_MIGRATIONS=false docker compose up -d famapp
```
## Backups
The `famapp-backup` container runs nightly `pg_dump` for both `famapp` and `authentik` databases into the `backups` volume.
```bash
# Check last backup run
docker compose logs famapp-backup | tail -20
# List backup files
docker compose exec famapp-backup ls -lh /backups
# Manual backup now
docker compose exec famapp-backup sh /scripts/backup.sh
# Restore from a backup file
docker compose exec famapp-backup sh /scripts/restore.sh famapp_2026-06-01.sql.gz
```
See `deploy/backups/README.md` for retention policy and full restore details.
## Common issues
### App container exits immediately
```bash
docker compose logs famapp
```
Likely causes:
- **Missing required env var** — the app throws on startup if `AUTH_SECRET`, `DATABASE_URL`, or `AUTH_OIDC_*` are absent.
- **`ENABLE_DEV_LOGIN=true` in production** — `src/lib/dev-login-config.ts` throws an assertion error on import. Remove the variable from the production env.
- **Database not ready** — Postgres healthcheck should prevent this, but if the DB is slow to start, increase `start_period` in `compose.yaml`.
### Migrations fail on boot
```bash
docker compose logs famapp | grep -i migration
```
- Schema is ahead of code: roll back the image or forward-migrate manually.
- Database unreachable: confirm `famapp-db` is healthy (`docker compose ps`).
### OIDC login fails
1. Confirm `AUTH_OIDC_ISSUER` matches the Authentik provider URL exactly (trailing slash matters).
2. Confirm the OIDC client redirect URI in Authentik includes `https://fam.yourdomain.com/api/auth/callback/oidc`.
3. Check Authentik logs: `docker compose logs authentik-server | tail -50`.
### Push notifications not arriving
1. Confirm `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, and `VAPID_SUBJECT` are all set in the production env.
2. Verify the browser's push subscription is still valid (Settings → notifications → re-enable).
3. If using ntfy as a secondary channel, confirm `NTFY_URL` and `NTFY_TOPIC` are set.
### MinIO / garden image uploads failing
```bash
docker compose logs famapp-minio | tail -30
```
- Confirm `MINIO_ENDPOINT` is `http://famapp-minio:9000` in the compose env (not `localhost`).
- Confirm the `garden` bucket exists — create it manually via the MinIO console at port `9001` if it is missing.
### Out of disk space
```bash
df -h /var/lib/docker
docker system prune --volumes # removes stopped containers, dangling images, unused volumes
```
Old backup files accumulate in the `backups` volume. The retention script (`deploy/backups/retain.sh`) runs nightly — check its logs if the volume keeps growing.
## Authentik admin access
The Authentik admin UI is at `https://auth.yourdomain.com`. Log in with the superuser credentials set during bootstrap — see `deploy/authentik/README.md`.
To reset the Authentik admin password from the CLI:
```bash
docker compose exec authentik-server ak create_recovery_key 1 akadmin
# prints a one-time recovery URL
```
+36
View File
@@ -0,0 +1,36 @@
# 0003 — Release workflow
Date: 2026-06-01
Status: accepted
## Context
The project needed a consistent, enforced standard for commit messages, changelog generation, versioning, and GitHub releases — especially important since both humans and AI agents (Claude Code, Codex) commit to the repo.
## Decision
- **commitlint** (`@commitlint/config-conventional`) enforces conventional commit format at the `commit-msg` git hook
- **husky** v9 wires the hooks; `prepare` installs them on `pnpm install`
- **lint-staged** runs prettier + eslint on staged files at the `pre-commit` hook
- **release-it** + `@release-it/conventional-changelog` manages the full release cycle:
- bumps `package.json` version (semver)
- generates/prepends to `CHANGELOG.md`
- creates a signed git tag (`v{version}`)
- creates a GitHub Release with the generated notes
- pushes the tag and commit
Release commands:
- `pnpm release` — interactive (prompts for increment type)
- `pnpm release:patch` / `:minor` / `:major` — non-interactive
- `pnpm release:dry` — preview without writing anything
- Requires `GITHUB_TOKEN` in env for GitHub Release creation
Conventional commit types: `feat`, `fix`, `refactor`, `docs`, `test`, `chore`, `perf`, `ci`, `revert`
## Consequences
- Every commit is validated; bad format is rejected immediately
- CHANGELOG.md is auto-generated from commit history — no manual upkeep
- Releases are reproducible: one command, idempotent output
- `chore`, `ci`, `test` commits are hidden in the changelog; `feat`, `fix`, `perf`, `refactor`, `docs` are surfaced
+5 -1
View File
@@ -22,4 +22,8 @@ What this costs us, what it buys us.
## Index
- (none yet — add as decisions are made)
<!-- AUTO-GENERATED -->
- [0002 — List realtime uses Postgres NOTIFY and SSE](0002-list-sse-notify.md)
- [0003 — Release workflow (commitlint + release-it)](0003-release-workflow.md)
<!-- END AUTO-GENERATED -->
+58 -8
View File
@@ -34,20 +34,70 @@ This note tracks the development-only work added to make the app easy to run and
## Current Local Run Procedure
One command starts the database, runs migrations, seeds, and launches the dev server:
```powershell
docker compose -f docker-compose.dev.yaml up -d
pnpm db:migrate
pnpm db:seed
pnpm dev
pnpm dev:local
```
Then open:
The script prints three URLs at startup:
```text
http://127.0.0.1:3000/login
| URL | Use for |
| ---------------------------- | ---------------------------------------------------------- |
| `http://localhost:3000` | Browser on this machine |
| `http://192.168.x.y:3000` | Phone on the same WiFi (general UI testing) |
| `https://dev.yourdomain.com` | Push notifications + PWA install (needs Caddy — see below) |
Then open `/login` and click **Dev login**.
### HMR and restarts
`next dev` has hot module replacement — most `.ts`/`.tsx` changes apply instantly without a restart.
A full restart (`Ctrl+C``pnpm dev:local`) is needed for:
- `.env` changes
- `next.config.ts` changes
### Clean slate
To delete all local data and start fresh (e.g. after a destructive schema change):
```powershell
pnpm dev:reset
```
Click **Dev login**.
### HTTPS for push notification and PWA testing (one-time setup)
Service workers and Web Push require HTTPS. The plain LAN address won't work for these.
Route through the existing Caddy server on the home server instead — no extra tooling needed.
**Step 1 — DHCP reservation**
Set a reservation on the router so the dev machine always gets `192.168.x.y`.
**Step 2 — DNS record**
Add a `dev.yourdomain.com` A record pointing to the same public IP as `fam.yourdomain.com`.
**Step 3 — Windows Firewall**
Allow inbound TCP 3000 on the dev machine (run once in an elevated PowerShell):
```powershell
New-NetFirewallRule -DisplayName "famapp dev" -Direction Inbound `
-Protocol TCP -LocalPort 3000 -Action Allow
```
**Step 4 — Caddy snippet**
Paste `deploy/Caddyfile.dev.snippet` into the home server Caddyfile and reload:
```bash
caddy reload --config /path/to/Caddyfile
```
After this, `https://dev.yourdomain.com` proxies to the dev machine with a real Let's Encrypt cert.
## Current Local E2E Procedure
+4
View File
@@ -2,6 +2,10 @@
Run this before every production deploy (first deploy and each tagged release). Dev-login is intentionally retained behind a double gate; this checklist is what keeps that gate honest.
## README
- [ ] `README.md` reflects the current module list and any env vars added since the last release.
## Env hygiene
- [ ] Server `.env` (next to `deploy/compose.yaml`) does **not** set:
+173
View File
@@ -0,0 +1,173 @@
# 70 — Garden infrastructure (MinIO + upload route + schema)
## Goal
Lay the infrastructure foundation for the garden module: add a MinIO object-storage container to the compose stack, create a generic file-upload API route, define the Drizzle schema for all four garden tables, and run the migration.
No UI or business logic — just the plumbing that every subsequent garden task depends on.
## Depends on
- 03 (Drizzle + Postgres), 07 (household seed)
## Scope
### compose.yaml additions (`deploy/compose.yaml`)
Add a `minio` service and a `garden-uploads` named volume:
```yaml
minio:
image: minio/minio:latest
command: server /data --console-address ":9001"
environment:
MINIO_ROOT_USER: ${MINIO_ROOT_USER}
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD}
volumes:
- garden-uploads:/data
ports:
- "9000:9000" # API
- "9001:9001" # Console (dev only — restrict in prod)
healthcheck:
test: ["CMD", "mc", "ready", "local"]
interval: 30s
timeout: 10s
retries: 3
volumes:
garden-uploads:
```
Add `MINIO_ENDPOINT`, `MINIO_ROOT_USER`, `MINIO_ROOT_PASSWORD`, `MINIO_BUCKET` to `.env.example`.
### MinIO client (`src/lib/minio.ts`)
Thin singleton using the `minio` npm package:
- Connect using `MINIO_ENDPOINT`, `MINIO_ROOT_USER`, `MINIO_ROOT_PASSWORD`.
- Export `minioClient` and `MINIO_BUCKET` constant.
- On first use, create the bucket if it does not exist (`bucketExists` + `makeBucket`).
### Upload API route (`src/app/api/uploads/route.ts`)
- `POST /api/uploads` — accepts `multipart/form-data` with a single `file` field.
- Validates: authenticated session required (401 if not); max file size 5 MB (413 if exceeded); MIME type must match `image/*` (415 if not).
- Generates a storage key: `garden/<householdId>/<randomUUID>.<ext>`.
- Streams to MinIO via `putObject`.
- Returns `{ url: "/api/uploads/<key>" }`.
- `GET /api/uploads/[...key]` — proxies the object back from MinIO using `getObject`. Sets `Cache-Control: public, max-age=31536000, immutable`.
This route is generic — not garden-specific. Other modules can reuse it.
### Schema (`src/modules/garden/schema.ts`)
Four tables, all `household_id`-scoped:
**`garden_containers`**
- `id` uuid pk
- `household_id` fk households cascade
- `name` text not null
- `type` text not null default `'other'` — free text, convention: `'shelf' | 'terrarium' | 'raised-bed' | 'window-box' | 'single-pot' | 'outdoor' | 'other'`
- `location_notes` text nullable
- `cover_image_url` text nullable
- `created_at`, `updated_at` timestamptz
Index on `household_id`.
**`garden_plants`**
- `id` uuid pk
- `household_id` fk households cascade
- `container_id` uuid nullable fk `garden_containers` set-null on delete
- `name` text not null
- `scientific_name` text nullable
- `species_id` text nullable — external Perenual species ID, stored as string
- `category` text not null default `'other'` — free text, convention: `'succulent' | 'tropical' | 'herb' | 'vegetable' | 'tree' | 'flower' | 'other'`
- `notes` text nullable
- `acquisition_date` date nullable
- `growth_stage` text nullable — convention: `'seedling' | 'juvenile' | 'mature' | 'flowering' | 'fruiting' | 'dormant'`
- `health_status` text not null default `'healthy'` — convention: `'healthy' | 'stressed' | 'sick' | 'dormant'`
- `sunlight` text nullable
- `watering_notes` text nullable
- `fertilizing_notes` text nullable
- `primary_image_url` text nullable
- `images` jsonb not null default `'[]'` — typed as `string[]`, stores upload URL paths
- `created_at`, `updated_at` timestamptz
Indexes on `(household_id)`, `(household_id, container_id)`.
**`garden_care_logs`**
- `id` uuid pk
- `plant_id` uuid fk `garden_plants` cascade
- `household_id` fk households cascade
- `care_type` text not null — convention: `'watered' | 'fertilized' | 'repotted' | 'pruned' | 'misted' | 'inspected' | 'treated' | 'propagated' | 'custom'`
- `performed_by` uuid fk users set-null on delete
- `notes` text nullable
- `performed_at` timestamptz not null default now()
- `created_at` timestamptz
Indexes on `(plant_id, performed_at desc)`, `(household_id)`.
**`garden_care_schedules`**
- `id` uuid pk
- `plant_id` uuid fk `garden_plants` cascade
- `household_id` fk households cascade
- `care_type` text not null
- `interval_days` int not null
- `last_performed_at` timestamptz nullable
- `next_due_at` timestamptz nullable — recomputed after every care log entry
- `enabled` boolean not null default true
- `created_at`, `updated_at` timestamptz
Unique index on `(plant_id, care_type)` — one schedule per plant per care type.
Index on `(household_id, next_due_at)` for dashboard queries.
### Drizzle migration
Generate and commit under `drizzle/`. Run `pnpm db:migrate` to apply.
### Module scaffold (`src/modules/garden/`)
Create the directory with stubs:
- `schema.ts` (complete, from above)
- `manifest.tsx` (minimal stub: `id: "garden"`, `name: "Garden"`, empty `entities: []`)
- `server/actions.ts` (empty stub)
- `server/queries.ts` (empty stub)
Register in `src/modules/index.ts`:
```typescript
import gardenManifest from "./garden/manifest";
registerModule(gardenManifest);
```
### Environment
Add to `.env.example`:
```
MINIO_ENDPOINT=http://localhost:9000
MINIO_ROOT_USER=famapp
MINIO_ROOT_PASSWORD=changeme
MINIO_BUCKET=garden
PERENUAL_API_KEY= # filled in task 72
```
## Out of scope
- Any garden-specific UI.
- Perenual API integration (task 72).
- Care logic (tasks 7374).
## Acceptance criteria
- [ ] `docker compose up minio` starts and passes health-check.
- [ ] `POST /api/uploads` rejects unauthenticated requests with 401.
- [ ] `POST /api/uploads` rejects files > 5 MB with 413.
- [ ] `POST /api/uploads` accepts a valid JPEG and returns `{ url: "..." }`; `GET` of that URL returns the image bytes.
- [ ] `pnpm db:migrate` applies cleanly; all four tables exist with the correct columns.
- [ ] `garden` module appears in `/debug/registry`.
+82
View File
@@ -0,0 +1,82 @@
# 71 — Garden containers
## Goal
Implement full CRUD for **containers** — the grouping layer above individual plants (shelves, terrariums, raised beds, etc.). A container has a name, type, location notes, and an optional cover photo.
## Depends on
- 70 (garden infrastructure — schema, MinIO, upload route)
## Scope
### Server (`src/modules/garden/server/`)
Add to `actions.ts`:
- `createContainer(input: { name, type, locationNotes?, coverImageUrl? })` — Zod-validated, `getCurrentSession`, insert, `logActivity`, `revalidatePath("/garden")`.
- `updateContainer(input: { id, name?, type?, locationNotes?, coverImageUrl? })` — patch, household membership check, logActivity.
- `deleteContainer(input: { id })` — household membership check; plants with this `container_id` have it set to null (handled by schema `ON DELETE SET NULL`); logActivity; revalidatePath.
Add to `queries.ts`:
- `listContainers()` — returns all containers for the current household with a computed `plantCount`.
- `getContainer(id)` — returns the container + all its plants (with last-watered date derived from care logs — use a lateral join or subquery).
### UI (`src/modules/garden/components/`)
**`container-list.tsx`** (server component)
- Grid of cards. Each card: cover photo (placeholder icon if none), name, type badge, plant count.
- "New container" button → sheet/dialog.
**`container-detail.tsx`** (server component)
- Header: cover photo, name, type, location notes, edit/delete buttons.
- Plant grid (placeholder for now — task 72 fills in the plant cards).
- "+ Add plant to this container" button — links to `/garden/plants/new?containerId=<id>`.
**`container-form.tsx`** (client component)
- Fields: name (required), type (select — 7 options), location notes (textarea), cover photo (file input → `POST /api/uploads` → stores returned URL).
- Used for both create and edit via an optional `existing` prop.
### Pages (`src/app/garden/`)
- `page.tsx``/garden` root page: two tabs — "Plants" (placeholder for task 72) and "Containers". Containers tab renders `<ContainerList />`.
- `containers/[id]/page.tsx` — renders `<ContainerDetail />`.
- `containers/new/page.tsx` — renders `<ContainerForm />` in create mode; redirects to `/garden` on success.
### Nav
Add `/garden` to the bottom nav and sidebar. Use the `sprout` Lucide icon (or nearest available). Register in the garden manifest:
```typescript
nav: { href: "/garden", label: "Garden", icon: "sprout" }
```
### Activity log
`renderActivity` for `garden.container` entity type in the manifest:
- `create``Created container "${name}"`
- `update``Updated container "${name}"`
- `delete``Deleted container`
### Share links
Containers are shareable (read-only). Add `loadForShare` and `renderSharedView` to the entity registration so a share link shows the container's name, type, location notes, cover photo, and plant names. Add `loadContainerForShare(id)` in `src/modules/garden/server/share-queries.ts`.
## Out of scope
- Plant cards inside the container detail (task 72 fills those in).
- Care tracking (tasks 7374).
## Acceptance criteria
- [ ] Create / edit / delete containers works end-to-end.
- [ ] Cover photo uploads to MinIO and renders on the card and detail page.
- [ ] Deleting a container nullifies `container_id` on its plants rather than deleting the plants.
- [ ] `/garden` page renders with a Containers tab.
- [ ] `garden.container` entity is registered with share support in the manifest.
- [ ] Activity log entries appear for create / update / delete.
+117
View File
@@ -0,0 +1,117 @@
# 72 — Garden plants
## Goal
Implement full CRUD for individual **plants**. Each plant has a name, category, care notes, health status, up to 10 photos, an optional container assignment, and species data pulled from the **Perenual API** when the user searches for a known species.
## Depends on
- 70 (schema, MinIO, upload route), 71 (containers — container assignment picker)
## Scope
### Perenual API wrapper (`src/modules/garden/server/species-lookup.ts`)
Perenual (perenual.com) provides a free-tier plant species API. Key endpoint: `GET /api/species-list?key=<KEY>&q=<query>`.
Implement:
```typescript
export type SpeciesSuggestion = {
id: string;
common_name: string;
scientific_name: string;
watering: string; // e.g. "frequent", "average", "minimum"
sunlight: string[]; // e.g. ["full sun", "part shade"]
cycle: string; // e.g. "Perennial"
default_image_url: string | null;
};
export async function searchSpecies(query: string): Promise<SpeciesSuggestion[]>;
export async function getSpeciesById(id: string): Promise<SpeciesSuggestion | null>;
```
Cache results for 24 hours in a `garden_species_cache` table (columns: `species_id` text pk, `data` jsonb, `cached_at` timestamptz). Add this table to the schema in `src/modules/garden/schema.ts` and include it in the migration from task 70 (or add a new migration).
If the API is unreachable or returns an error, log the failure and return `[]` / `null`. `PERENUAL_API_KEY` from env; if absent, `searchSpecies` returns `[]` silently so the app works without the key.
### Server (`src/modules/garden/server/`)
Add to `actions.ts`:
- `createPlant(input)` — Zod-validated, `getCurrentSession`, insert, `logActivity`, `revalidatePath("/garden")`.
- `updatePlant(input: { id, ...partials })` — patch, household check, logActivity.
- `deletePlant(input: { id })` — household check, logActivity; care logs + schedules cascade-delete via DB.
- `addPlantImage(input: { id, url })` — appends URL to `images` jsonb array; reject if already 10 images.
- `removePlantImage(input: { id, url })` — removes URL from array; if it was `primary_image_url`, set primary to first remaining or null.
- `setPrimaryImage(input: { id, url })` — sets `primary_image_url`; url must already be in `images`.
Add to `queries.ts`:
- `listPlants({ containerId? })` — all plants in household optionally filtered by container. Include last-care timestamps per type via a lateral subquery.
- `getPlant(id)` — full plant data + container name + care log summary (last 5 entries) + active schedules.
### UI (`src/modules/garden/components/`)
**`plant-list.tsx`** (server component)
- Grouped by container first; "Unassigned" group for plants with no container.
- Each card: primary image thumbnail, name, health badge, "last watered X days ago", overdue care indicator.
- Replaces the placeholder in the "Plants" tab on `/garden/page.tsx` from task 71.
**`plant-detail.tsx`** (server component)
- Three-tab layout: **Info**, **Gallery**, **Care** (Care tab filled in by task 73).
- Info tab: all fields, container link, health/stage badges, species info.
- Gallery tab: photo grid, primary image star-toggle, delete individual image, upload new image.
**`plant-form.tsx`** (client component)
- Fields: name (required), category (select), container (select, nullable), health status (select), growth stage (select).
- Species search combobox: debounced search → `searchSpecies` → select → auto-fills scientific name, sunlight, watering notes. User can override.
- Care notes textareas: watering notes, fertilizing notes, general notes.
- Acquisition date picker.
- Image uploader: drag-and-drop or click, previews, max 10. First uploaded image auto-set as primary.
- `containerId` query-param pre-fill (from task 71 "Add plant to container" button).
**`species-search.tsx`** (client component)
- Debounced combobox calling a `/api/garden/species-search` route handler. Fires `onSelect(suggestion)` on pick.
### Pages (`src/app/garden/`)
- `plants/new/page.tsx``<PlantForm />` in create mode.
- `plants/[id]/page.tsx``<PlantDetail />` with edit/delete controls.
- `plants/[id]/edit/page.tsx``<PlantForm />` in edit mode.
### Activity log
`renderActivity` for `garden.plant`:
- `create``Added plant "${name}"`
- `update``Updated "${name}"`
- `delete``Removed plant "${name}"`
### Search
Register `search` on the `garden.plant` entity using `ilike` on `name || ' ' || coalesce(scientific_name, '')`.
### Share links
Plants are shareable (read-only). The shared view shows name, scientific name, primary image, gallery, health status, and care notes. Add `loadPlantForShare(id)` in `src/modules/garden/server/share-queries.ts`.
## Out of scope
- Care log UI and schedules (task 73).
- Dashboard widgets (task 75).
## Acceptance criteria
- [ ] Create / edit / delete plants works end-to-end.
- [ ] Species search returns Perenual results and auto-fills form fields on selection.
- [ ] App works correctly via manual entry when `PERENUAL_API_KEY` is absent.
- [ ] Up to 10 images upload; primary image can be set and changed; individual images can be removed.
- [ ] Plant list on `/garden` groups by container with an "Unassigned" bucket.
- [ ] `garden.plant` entity is registered with search and share support.
- [ ] Activity log entries appear for create / update / delete.
- [ ] Plant share link renders the read-only view correctly.
+75
View File
@@ -0,0 +1,75 @@
# 73 — Garden care tracking
## Goal
Implement the **care log** and **care schedule** systems. Users can log a care event for any plant (watered, fertilized, repotted, etc.), set up recurring schedules with an interval, and receive reminders when care is due.
## Depends on
- 70 (schema), 72 (plants exist to attach care records to)
- 41 (reminders system — `scheduleReminder` / `cancelReminder`)
## Scope
### Care log actions (`src/modules/garden/server/actions.ts`)
- `logCare(input: { plantId, careType, notes?, performedAt? })` — Zod-validated; `performedAt` defaults to now(). Insert into `garden_care_logs`. After inserting: call `updateScheduleAfterCare(plantId, careType)`, call `logActivity`, `revalidatePath`.
- `deleteCareLog(input: { id })` — household check, delete.
### Care schedule actions (`src/modules/garden/server/actions.ts`)
- `upsertCareSchedule(input: { plantId, careType, intervalDays, enabled? })` — upsert on `(plant_id, care_type)`. Recompute `next_due_at`: if `last_performed_at` exists use `last_performed_at + intervalDays`, else `now() + intervalDays`. Wire reminder: `scheduleReminder({ entityType: "garden.schedule", entityId: scheduleRow.id, fireAt: next_due_at })`.
- `deleteCareSchedule(input: { id })``cancelReminder("garden.schedule", id)`, delete.
- `toggleCareSchedule(input: { id, enabled })` — flip `enabled`; cancel reminder if disabling, reschedule if enabling.
### Schedule update helper (`src/modules/garden/server/care-schedule.ts`)
`updateScheduleAfterCare(plantId, careType)` — finds the schedule row, sets `last_performed_at = now()`, `next_due_at = now() + interval_days`, cancels old reminder, schedules new one.
Uses `entityType = "garden.schedule"` + `entityId = schedule.id` to satisfy the unique constraint on `(entity_type, entity_id)` in the reminders table — one reminder per schedule row, not per plant.
### Queries (`src/modules/garden/server/queries.ts`)
- `getCareLogs(plantId, limit?)` — most recent N logs ordered `performed_at desc`.
- `getCareSchedules(plantId)` — all schedules with computed `daysUntilDue` and `isOverdue`.
- `getOverduePlants(householdId)` — plants with at least one enabled schedule where `next_due_at < now()`, sorted most-overdue first.
- `getCareDueSoon(householdId, withinDays)` — plants with care due within N days.
### UI (`src/modules/garden/components/`)
**`care-log-form.tsx`** (client component) — plant picker + care type select + optional notes + optional performed-at datetime (defaults to now). Used as a sheet and inline in the plant detail Care tab.
**`care-schedule-editor.tsx`** (client component) — list of active schedules per plant (care type, interval, next due, enabled toggle, delete). "Add schedule" form with care type + interval days.
**`care-history-list.tsx`** (server component) — chronological log entries: care type icon, "X days ago", performed-by avatar, notes.
### Plant detail Care tab (update `plant-detail.tsx` from task 72)
The Care tab (previously placeholder) renders: `<CareScheduleEditor />` → "Log care" button → `<CareHistoryList />`.
### Quick-add (update manifest)
```typescript
{
id: "garden.log-care",
label: "Log plant care",
icon: "droplets",
url: "/garden",
}
```
## Out of scope
- Calendar/lists integration (task 74).
- Dashboard widget (task 75).
## Acceptance criteria
- [ ] Logging care inserts a log row and updates `last_performed_at` + `next_due_at` on the matching schedule.
- [ ] Creating a schedule with interval 7 sets `next_due_at` to 7 days from now; a reminder is scheduled.
- [ ] After logging care, old reminder is cancelled and a new one scheduled.
- [ ] Disabling a schedule cancels its reminder; re-enabling reschedules it.
- [ ] Deleting a schedule cancels its reminder.
- [ ] `getOverduePlants` returns correctly sorted results.
- [ ] Care tab in plant detail shows schedule editor, log form, and history.
- [ ] "Log plant care" appears in the quick-add sheet.
+83
View File
@@ -0,0 +1,83 @@
# 74 — Garden integrations (calendar + lists)
## Goal
Wire the garden module into the two existing coordination modules:
1. **Calendar**: schedule a plant care event on the household calendar from within a care schedule row.
2. **Lists**: push all overdue care tasks to the household task list in one tap.
## Depends on
- 73 (care schedules + overdue queries)
- 10 (calendar module — `createEvent`)
- 11 (lists module — `addItem`)
## Scope
### Calendar integration
#### Server action (`src/modules/garden/server/actions.ts`)
`scheduleOnCalendar(input: { scheduleId, calendarId, reminderMinutesBefore? })`:
- Look up the schedule + plant; household check.
- `startAt` = `next_due_at` (reject with user-facing error if null).
- `endAt` = `startAt + 30 min`; `allDay = false`.
- Title convention: `"Water ${plant.name}"` / `"Fertilize ${plant.name}"` / `"Repot ${plant.name}"` / `"${careType} — ${plant.name}"` for other types.
- Notes: `"Scheduled from garden. Next due: ${next_due_at.toLocaleDateString()}"`.
- Call `createCalendarEvent(...)` from the bridge below.
#### Bridge file (`src/modules/garden/server/calendar-bridge.ts`)
```typescript
export { createEvent as createCalendarEvent } from "@/modules/calendar/server/actions";
export { listCalendars } from "@/modules/calendar/server/queries";
```
This keeps the cross-module dependency explicit and swappable without touching `_core`.
#### UI
In `care-schedule-editor.tsx`, add an "Add to calendar" button per schedule row. Clicking it opens a popover with: calendar select (from `listCalendars`) + optional reminder-minutes input + "Schedule" button. Show a success toast linking to `/calendar`.
---
### Lists integration
#### Server action (`src/modules/garden/server/actions.ts`)
`pushOverdueToTaskList(): Promise<{ added: number }>`:
- Call `getOverduePlants(householdId)`.
- Find the household default task list via the bridge below.
- For each overdue `(plant, schedule)` pair insert a list item:
- `text`: same title convention as the calendar integration.
- `notes`: `"Overdue by ${daysOverdue} day(s)"`.
- `dueAt`: `schedule.next_due_at`.
- Skip pairs where an identical `text` item already exists in the list (prevent duplicates).
- Return `{ added: N }`.
#### Bridge file (`src/modules/garden/server/lists-bridge.ts`)
```typescript
export { addItem as addListItem } from "@/modules/lists/server/actions";
export { listLists } from "@/modules/lists/server/queries";
```
#### UI
Add an "Add overdue to task list" button to the `/garden` page header (available before the dashboard widget in task 75). Shows a toast: "Added N tasks to your task list." If N = 0, toast says "No overdue care tasks."
## Out of scope
- Bi-directional sync (checking off a list item does not mark the plant as cared-for).
- Recurring calendar events (garden creates single events only).
## Acceptance criteria
- [ ] "Add to calendar" creates a calendar event visible at `/calendar` with the correct title.
- [ ] "Add overdue to task list" pushes one item per overdue schedule, skips existing duplicates.
- [ ] Items appear in the task list at `/lists`.
- [ ] Both actions enforce household scope.
- [ ] Both are graceful no-ops when nothing is overdue / due.
+144
View File
@@ -0,0 +1,144 @@
# 75 — Garden dashboard, widgets, and manifest completion
## Goal
Complete the garden module: full manifest registration, two dashboard widgets, search integration, quick-add polish, and a Playwright happy-path test.
## Depends on
- 7074 (all previous garden tasks)
## Scope
### Manifest completion (`src/modules/garden/manifest.tsx`)
Replace the task-70 stub with the full manifest.
**Entities:**
```typescript
entities: [
{
type: "garden.container",
label: { singular: "Container", plural: "Containers" },
share: { canShare: true, defaultCapabilities: ["read"] },
search: { search: searchContainers },
resolveUrl: (id) => `/garden/containers/${id}`,
loadForShare: loadContainerForShare,
renderSharedView: ...,
renderActivity: ...,
},
{
type: "garden.plant",
label: { singular: "Plant", plural: "Plants" },
share: { canShare: true, defaultCapabilities: ["read"] },
search: { search: searchPlants },
resolveUrl: (id) => `/garden/plants/${id}`,
loadForShare: loadPlantForShare,
renderSharedView: ...,
renderActivity: ...,
},
]
```
`garden.schedule` is internal (reminders only) — not registered as a shareable or searchable entity.
**Quick adds** (consolidate from tasks 7173):
- `{ id: "garden.add-plant", label: "Add plant", icon: "leaf", url: "/garden/plants/new" }`
- `{ id: "garden.add-container", label: "Add container", icon: "box", url: "/garden/containers/new" }`
- `{ id: "garden.log-care", label: "Log plant care", icon: "droplets", url: "/garden?logCare=1" }`
**Nav**: `{ href: "/garden", label: "Garden", icon: "sprout" }`.
---
### Widget 1: `garden.care-due`
**Title**: "Plants needing care" | **Category**: "Garden"
**Default size**: `{ w: 4, h: 4 }` | **Min size**: `{ w: 3, h: 2 }`
Config schema:
```typescript
z.object({
containerIds: z.union([z.literal("all"), z.array(z.string().uuid())]),
daysAhead: z.number().int().min(0).max(30).default(0),
});
```
Default config: `{ containerIds: "all", daysAhead: 0 }`.
`resolveConfigOptions`: returns `{ containers: [{ id, name }] }`.
Render:
- Empty state if nothing is due: "All plants are on schedule."
- Otherwise: compact list sorted by days overdue. Each row: plant name, care type icon, urgency badge ("X days overdue" / "due today"), inline "Log care" button (calls `logCare` action + revalidates — no navigation).
- Truncate at 10 rows; "View all" link to `/garden`.
- Rows with `next_due_at` within `daysAhead` days show as upcoming in a lighter style below overdue rows.
---
### Widget 2: `garden.overview`
**Title**: "Garden overview" | **Category**: "Garden"
**Default size**: `{ w: 3, h: 2 }` | **Min size**: `{ w: 2, h: 2 }`
Config schema: `z.object({})`.
Render:
- Stat row: total plants, total containers, overdue care count.
- "Next care" line: "Next: water [Plant] in N days" / "today" / "overdue".
- Link to `/garden`.
---
### Widget component (`src/modules/garden/components/plant-widget.tsx`)
Server component implementing both widgets, following the pattern in `src/modules/lists/components/list-widget.tsx`.
---
### Search adapters
Implement `searchContainers` and `searchPlants` using `ilike` on name fields, returning `SearchResult[]`. Both appear in the command palette.
---
### Notification body improvement (optional)
If `tickReminders` in `src/modules/_core/reminders.ts` can be extended without structural changes — add a registry of entity-type resolvers and register `"garden.schedule"` to resolve to `"Time to water [plant name]"`. If it requires core changes, defer and note as known limitation.
---
### Playwright E2E test (`tests/garden.spec.ts`)
Happy path:
1. Log in as the seeded user.
2. Create container "Living Room Shelf".
3. Create plant "Pothos" in that container (manual entry, no species lookup).
4. Add watering schedule: every 7 days.
5. Log care: watered.
6. Verify schedule `next_due_at` updates to ~7 days from now.
7. Confirm plant appears grouped under "Living Room Shelf" on `/garden`.
8. Add `garden.care-due` widget to the default dashboard.
9. Confirm no overdue items (just watered).
## Out of scope
- Health trend charts.
- Weather-based watering adjustments.
- Social/community features.
## Acceptance criteria
- [ ] Both widgets register and appear in the widget picker.
- [ ] `garden.care-due` shows overdue plants sorted by urgency; inline log button works.
- [ ] `garden.overview` shows correct counts.
- [ ] Both entities appear in command palette search.
- [ ] All three quick-adds appear in the `+` sheet.
- [ ] Garden nav link appears in sidebar and bottom nav.
- [ ] Playwright happy-path test passes.
+10
View File
@@ -33,6 +33,7 @@ Every task file has these sections:
- [06 — Authentik install + OIDC integration](06-authentik-oidc.md)
- [07 — Household seeding & session](07-household-seed.md)
- [08 — Theming infrastructure (multi-theme + dark mode)](08-theming.md)
- [09 — Pre-deploy checklist (recurring)](09-pre-deploy-checklist.md)
### Phase 2 — Core modules
@@ -69,3 +70,12 @@ Every task file has these sections:
- [60 — Postgres backups (pg_dump cron)](60-backups.md)
- [61 — Rate limiting on share links](61-rate-limit.md)
- [62 — Structured logging](62-logging.md)
### Phase 8 — Garden module
- [70 — Garden infrastructure (MinIO + upload route + schema)](70-garden-infrastructure.md)
- [71 — Garden containers](71-garden-containers.md)
- [72 — Garden plants](72-garden-plants.md)
- [73 — Garden care tracking](73-garden-care-tracking.md)
- [74 — Garden integrations](74-garden-integrations.md)
- [75 — Garden dashboard](75-garden-dashboard.md)
+7
View File
@@ -0,0 +1,7 @@
ALTER TABLE "users" ADD COLUMN "theme_palette" text NOT NULL DEFAULT 'clay';--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "theme_font_pair" text NOT NULL DEFAULT 'serif-sans';--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "theme_density" text NOT NULL DEFAULT 'regular';--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "theme_dash_layout" text NOT NULL DEFAULT 'classic';--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "theme_cal_view" text NOT NULL DEFAULT 'month';--> statement-breakpoint
ALTER TABLE "users" ADD COLUMN "theme_nav_style" text NOT NULL DEFAULT 'rail-desktop';--> statement-breakpoint
ALTER TABLE "users" DROP COLUMN IF EXISTS "theme";
+74
View File
@@ -0,0 +1,74 @@
-- Task 70: Garden module — containers, plants, care logs, care schedules, species cache
CREATE TABLE "garden_containers" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"household_id" uuid NOT NULL REFERENCES "households"("id") ON DELETE CASCADE,
"name" text NOT NULL,
"type" text NOT NULL DEFAULT 'other',
"location_notes" text,
"cover_image_url" text,
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
);
CREATE INDEX "garden_containers_household_idx" ON "garden_containers" ("household_id");
CREATE TABLE "garden_plants" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"household_id" uuid NOT NULL REFERENCES "households"("id") ON DELETE CASCADE,
"container_id" uuid REFERENCES "garden_containers"("id") ON DELETE SET NULL,
"name" text NOT NULL,
"scientific_name" text,
"species_id" text,
"category" text NOT NULL DEFAULT 'other',
"notes" text,
"acquisition_date" date,
"growth_stage" text,
"health_status" text NOT NULL DEFAULT 'healthy',
"sunlight" text,
"watering_notes" text,
"fertilizing_notes" text,
"primary_image_url" text,
"images" jsonb NOT NULL DEFAULT '[]',
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
);
CREATE INDEX "garden_plants_household_idx" ON "garden_plants" ("household_id");
CREATE INDEX "garden_plants_household_container_idx" ON "garden_plants" ("household_id", "container_id");
CREATE TABLE "garden_care_logs" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"plant_id" uuid NOT NULL REFERENCES "garden_plants"("id") ON DELETE CASCADE,
"household_id" uuid NOT NULL REFERENCES "households"("id") ON DELETE CASCADE,
"care_type" text NOT NULL,
"performed_by" uuid REFERENCES "users"("id") ON DELETE SET NULL,
"notes" text,
"performed_at" timestamp with time zone NOT NULL DEFAULT now(),
"created_at" timestamp with time zone NOT NULL DEFAULT now()
);
CREATE INDEX "garden_care_logs_plant_performed_idx" ON "garden_care_logs" ("plant_id", "performed_at");
CREATE INDEX "garden_care_logs_household_idx" ON "garden_care_logs" ("household_id");
CREATE TABLE "garden_care_schedules" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"plant_id" uuid NOT NULL REFERENCES "garden_plants"("id") ON DELETE CASCADE,
"household_id" uuid NOT NULL REFERENCES "households"("id") ON DELETE CASCADE,
"care_type" text NOT NULL,
"interval_days" integer NOT NULL,
"last_performed_at" timestamp with time zone,
"next_due_at" timestamp with time zone,
"enabled" boolean NOT NULL DEFAULT true,
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX "garden_care_schedules_plant_type_uq" ON "garden_care_schedules" ("plant_id", "care_type");
CREATE INDEX "garden_care_schedules_household_due_idx" ON "garden_care_schedules" ("household_id", "next_due_at");
CREATE TABLE "garden_species_cache" (
"species_id" text PRIMARY KEY NOT NULL,
"data" jsonb NOT NULL,
"cached_at" timestamp with time zone NOT NULL DEFAULT now()
);
+6
View File
@@ -0,0 +1,6 @@
-- Add title/body to reminders for rich notification bodies
ALTER TABLE reminders ADD COLUMN IF NOT EXISTS title text;
ALTER TABLE reminders ADD COLUMN IF NOT EXISTS body text;
-- Add metadata to list_items for garden task linking
ALTER TABLE list_items ADD COLUMN IF NOT EXISTS metadata jsonb;
+13
View File
@@ -0,0 +1,13 @@
CREATE TABLE "bang_events" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"household_id" uuid NOT NULL,
"recorded_by" uuid,
"occurred_on" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "bang_events" ADD CONSTRAINT "bang_events_household_id_households_id_fk" FOREIGN KEY ("household_id") REFERENCES "public"."households"("id") ON DELETE cascade ON UPDATE no action;
--> statement-breakpoint
ALTER TABLE "bang_events" ADD CONSTRAINT "bang_events_recorded_by_users_id_fk" FOREIGN KEY ("recorded_by") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
--> statement-breakpoint
CREATE INDEX "bang_events_household_occurred_idx" ON "bang_events" USING btree ("household_id","occurred_on");
+1
View File
@@ -0,0 +1 @@
ALTER TABLE "garden_containers" ADD COLUMN "images" jsonb DEFAULT '[]'::jsonb NOT NULL;
+2 -2
View File
@@ -1,6 +1,6 @@
{
"id": "fc208bad-8bfd-452d-876f-7e853f699931",
"prevId": "cb06cd57-d5a0-4fb7-bbf3-335173a1168c",
"id": "ff1f5ff1-7539-4c5e-a20d-f01c719ef198",
"prevId": "fc208bad-8bfd-452d-876f-7e853f699931",
"version": "7",
"dialect": "postgresql",
"tables": {
File diff suppressed because it is too large Load Diff
+35
View File
@@ -99,6 +99,41 @@
"when": 1778400000000,
"tag": "0013_push_notify_reminders",
"breakpoints": true
},
{
"idx": 14,
"version": "7",
"when": 1778600000000,
"tag": "0014_paper_ink_theme",
"breakpoints": true
},
{
"idx": 15,
"version": "7",
"when": 1748736000000,
"tag": "0015_garden_schema",
"breakpoints": true
},
{
"idx": 16,
"version": "7",
"when": 1748822400000,
"tag": "0016_garden_improvements",
"breakpoints": true
},
{
"idx": 17,
"version": "7",
"when": 1780391596552,
"tag": "0017_bang_counter",
"breakpoints": true
},
{
"idx": 18,
"version": "7",
"when": 1748995200000,
"tag": "0018_container_images",
"breakpoints": true
}
]
}
+9 -1
View File
@@ -5,7 +5,15 @@ import nextConfig from "eslint-config-next/core-web-vitals";
export default tseslint.config(
{
ignores: ["node_modules/**", ".next/**", ".claude/**", "dist/**", "drizzle/**", "public/sw.js"],
ignores: [
"node_modules/**",
".next/**",
".claude/**",
".design-tmp/**",
"dist/**",
"drizzle/**",
"public/sw.js",
],
},
js.configs.recommended,
...tseslint.configs.recommended,
+38 -9
View File
@@ -1,14 +1,17 @@
{
"name": "famapp",
"version": "0.0.0",
"version": "0.5.1",
"private": true,
"type": "module",
"packageManager": "pnpm@10.33.3",
"engines": {
"node": ">=22"
"node": ">=24"
},
"scripts": {
"dev": "next dev",
"dev:network": "next dev --hostname 0.0.0.0",
"dev:local": "node scripts/dev.mjs",
"dev:reset": "node scripts/dev-reset.mjs",
"build": "next build",
"start": "next start",
"lint": "eslint .",
@@ -19,27 +22,51 @@
"typecheck": "tsc --noEmit",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:seed": "tsx --env-file=.env scripts/seed.ts",
"db:seed": "node --env-file=.env scripts/seed.mjs",
"db:studio": "drizzle-kit studio",
"gen:icons": "node scripts/generate-icons.mjs",
"vapid:generate": "node scripts/vapid-generate.mjs"
"vapid:generate": "node scripts/vapid-generate.mjs",
"prepare": "husky",
"release": "dotenv -e .env -- release-it",
"release:patch": "dotenv -e .env -- release-it patch",
"release:minor": "dotenv -e .env -- release-it minor",
"release:major": "dotenv -e .env -- release-it major",
"release:dry": "dotenv -e .env -- release-it --dry-run"
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write"
],
"*.{js,mjs,cjs}": [
"prettier --write"
],
"*.{json,md,css,yaml,yml}": [
"prettier --write"
]
},
"devDependencies": {
"@eslint/eslintrc": "^3.3.5",
"@commitlint/cli": "^21.0.2",
"@commitlint/config-conventional": "^21.0.2",
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.59.1",
"@release-it/conventional-changelog": "^11.0.1",
"@tailwindcss/postcss": "^4.2.4",
"@types/node": "^22.9.0",
"@types/canvas-confetti": "^1.9.0",
"@types/node": "^24.0.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@types/react-grid-layout": "^2.1.0",
"@types/web-push": "^3.6.4",
"dotenv-cli": "^11.0.0",
"drizzle-kit": "^0.31.10",
"eslint": "^9.15.0",
"eslint-config-next": "^16.2.4",
"globals": "^15.12.0",
"husky": "^9.1.7",
"lint-staged": "^17.0.7",
"pino-pretty": "^13.1.3",
"prettier": "^3.3.3",
"release-it": "^20.2.0",
"tailwindcss": "^4.2.4",
"tsx": "^4.19.4",
"typescript": "^5.6.3",
@@ -51,13 +78,16 @@
"@fullcalendar/core": "^6.1.20",
"@fullcalendar/daygrid": "^6.1.20",
"@fullcalendar/interaction": "^6.1.20",
"@fullcalendar/list": "^6.1.20",
"@fullcalendar/react": "^6.1.20",
"@fullcalendar/timegrid": "^6.1.20",
"canvas-confetti": "^1.9.4",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"drizzle-orm": "^0.45.2",
"lucide-react": "^1.14.0",
"minio": "^8.0.7",
"next": "^15.5.15",
"next-auth": "5.0.0-beta.31",
"pino": "^10.3.1",
@@ -69,7 +99,6 @@
"tailwind-merge": "^3.5.0",
"tw-animate-css": "^1.4.0",
"web-push": "^3.6.7",
"zod": "^4.4.3",
"zod-to-json-schema": "^3.25.2"
"zod": "^4.4.3"
}
}
+1990 -51
View File
File diff suppressed because it is too large Load Diff
+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<style>
@media (prefers-color-scheme: dark) { .bg { fill: #6366F1; } }
</style>
<rect class="bg" width="512" height="512" rx="96" fill="#4338CA"/>
<rect x="130" y="238" width="252" height="190" fill="white"/>
<polygon points="256,82 68,254 444,254" fill="white"/>
<rect x="216" y="338" width="80" height="90" rx="8" fill="#4338CA"/>
</svg>

After

Width:  |  Height:  |  Size: 444 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 335 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 496 B

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 547 B

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 546 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 13 KiB

+4 -10
View File
@@ -1,12 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
<!-- Background -->
<rect width="512" height="512" rx="80" fill="#4F46E5"/>
<!-- House body -->
<polygon points="256,108 396,234 364,234 364,392 148,392 148,234 116,234" fill="white"/>
<!-- Door -->
<rect x="212" y="296" width="88" height="96" rx="6" fill="#4F46E5"/>
<!-- Left window -->
<rect x="164" y="254" width="66" height="54" rx="6" fill="#4F46E5" opacity="0.55"/>
<!-- Right window -->
<rect x="282" y="254" width="66" height="54" rx="6" fill="#4F46E5" opacity="0.55"/>
<rect width="512" height="512" rx="96" fill="#4338CA"/>
<rect x="130" y="238" width="252" height="190" fill="white"/>
<polygon points="256,82 68,254 444,254" fill="white"/>
<rect x="216" y="338" width="80" height="90" rx="8" fill="#4338CA"/>
</svg>

Before

Width:  |  Height:  |  Size: 594 B

After

Width:  |  Height:  |  Size: 345 B

+8 -5
View File
@@ -4,23 +4,26 @@
"description": "Family coordination app",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#4F46E5",
"background_color": "#4338CA",
"theme_color": "#4338CA",
"icons": [
{
"src": "/icon-192.png",
"sizes": "192x192",
"type": "image/png"
"type": "image/png",
"purpose": "any"
},
{
"src": "/icon-384.png",
"sizes": "384x384",
"type": "image/png"
"type": "image/png",
"purpose": "any"
},
{
"src": "/icon-512.png",
"sizes": "512x512",
"type": "image/png"
"type": "image/png",
"purpose": "any"
},
{
"src": "/icon-512-maskable.png",
+24
View File
@@ -0,0 +1,24 @@
/**
* Dev environment reset script.
*
* Tears down the local Postgres container and deletes its volume (all local
* data is lost), then performs a fresh startup: container up, migrate, seed,
* Next.js dev server.
*
* Use this when you want a completely clean local database e.g. after a
* destructive schema change or to reproduce a fresh-install scenario.
*
* Usage: pnpm dev:reset
*/
import { execSync } from "child_process";
import { main } from "./dev.mjs";
console.log("\n⚠ Resetting dev environment — all local data will be deleted.");
execSync("docker compose -f docker-compose.dev.yaml down -v", {
stdio: "inherit",
shell: true,
});
console.log("\n▸ Restarting from scratch...");
await main();
+114
View File
@@ -0,0 +1,114 @@
/**
* Dev environment startup script.
*
* Starts the local Postgres container, waits for it to be ready, runs
* migrations + seed, then spawns `next dev` bound to 0.0.0.0 so the app
* is reachable from other devices on the LAN.
*
* Usage: pnpm dev:local
*/
import { execSync, spawn } from "child_process";
import net from "net";
import os from "os";
import { fileURLToPath } from "url";
/** Return the first LAN IPv4 address (prefers 192.168.x / 10.x ranges). */
function getLanIp() {
const all = Object.values(os.networkInterfaces())
.flat()
.filter((n) => n.family === "IPv4" && !n.internal)
.map((n) => n.address);
return all.find((a) => a.startsWith("192.168.") || a.startsWith("10.")) ?? all[0] ?? "unknown";
}
/** Poll TCP host:port until it accepts a connection or the timeout expires. */
function waitForTcp(host, port, timeoutMs = 30_000) {
return new Promise((resolve, reject) => {
const deadline = Date.now() + timeoutMs;
function attempt() {
const sock = net.createConnection({ host, port });
sock.on("connect", () => {
sock.destroy();
resolve();
});
sock.on("error", () => {
sock.destroy();
if (Date.now() >= deadline) {
reject(
new Error(
`Postgres not ready on ${host}:${port} after ${timeoutMs / 1000}s. ` +
"Is Docker running? Check: docker compose -f docker-compose.dev.yaml logs",
),
);
} else {
setTimeout(attempt, 500);
}
});
}
attempt();
});
}
/** Run a shell command synchronously, streaming output to the terminal. */
function run(cmd) {
execSync(cmd, { stdio: "inherit", shell: true });
}
export async function main() {
// 1. Start DB container (idempotent — safe to call when already running)
console.log("\n▸ Starting database container...");
run("docker compose -f docker-compose.dev.yaml up -d");
// 2. Wait for Postgres to accept connections
process.stdout.write("▸ Waiting for Postgres");
const tick = setInterval(() => process.stdout.write("."), 500);
try {
await waitForTcp("127.0.0.1", 5432);
} finally {
clearInterval(tick);
process.stdout.write(" ready\n");
}
// 3. Apply any pending migrations (no-op if already current)
console.log("▸ Running migrations...");
run("pnpm db:migrate");
// 4. Seed default data (idempotent)
console.log("▸ Seeding...");
run("pnpm db:seed");
// 5. Print access URLs before the Next.js banner appears
const lanIp = getLanIp();
console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
console.log(` Local → http://localhost:3000`);
console.log(` LAN → http://${lanIp}:3000 (phone on same WiFi)`);
console.log(` HTTPS → https://dev.<your-domain> (push/PWA — needs Caddyfile.dev.snippet)`);
console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
// 6. Spawn Next.js dev server bound to all interfaces.
// HMR handles most code changes without a restart.
// Restart needed for: .env changes, next.config.ts changes.
// Pass command as a single string with no args array — shell handles .cmd
// resolution on Windows and the empty args avoids DEP0190.
const next = spawn("pnpm run dev:network", [], { stdio: "inherit", shell: true });
// Forward Ctrl+C / SIGTERM to the child so it shuts down cleanly.
const forward = (sig) => () => next.kill(sig);
process.on("SIGINT", forward("SIGINT"));
process.on("SIGTERM", forward("SIGTERM"));
await new Promise((resolve) => next.on("exit", (code) => resolve(code)));
process.exit(0);
}
// Run when invoked directly (not imported by dev-reset.mjs)
const __filename = fileURLToPath(import.meta.url);
if (process.argv[1] === __filename) {
main().catch((err) => {
console.error("\ndev startup failed:", err.message);
process.exit(1);
});
}
+27 -79
View File
@@ -1,100 +1,48 @@
/**
* Generates placeholder PNG icons for the famapp PWA.
* Rasterizes public/icon.svg into all required PNG icon sizes.
*
* Usage: node scripts/generate-icons.mjs
*
* Produces:
* public/icon-16.png
* public/icon-32.png
* public/icon-180.png (apple-touch-icon)
* public/icon-192.png
* public/icon-384.png
* public/icon-512.png
* public/icon-512-maskable.png (same image; OS applies its own mask)
* public/icon-180.png (apple-touch-icon)
*
* All images are solid indigo (#4F46E5) squares replace with a real
* branded export from icon.svg when assets are finalised.
* public/icon-512-maskable.png (square bg, content in safe zone)
*/
import { deflateSync } from "zlib";
import { writeFileSync } from "fs";
import { resolve, dirname } from "path";
import sharp from "sharp";
import { readFileSync } from "fs";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
const __dir = dirname(fileURLToPath(import.meta.url));
const publicDir = resolve(__dir, "../public");
const __dirname = dirname(fileURLToPath(import.meta.url));
const pub = join(__dirname, "..", "public");
// Build CRC-32 lookup table once.
const CRC_TABLE = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
CRC_TABLE[i] = c;
}
const svg = readFileSync(join(pub, "icon.svg"));
function crc32(buf) {
let crc = 0xffffffff;
for (let i = 0; i < buf.length; i++) crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
return (crc ^ 0xffffffff) >>> 0;
}
function u32(n) {
const b = Buffer.alloc(4);
b.writeUInt32BE(n, 0);
return b;
}
function pngChunk(type, data) {
const typeBytes = Buffer.from(type, "ascii");
const crc = u32(crc32(Buffer.concat([typeBytes, data])));
return Buffer.concat([u32(data.length), typeBytes, data, crc]);
}
/**
* Returns a Buffer containing a valid PNG of size×size filled with (r, g, b).
*/
function solidPNG(size, r, g, b) {
const PNG_SIG = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
const ihdr = pngChunk(
"IHDR",
Buffer.concat([
u32(size),
u32(size),
Buffer.from([8, 2, 0, 0, 0]), // 8-bit RGB, no interlace
]),
);
// One filter byte (0 = None) followed by size×3 RGB bytes per row.
const rowLen = 1 + size * 3;
const raw = Buffer.alloc(size * rowLen);
for (let y = 0; y < size; y++) {
const base = y * rowLen;
raw[base] = 0;
for (let x = 0; x < size; x++) {
raw[base + 1 + x * 3] = r;
raw[base + 2 + x * 3] = g;
raw[base + 3 + x * 3] = b;
}
}
const idat = pngChunk("IDAT", deflateSync(raw));
const iend = pngChunk("IEND", Buffer.alloc(0));
return Buffer.concat([PNG_SIG, ihdr, idat, iend]);
}
// Indigo-600 (#4F46E5)
const [R, G, B] = [0x4f, 0x46, 0xe5];
const icons = [
const sizes = [
{ name: "icon-16.png", size: 16 },
{ name: "icon-32.png", size: 32 },
{ name: "icon-180.png", size: 180 },
{ name: "icon-192.png", size: 192 },
{ name: "icon-384.png", size: 384 },
{ name: "icon-512.png", size: 512 },
{ name: "icon-512-maskable.png", size: 512 },
{ name: "icon-180.png", size: 180 },
];
for (const { name, size } of icons) {
const out = resolve(publicDir, name);
writeFileSync(out, solidPNG(size, R, G, B));
for (const { name, size } of sizes) {
await sharp(svg).resize(size, size).png().toFile(join(pub, name));
console.log(` ✓ public/${name} (${size}×${size})`);
}
// Maskable: remove rounded corners so the background fills the full canvas,
// allowing the OS to apply any mask shape without clipping the icon corners.
const maskableSvg = readFileSync(join(pub, "icon.svg"), "utf-8").replace('rx="96"', "");
await sharp(Buffer.from(maskableSvg))
.resize(512, 512)
.png()
.toFile(join(pub, "icon-512-maskable.png"));
console.log(` ✓ public/icon-512-maskable.png (512×512 maskable)`);
-30
View File
@@ -1,30 +0,0 @@
import postgres from "postgres";
import { drizzle } from "drizzle-orm/postgres-js";
import { households } from "@/modules/_core/schema";
import { ensureDefaultCalendars } from "@/modules/calendar/server/defaults";
import { ensureDefaultLists } from "@/modules/lists/server/defaults";
const client = postgres(process.env["DATABASE_URL"]!);
const db = drizzle(client);
async function seed() {
const [existing] = await db.select().from(households).limit(1);
if (existing) {
console.log(`Household already exists ("${existing.name}"), skipping.`);
} else {
await db.insert(households).values({ name: "Home" });
console.log('Seeded household "Home".');
}
await ensureDefaultCalendars();
console.log("Ensured default calendars.");
await ensureDefaultLists();
console.log("Ensured default lists.");
await client.end();
process.exit(0);
}
seed().catch((err) => {
console.error(err);
process.exit(1);
});
+52
View File
@@ -0,0 +1,52 @@
/**
* Dev script: send a test push notification to all subscriptions for the dev user.
* Usage: tsx --env-file=.env scripts/send-test-push.mts
*/
import webPush from "web-push";
import postgres from "postgres";
const subject = process.env["VAPID_SUBJECT"];
const publicKey = process.env["VAPID_PUBLIC_KEY"];
const privateKey = process.env["VAPID_PRIVATE_KEY"];
const databaseUrl = process.env["DATABASE_URL"];
if (!subject || !publicKey || !privateKey) {
console.error("VAPID env vars not set");
process.exit(1);
}
if (!databaseUrl) {
console.error("DATABASE_URL not set");
process.exit(1);
}
webPush.setVapidDetails(subject, publicKey, privateKey);
const sql = postgres(databaseUrl);
const subs = await sql`SELECT id, user_id, endpoint, p256dh, auth FROM push_subscriptions`;
console.log(`Found ${subs.length} push subscription(s)`);
if (subs.length === 0) {
console.log("No subscriptions — enable push notifications in Settings first.");
await sql.end();
process.exit(0);
}
for (const sub of subs) {
try {
await webPush.sendNotification(
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
JSON.stringify({
title: "famapp test",
body: "Push notifications are working!",
url: "/settings",
}),
);
console.log(`Sent to ${sub.endpoint.slice(0, 60)}...`);
} catch (err: unknown) {
const e = err as { statusCode?: number; message?: string };
console.error(`Failed (${e.statusCode ?? "?"}): ${e.message}`);
}
}
await sql.end();
-1
View File
@@ -3,4 +3,3 @@ import webPush from "web-push";
const { publicKey, privateKey } = webPush.generateVAPIDKeys();
console.log(`VAPID_PUBLIC_KEY=${publicKey}`);
console.log(`VAPID_PRIVATE_KEY=${privateKey}`);
console.log(`NEXT_PUBLIC_VAPID_PUBLIC_KEY=${publicKey}`);
@@ -0,0 +1,17 @@
import { NextResponse } from "next/server";
import { getCurrentSession } from "@/lib/session";
import { searchSpecies } from "@/modules/garden/server/species-lookup";
export async function GET(request: Request) {
try {
await getCurrentSession();
} catch {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const q = searchParams.get("q") ?? "";
const results = await searchSpecies(q);
return NextResponse.json(results);
}
+34
View File
@@ -0,0 +1,34 @@
import { NextResponse } from "next/server";
import { minioClient, MINIO_BUCKET } from "@/lib/minio";
export const runtime = "nodejs";
export async function GET(_request: Request, { params }: { params: Promise<{ key: string[] }> }) {
const { key } = await params;
const objectKey = key.join("/");
try {
const stat = await minioClient.statObject(MINIO_BUCKET, objectKey);
const stream = await minioClient.getObject(MINIO_BUCKET, objectKey);
const chunks: Buffer[] = [];
for await (const chunk of stream) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array));
}
const buffer = Buffer.concat(chunks);
const metaData = stat.metaData as Record<string, string> | undefined;
const contentType =
metaData?.["content-type"] ?? metaData?.["Content-Type"] ?? "application/octet-stream";
return new Response(buffer, {
headers: {
"Content-Type": contentType,
"Cache-Control": "public, max-age=31536000, immutable",
"Content-Length": String(buffer.length),
},
});
} catch {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
}
+62
View File
@@ -0,0 +1,62 @@
import { randomUUID } from "node:crypto";
import { NextResponse } from "next/server";
import { getCurrentSession } from "@/lib/session";
import { ensureBucket, minioClient, MINIO_BUCKET } from "@/lib/minio";
export const runtime = "nodejs";
export const maxDuration = 60;
export const config = {
api: { bodyParser: { sizeLimit: "100mb" } },
};
const MAX_FILE_SIZE = 100 * 1024 * 1024;
export async function POST(request: Request) {
let session: Awaited<ReturnType<typeof getCurrentSession>>;
try {
session = await getCurrentSession();
} catch {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
let formData: FormData;
try {
formData = await request.formData();
} catch {
return NextResponse.json({ error: "Invalid multipart body" }, { status: 400 });
}
const file = formData.get("file");
if (!(file instanceof File)) {
return NextResponse.json({ error: "No file field in request" }, { status: 400 });
}
if (!file.type.startsWith("image/")) {
return NextResponse.json({ error: "Only image files are allowed" }, { status: 415 });
}
if (file.size > MAX_FILE_SIZE) {
return NextResponse.json({ error: "File exceeds 100 MB limit" }, { status: 413 });
}
const rawExt = file.name.split(".").pop() ?? "bin";
const safeExt = rawExt
.replace(/[^a-z0-9]/gi, "")
.toLowerCase()
.slice(0, 8);
const key = `garden/${session.household.id}/${randomUUID()}.${safeExt}`;
try {
await ensureBucket();
const buffer = Buffer.from(await file.arrayBuffer());
await minioClient.putObject(MINIO_BUCKET, key, buffer, buffer.length, {
"Content-Type": file.type,
});
} catch (err) {
console.error("Upload failed", err);
return NextResponse.json({ error: "Upload service unavailable" }, { status: 503 });
}
return NextResponse.json({ url: `/api/uploads/${key}` });
}
+11 -2
View File
@@ -1,5 +1,7 @@
import { CalendarShell } from "@/modules/calendar/components/calendar-shell";
import { listCalendars, listEvents } from "@/modules/calendar/server/queries";
import { getCurrentSession } from "@/lib/session";
import type { CalView } from "@/modules/_core/themes";
export default async function CalendarPage() {
const now = new Date();
@@ -8,10 +10,17 @@ export default async function CalendarPage() {
const to = new Date(now);
to.setMonth(to.getMonth() + 10);
const [calendars, events] = await Promise.all([
const [{ user }, calendars, events] = await Promise.all([
getCurrentSession(),
listCalendars(),
listEvents({ from, to, calendarIds: "all" }),
]);
return <CalendarShell calendars={calendars} events={events} />;
return (
<CalendarShell
calendars={calendars}
events={events}
defaultView={user.themeCalView as CalView}
/>
);
}
+58 -10
View File
@@ -1,13 +1,20 @@
import { notFound } from "next/navigation";
import { Suspense } from "react";
import { getCurrentSession } from "@/lib/session";
import { parseDashboardLayout, computeDefaultLayout } from "@/lib/dashboard";
import { parseDashboardLayout } from "@/lib/dashboard";
import { computeDefaultLayout } from "@/lib/dashboard.server";
import { getWidget, getWidgetMetas } from "@/modules/_core";
import { getDashboardBySlug } from "@/app/d/actions";
import { DashboardEditor } from "@/components/dashboard-editor";
import { QuickAddFab } from "@/components/quick-add-fab";
import { EditDashboardButton } from "@/components/edit-dashboard-button";
import { DashboardSwitcher } from "@/components/dashboard-switcher";
import { DashboardTab } from "@/components/dashboard-tab";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { dashboards } from "@/modules/_core/schema";
import { asc, eq } from "drizzle-orm";
import type { DashLayout } from "@/modules/_core/themes";
const smColSpan: Record<number, string> = {
1: "sm:col-span-1",
@@ -24,6 +31,9 @@ const smColSpan: Record<number, string> = {
12: "sm:col-span-12",
};
const greetingForHour = (h: number) =>
h < 5 ? "Up early" : h < 12 ? "Good morning" : h < 18 ? "Good afternoon" : "Good evening";
export default async function DashboardPage({
params,
searchParams,
@@ -52,17 +62,55 @@ export default async function DashboardPage({
);
}
// For dashboard tabs sub-header, pull the user's dashboards (small list).
const session = await auth();
const userDashboards = session?.user?.id
? await db
.select({
id: dashboards.id,
name: dashboards.name,
slug: dashboards.slug,
isDefault: dashboards.isDefault,
position: dashboards.position,
})
.from(dashboards)
.where(eq(dashboards.userId, session.user.id))
.orderBy(asc(dashboards.position), asc(dashboards.createdAt))
: [];
const ctx = { userId: user.id, householdId: household.id };
const placements = [...layout.widgets].sort((a, b) => a.y - b.y || a.x - b.x);
const dashLayout = (user.themeDashLayout as DashLayout) ?? "classic";
const containerCls =
dashLayout === "glance" ? "max-w-[760px] mx-auto" : dashLayout === "split" ? "" : "";
const greeting = greetingForHour(new Date().getHours());
const today = new Date().toLocaleDateString(undefined, {
weekday: "long",
month: "long",
day: "numeric",
});
const firstName = (user.name ?? "").split(" ")[0] ?? "";
return (
<div className="p-4 sm:p-6">
<div className="mb-6 flex items-center justify-between">
<h1 className="text-2xl font-bold">{dashboard.name}</h1>
<div className="flex items-center gap-2">
<QuickAddFab />
<EditDashboardButton />
<div className={containerCls}>
{userDashboards.length >= 1 && (
<div className="flex items-center gap-1 mb-4 overflow-x-auto">
{userDashboards.map((d) => (
<DashboardTab key={d.id} slug={d.slug} name={d.name} />
))}
<DashboardSwitcher dashboards={userDashboards} />
</div>
)}
<div className="mb-6 flex items-end justify-between gap-4 flex-wrap">
<div>
<h1 className="serif text-[26px] sm:text-[30px] leading-tight tracking-tight">
{greeting}
{firstName && `, ${firstName}`}.
</h1>
<p className="muted mt-1 text-[13px]">{today}</p>
</div>
<EditDashboardButton />
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-12">
@@ -73,8 +121,8 @@ export default async function DashboardPage({
return (
<div key={i} className={`col-span-1 ${colClass}`}>
<Card className="h-full">
<CardHeader className="pb-2">
<CardTitle className="text-base">{widget.title}</CardTitle>
<CardHeader>
<CardTitle>{widget.title}</CardTitle>
</CardHeader>
<CardContent>
<Suspense
+2 -1
View File
@@ -8,7 +8,8 @@ import { db } from "@/lib/db";
import { getCurrentSession } from "@/lib/session";
import { getWidget } from "@/modules/_core";
import { dashboards } from "@/modules/_core/schema";
import { computeDefaultLayout, type DashboardLayout } from "@/lib/dashboard";
import { type DashboardLayout } from "@/lib/dashboard";
import { computeDefaultLayout } from "@/lib/dashboard.server";
export type DashboardMeta = {
id: string;
+27
View File
@@ -0,0 +1,27 @@
"use client";
import { useEffect } from "react";
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-4 p-8">
<h2 className="text-xl font-semibold">Something went wrong</h2>
<button
onClick={reset}
className="rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground hover:bg-primary/90"
>
Try again
</button>
</div>
);
}
+18
View File
@@ -0,0 +1,18 @@
import { notFound } from "next/navigation";
import { getContainer } from "@/modules/garden/server/queries";
import { ContainerDetail } from "@/modules/garden/components/container-detail";
import { getShareLinksForEntity } from "@/modules/_core/share";
export default async function ContainerPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const [container, shareLinks] = await Promise.all([
getContainer(id),
getShareLinksForEntity("garden.container", id),
]);
if (!container) notFound();
return (
<div className="page-content">
<ContainerDetail container={container} shareLinks={shareLinks} />
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import { redirect } from "next/navigation";
import { createContainer } from "@/modules/garden/server/actions";
export default function NewContainerPage() {
async function handleCreate(formData: FormData) {
"use server";
await createContainer({
name: formData.get("name") as string,
type: (formData.get("type") as string) || "other",
locationNotes: (formData.get("locationNotes") as string) || null,
});
redirect("/garden");
}
return (
<div className="page-content max-w-lg">
<div className="flex items-center gap-3 mb-1">
<a href="/garden" className="btn btn-ghost btn-icon" aria-label="Back to garden">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="15 18 9 12 15 6" />
</svg>
</a>
<h1 className="page-title">New container</h1>
</div>
<form action={handleCreate} className="flex flex-col gap-4 mt-4">
<div className="flex flex-col gap-1">
<label htmlFor="name" className="text-sm font-medium">
Name
</label>
<input id="name" name="name" required maxLength={120} className="input" />
</div>
<div className="flex flex-col gap-1">
<label htmlFor="type" className="text-sm font-medium">
Type
</label>
<select id="type" name="type" defaultValue="other">
{(
[
["shelf", "Shelf"],
["terrarium", "Terrarium"],
["raised-bed", "Raised bed"],
["window-box", "Window box"],
["single-pot", "Single pot"],
["outdoor", "Outdoor"],
["other", "Other"],
] as const
).map(([v, l]) => (
<option key={v} value={v}>
{l}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-1">
<label htmlFor="locationNotes" className="text-sm font-medium">
Location notes
</label>
<textarea
id="locationNotes"
name="locationNotes"
maxLength={500}
rows={2}
className="input"
/>
</div>
<div className="flex gap-2 justify-end">
<a href="/garden" className="btn btn-ghost">
Cancel
</a>
<button type="submit" className="btn btn-primary">
Create
</button>
</div>
</form>
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
import Link from "next/link";
import { listContainers, listPlants } from "@/modules/garden/server/queries";
import { ContainerList } from "@/modules/garden/components/container-list";
import { PlantList } from "@/modules/garden/components/plant-list";
import { PushOverdueButton } from "@/modules/garden/components/push-overdue-button";
type Props = {
searchParams: Promise<{ tab?: string }>;
};
export default async function GardenPage({ searchParams }: Props) {
const { tab = "containers" } = await searchParams;
const isPlants = tab === "plants";
const [containers, plants] = await Promise.all([
listContainers(),
isPlants ? listPlants() : Promise.resolve([]),
]);
return (
<div className="page-content">
<div className="flex items-center justify-between mb-1">
<h1 className="page-title mb-0">Garden</h1>
<PushOverdueButton />
</div>
<div className="flex gap-6 border-b border-[var(--ink-faint)] mb-6">
<Link
href="/garden?tab=containers"
className={`pb-2 text-sm font-medium transition-colors ${
!isPlants
? "border-b-2 border-[var(--ink)] text-[var(--ink)]"
: "text-[var(--ink-mute)]"
}`}
>
Containers
</Link>
<Link
href="/garden?tab=plants"
className={`pb-2 text-sm font-medium transition-colors ${
isPlants ? "border-b-2 border-[var(--ink)] text-[var(--ink)]" : "text-[var(--ink-mute)]"
}`}
>
Plants
</Link>
</div>
{isPlants ? <PlantList plants={plants} /> : <ContainerList containers={containers} />}
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { notFound } from "next/navigation";
import { getPlant, listContainers } from "@/modules/garden/server/queries";
import { PlantForm } from "@/modules/garden/components/plant-form";
export default async function EditPlantPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const [plant, containers] = await Promise.all([getPlant(id), listContainers()]);
if (!plant) notFound();
return (
<div className="page-content max-w-xl">
<h1 className="page-title">Edit Plant</h1>
<PlantForm existingPlant={plant} containers={containers} />
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
import { notFound } from "next/navigation";
import { listCalendars } from "@/modules/garden/server/calendar-bridge";
import { getCareLogs, getCareSchedules, getPlant } from "@/modules/garden/server/queries";
import { PlantDetail } from "@/modules/garden/components/plant-detail";
import { getShareLinksForEntity } from "@/modules/_core/share";
export default async function PlantPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const [plant, careLogs, careSchedules, calendars, shareLinks] = await Promise.all([
getPlant(id),
getCareLogs(id),
getCareSchedules(id),
listCalendars(),
getShareLinksForEntity("garden.plant", id),
]);
if (!plant) notFound();
return (
<div className="page-content">
<PlantDetail
plant={plant}
careLogs={careLogs}
careSchedules={careSchedules}
calendars={calendars}
shareLinks={shareLinks}
/>
</div>
);
}
+34
View File
@@ -0,0 +1,34 @@
import { listContainers } from "@/modules/garden/server/queries";
import { PlantForm } from "@/modules/garden/components/plant-form";
export default async function NewPlantPage({
searchParams,
}: {
searchParams: Promise<{ containerId?: string }>;
}) {
const params = await searchParams;
const containers = await listContainers();
return (
<div className="page-content max-w-xl">
<div className="flex items-center gap-3 mb-1">
<a href="/garden" className="btn btn-ghost btn-icon" aria-label="Back to garden">
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<polyline points="15 18 9 12 15 6" />
</svg>
</a>
<h1 className="page-title">Add Plant</h1>
</div>
<PlantForm containers={containers} defaultContainerId={params.containerId ?? null} />
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
"use client";
import { useEffect } from "react";
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
console.error(error);
}, [error]);
return (
<html>
<body className="flex min-h-screen flex-col items-center justify-center gap-4 p-8">
<h2 className="text-xl font-semibold">Something went wrong</h2>
<button
onClick={reset}
className="rounded-md bg-primary px-4 py-2 text-sm text-primary-foreground hover:bg-primary/90"
>
Try again
</button>
</body>
</html>
);
}
+1446 -170
View File
File diff suppressed because it is too large Load Diff
+93 -25
View File
@@ -1,8 +1,7 @@
import type { Metadata, Viewport } from "next";
import "./globals.css";
import { Geist } from "next/font/google";
import { Inter, Source_Serif_4, Newsreader, Fraunces, JetBrains_Mono } from "next/font/google";
import { cn } from "@/lib/utils";
import { AppNav } from "@/components/app-nav";
import "@/modules"; // registers all module manifests
import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
@@ -15,11 +14,35 @@ import { QuickAddSheet } from "@/components/quick-add-sheet";
import { CommandPalette } from "@/components/command-palette";
import { PwaRegister } from "@/components/pwa-register";
import { InstallPrompt } from "@/components/install-prompt";
import { AppShell } from "@/components/app-shell";
import { DEFAULT_THEME, navStyleToDataNav } from "@/modules/_core/themes";
import type { Palette, ThemeMode, FontPair, Density, NavStyle } from "@/modules/_core/themes";
const geist = Geist({ subsets: ["latin"], variable: "--font-sans" });
const inter = Inter({ subsets: ["latin"], variable: "--sans-inter", display: "swap" });
const sourceSerif = Source_Serif_4({
subsets: ["latin"],
variable: "--serif-source",
display: "swap",
});
const newsreader = Newsreader({
subsets: ["latin"],
variable: "--serif-newsreader",
display: "swap",
});
const fraunces = Fraunces({
subsets: ["latin"],
variable: "--serif-fraunces",
display: "swap",
});
const jetbrains = JetBrains_Mono({
subsets: ["latin"],
variable: "--mono-jb",
display: "swap",
});
export const viewport: Viewport = {
themeColor: "#4F46E5",
themeColor: "#1F1B16",
viewportFit: "cover",
};
export const metadata: Metadata = {
@@ -32,38 +55,69 @@ export const metadata: Metadata = {
title: "famapp",
},
icons: {
icon: [
{ url: "/favicon.svg", type: "image/svg+xml" },
{ url: "/icon-32.png", sizes: "32x32", type: "image/png" },
{ url: "/icon-16.png", sizes: "16x16", type: "image/png" },
],
apple: "/icon-180.png",
},
};
// Runs before paint reads localStorage / prefers-color-scheme and applies
// data-theme + dark class to <html> so signed-out pages also get the right theme.
// Pre-paint: read user's theme prefs from localStorage and apply data-* + .dark.
// Falls back to clay/serif-sans/regular/sidebar/system if nothing is stored.
const prePaintScript = `(function(){
try {
var t = localStorage.getItem('theme') || 'default';
var m = localStorage.getItem('themeMode') || 'system';
var dark = m === 'dark' || (m === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
document.documentElement.setAttribute('data-theme', t);
if (dark) document.documentElement.classList.add('dark');
else document.documentElement.classList.remove('dark');
var palette = localStorage.getItem('themePalette') || localStorage.getItem('theme') || 'clay';
var mode = localStorage.getItem('themeMode') || 'system';
var fontPair = localStorage.getItem('themeFontPair') || 'serif-sans';
var density = localStorage.getItem('themeDensity') || 'regular';
var navStyle = localStorage.getItem('themeNavStyle') || 'rail-desktop';
var dataNav = navStyle === 'compact-rail' ? 'rail'
: navStyle === 'top-nav' ? 'top'
: 'sidebar';
if (window.matchMedia && window.matchMedia('(max-width: 759px)').matches) {
dataNav = navStyle === 'fab-only' ? 'fab' : 'bottom';
}
var dark = mode === 'dark' || (mode === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches);
var html = document.documentElement;
html.setAttribute('data-theme', palette);
html.setAttribute('data-font-pair', fontPair);
html.setAttribute('data-density', density);
html.setAttribute('data-nav', dataNav);
if (dark) html.classList.add('dark'); else html.classList.remove('dark');
} catch(e) {}
})();`;
export default async function RootLayout({ children }: { children: React.ReactNode }) {
let theme = "default";
let themeMode = "system";
let palette: Palette = DEFAULT_THEME.palette;
let mode: ThemeMode = DEFAULT_THEME.mode;
let fontPair: FontPair = DEFAULT_THEME.fontPair;
let density: Density = DEFAULT_THEME.density;
let navStyle: NavStyle = DEFAULT_THEME.navStyle;
let userDashboards: DashboardMeta[] = [];
let signedIn = false;
const session = await auth();
if (session?.user?.id) {
signedIn = true;
const [row] = await db
.select({ theme: users.theme, themeMode: users.themeMode })
.select({
themePalette: users.themePalette,
themeMode: users.themeMode,
themeFontPair: users.themeFontPair,
themeDensity: users.themeDensity,
themeNavStyle: users.themeNavStyle,
})
.from(users)
.where(eq(users.id, session.user.id))
.limit(1);
if (row) {
theme = row.theme;
themeMode = row.themeMode;
palette = row.themePalette as Palette;
mode = row.themeMode as ThemeMode;
fontPair = row.themeFontPair as FontPair;
density = row.themeDensity as Density;
navStyle = row.themeNavStyle as NavStyle;
}
userDashboards = await db
.select({
@@ -78,25 +132,39 @@ export default async function RootLayout({ children }: { children: React.ReactNo
.orderBy(asc(dashboards.position), asc(dashboards.createdAt));
}
// For system mode we can't know the preference on the server — the inline
// script will correct it before paint. We optimistically render light here.
const isDark = themeMode === "dark";
// Server-side initial dark guess: only for `dark` mode (system mode is corrected
// before paint by the inline script). Avoids a flash on signed-in users.
const isDark = mode === "dark";
const initialDataNav = navStyleToDataNav(navStyle);
const quickAdds = getQuickAdds();
const fontVars = cn(
inter.variable,
sourceSerif.variable,
newsreader.variable,
fraunces.variable,
jetbrains.variable,
);
return (
<html
lang="en"
data-theme={theme}
className={cn("font-sans", geist.variable, isDark ? "dark" : "")}
data-theme={palette}
data-font-pair={fontPair}
data-density={density}
data-nav={initialDataNav}
className={cn(fontVars, isDark ? "dark" : "")}
suppressHydrationWarning
>
<head>
<script dangerouslySetInnerHTML={{ __html: prePaintScript }} />
</head>
<body className="min-h-screen">
<body>
<QuickAddProvider actions={quickAdds}>
<AppNav dashboards={userDashboards} />
<main>{children}</main>
<AppShell signedIn={signedIn} navStyle={navStyle} dashboards={userDashboards}>
{children}
</AppShell>
<QuickAddSheet />
<CommandPalette />
<InstallPrompt />
+27 -11
View File
@@ -2,23 +2,34 @@ import { signIn } from "@/lib/auth";
import { Button } from "@/components/ui/button";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { DEV_LOGIN_COOKIE, isDevLoginEnabled } from "@/lib/dev-login-config";
import { isDevLoginEnabled } from "@/lib/dev-login-config";
import { createDevSession } from "@/lib/dev-login";
import { BrandMark } from "@/components/brand-mark";
export default function LoginPage() {
const devLoginEnabled = isDevLoginEnabled();
return (
<main className="flex min-h-screen flex-col items-center justify-center p-8">
<div className="flex flex-col items-center gap-6">
<h1 className="text-4xl font-bold">famapp</h1>
<main
className="flex min-h-screen flex-col items-center justify-center p-8"
style={{ background: "var(--paper)" }}
>
<div
className="rounded-[var(--r-lg)] shadow-[var(--shadow-2)] p-10 max-w-sm w-full text-center"
style={{ background: "var(--card)", border: "0.5px solid var(--hair)" }}
>
<div className="flex justify-center mb-3">
<BrandMark />
</div>
<h1 className="serif text-[28px] font-medium tracking-tight mb-2">famapp</h1>
<p className="muted text-[13.5px] mb-6">Sign in to your household.</p>
<form
action={async () => {
"use server";
await signIn("authentik", { redirectTo: "/" });
}}
>
<Button type="submit" size="lg">
<Button type="submit" size="lg" className="w-full">
Sign in with SSO
</Button>
</form>
@@ -26,18 +37,23 @@ export default function LoginPage() {
<form
action={async () => {
"use server";
// Auth.js may resolve either "authjs.session-token" (HTTP/dev) or
// "__Secure-authjs.session-token" (HTTPS) depending on AUTH_URL,
// trustHost, and proxy headers. Set both so the session is found
// regardless — this is dev-only code, correctness > elegance.
const { sessionToken, expires } = await createDevSession();
const cookieStore = await cookies();
cookieStore.set(DEV_LOGIN_COOKIE, sessionToken, {
httpOnly: true,
sameSite: "lax",
path: "/",
expires,
const base = { httpOnly: true, sameSite: "lax" as const, path: "/", expires };
cookieStore.set("authjs.session-token", sessionToken, base);
cookieStore.set("__Secure-authjs.session-token", sessionToken, {
...base,
secure: true,
});
redirect("/");
}}
className="mt-3"
>
<Button type="submit" variant="outline" size="lg">
<Button type="submit" variant="outline" size="lg" className="w-full">
Dev login
</Button>
</form>
+24 -20
View File
@@ -1,14 +1,17 @@
import type { Metadata } from "next";
import { headers } from "next/headers";
import { eq } from "drizzle-orm";
import { resolveShareToken } from "@/modules/_core/share";
import { getEntityType } from "@/modules/_core/registry";
import { isRateLimited, recordFailure } from "@/lib/rate-limit";
import { db } from "@/lib/db";
import { users } from "@/modules/_core/schema";
import { ShareFrame } from "@/components/share/share-frame";
export const metadata: Metadata = {
robots: { index: false, follow: false },
};
// Rate-limit prefix length — must match the value used in middleware.
const RL_PREFIX_LEN = 8;
export default async function SharePage({ params }: { params: Promise<{ token: string }> }) {
@@ -20,19 +23,12 @@ export default async function SharePage({ params }: { params: Promise<{ token: s
"0.0.0.0";
const rlKey = `${ip}:${token.slice(0, RL_PREFIX_LEN)}`;
// Secondary rate-limit check in the Node.js runtime (failure-only bucket).
// The primary 429 enforcement lives in src/middleware.ts which counts all
// requests in the Edge runtime. This page tracks only failed token lookups,
// providing accurate per-failure accounting. The two buckets are independent
// (separate module instances across runtimes); a shared Redis store would
// unify them for multi-replica deployments.
if (isRateLimited(rlKey)) {
return <ShareRateLimitError />;
}
const resolved = await resolveShareToken(token);
if (!resolved) {
// Only failed lookups increment the failure bucket.
recordFailure(rlKey);
return <ShareError />;
}
@@ -48,24 +44,32 @@ export default async function SharePage({ params }: { params: Promise<{ token: s
return <ShareError />;
}
// Best-effort lookup of the creator's display name. Doesn't reveal email.
const [creator] = resolved.createdBy
? await db
.select({ name: users.name })
.from(users)
.where(eq(users.id, resolved.createdBy))
.limit(1)
: [];
return (
<div className="min-h-screen">
<div className="border-b bg-background px-4 py-3">
<p className="text-xs text-muted-foreground">
Shared via famapp
{resolved.capabilities.write ? " · You can edit this" : " · View only"}
</p>
</div>
<ShareFrame
expiresAt={resolved.expiresAt}
capabilities={resolved.capabilities}
token={token}
sharedByName={creator?.name ?? null}
>
{entityReg.renderSharedView({ data, capabilities: resolved.capabilities, token })}
</div>
</ShareFrame>
);
}
function ShareRateLimitError() {
return (
<div className="flex min-h-[60vh] flex-col items-center justify-center gap-3 p-8 text-center">
<h1 className="text-xl font-semibold">Too many requests</h1>
<p className="max-w-sm text-sm text-muted-foreground">
<h1 className="serif text-[28px] font-medium tracking-tight">Too many requests</h1>
<p className="max-w-sm text-[13.5px] muted">
You have made too many requests in a short period. Please wait a minute and try again.
</p>
</div>
@@ -75,8 +79,8 @@ function ShareRateLimitError() {
function ShareError({ message }: { message?: string }) {
return (
<div className="flex min-h-[60vh] flex-col items-center justify-center gap-3 p-8 text-center">
<h1 className="text-xl font-semibold">Link not found</h1>
<p className="max-w-sm text-sm text-muted-foreground">
<h1 className="serif text-[28px] font-medium tracking-tight">Link not found</h1>
<p className="max-w-sm text-[13.5px] muted">
{message ??
"This share link may have expired or been revoked. Ask the sender for a new link."}
</p>
+62 -6
View File
@@ -4,17 +4,73 @@ import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { db } from "@/lib/db";
import { users } from "@/modules/_core/schema";
import { VALID_THEME_IDS, VALID_THEME_MODES } from "@/modules/_core/themes";
import type { ThemeId, ThemeMode } from "@/modules/_core/themes";
import {
VALID_PALETTES,
VALID_THEME_MODES,
VALID_FONT_PAIRS,
VALID_DENSITIES,
VALID_DASH_LAYOUTS,
VALID_CAL_VIEWS,
VALID_NAV_STYLES,
} from "@/modules/_core/themes";
import type {
Palette,
ThemeMode,
FontPair,
Density,
DashLayout,
CalView,
NavStyle,
} from "@/modules/_core/themes";
import { getCurrentSession } from "@/lib/session";
import { revokeShareLink } from "@/modules/_core/share";
export async function setUserTheme({ theme, mode }: { theme: ThemeId; mode: ThemeMode }) {
if (!VALID_THEME_IDS.has(theme)) throw new Error("Invalid theme");
if (!VALID_THEME_MODES.has(mode)) throw new Error("Invalid theme mode");
export interface ThemePatch {
palette?: Palette;
mode?: ThemeMode;
fontPair?: FontPair;
density?: Density;
dashLayout?: DashLayout;
calView?: CalView;
navStyle?: NavStyle;
}
export async function setUserTheme(patch: ThemePatch) {
const update: Record<string, string> = {};
if (patch.palette !== undefined) {
if (!VALID_PALETTES.has(patch.palette)) throw new Error("Invalid palette");
update["themePalette"] = patch.palette;
}
if (patch.mode !== undefined) {
if (!VALID_THEME_MODES.has(patch.mode)) throw new Error("Invalid theme mode");
update["themeMode"] = patch.mode;
}
if (patch.fontPair !== undefined) {
if (!VALID_FONT_PAIRS.has(patch.fontPair)) throw new Error("Invalid font pair");
update["themeFontPair"] = patch.fontPair;
}
if (patch.density !== undefined) {
if (!VALID_DENSITIES.has(patch.density)) throw new Error("Invalid density");
update["themeDensity"] = patch.density;
}
if (patch.dashLayout !== undefined) {
if (!VALID_DASH_LAYOUTS.has(patch.dashLayout)) throw new Error("Invalid dashboard layout");
update["themeDashLayout"] = patch.dashLayout;
}
if (patch.calView !== undefined) {
if (!VALID_CAL_VIEWS.has(patch.calView)) throw new Error("Invalid calendar view");
update["themeCalView"] = patch.calView;
}
if (patch.navStyle !== undefined) {
if (!VALID_NAV_STYLES.has(patch.navStyle)) throw new Error("Invalid nav style");
update["themeNavStyle"] = patch.navStyle;
}
if (Object.keys(update).length === 0) return;
const { user } = await getCurrentSession();
await db.update(users).set({ theme, themeMode: mode }).where(eq(users.id, user.id));
await db.update(users).set(update).where(eq(users.id, user.id));
}
export async function setCompletionVisibilityHours(hours: number): Promise<void> {
+291 -55
View File
@@ -7,44 +7,183 @@ import { ThemePicker } from "@/components/theme-picker";
import { CompletionDelaySetting } from "@/components/completion-delay-setting";
import { PushOptIn } from "@/components/push-opt-in";
import { NotifyChannelToggles } from "@/components/notify-channel-toggles";
import { ResponsiveSidebar } from "@/components/settings-section";
import type { SectionId } from "@/components/settings-section";
import { revokeShareLinkAction } from "./actions";
import { listCalendars } from "@/modules/calendar/server/queries";
import { listLists } from "@/modules/lists/server/queries";
import Link from "next/link";
import { NavIcon } from "@/components/nav-icon";
import { Mail, Globe, History, Sun, Bell, Pencil, Lock, Plus } from "lucide-react";
export default async function SettingsPage() {
const { user } = await getCurrentSession();
const shareLinks = await getActiveShareLinks();
const VALID_SECTIONS = new Set<SectionId>([
"household",
"sharing",
"notifications",
"calendars",
"appearance",
"data",
]);
export default async function SettingsPage({
searchParams,
}: {
searchParams: Promise<{ s?: string }>;
}) {
const sp = await searchParams;
const section: SectionId = VALID_SECTIONS.has(sp.s as SectionId)
? (sp.s as SectionId)
: "household";
const { user, household } = await getCurrentSession();
const ntfyConfigured = !!(process.env["NTFY_URL"] && process.env["NTFY_TOPIC"]);
const vapidKey = process.env["VAPID_PUBLIC_KEY"] ?? "";
return (
<div className="container max-w-2xl py-8 space-y-6">
<h1 className="text-2xl font-semibold">Settings</h1>
<div className="grid gap-5 sm:grid-cols-[220px_1fr]">
<ResponsiveSidebar active={section} />
<div className="space-y-4">
{section === "household" && <HouseholdSection household={household} userName={user.name} />}
{section === "sharing" && <SharingSection />}
{section === "notifications" && (
<NotificationsSection user={user} vapidKey={vapidKey} ntfyConfigured={ntfyConfigured} />
)}
{section === "calendars" && <CalendarsAndListsSection />}
{section === "appearance" && <AppearanceSection user={user} />}
{section === "data" && <DataSection />}
</div>
</div>
);
}
function HouseholdSection({
household,
userName,
}: {
household: { id: string; name: string };
userName: string | null;
}) {
return (
<>
<Card>
<CardHeader>
<CardTitle>Appearance</CardTitle>
<CardTitle>{household.name}</CardTitle>
<span className="meta">Self-hosted</span>
</CardHeader>
<CardContent>
<ThemePicker
initialTheme={user.theme as "default" | "warm"}
initialMode={user.themeMode as "light" | "dark" | "system"}
signedIn
/>
<p className="muted text-[13px] mb-3">
Household name shown on share links and the iOS PWA.
</p>
<Link
href="/settings/household"
className="inline-flex items-center gap-2 px-3 py-1.5 rounded-md text-[13px] font-medium border-[0.5px] hover:bg-[var(--shade)]"
style={{ borderColor: "var(--hair-2)" }}
>
<Pencil className="size-3.5" />
Edit household & members
</Link>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>Lists</CardTitle>
<CardTitle>You</CardTitle>
</CardHeader>
<CardContent>
<CompletionDelaySetting initialHours={user.completionVisibilityHours} />
<div className="set-row" style={{ borderBottom: "0", padding: 0 }}>
<span className="avatar avatar-lg" style={{ background: "var(--c-household)" }}>
{(userName ?? "?").trim()[0]?.toUpperCase()}
</span>
<div className="label">
<div className="t">{userName ?? "Anonymous"}</div>
<div className="d">Signed in via Authentik</div>
</div>
</div>
</CardContent>
</Card>
</>
);
}
async function SharingSection() {
const shareLinks = await getActiveShareLinks();
return (
<Card>
<CardHeader>
<CardTitle>Push Notifications</CardTitle>
<CardTitle>Public share links</CardTitle>
</CardHeader>
<CardContent>
<p className="muted text-[12.5px] mb-3">
Share any calendar, list, note, or event with people outside the household. Links expire
on their own no logins needed.
</p>
{shareLinks.length === 0 ? (
<p className="muted text-[13px]">No active share links.</p>
) : (
<div className="flex flex-col gap-2">
{shareLinks.map((link) => {
const registration = getEntityType(link.entityType);
const label = registration?.label.singular ?? link.entityType;
const iconName = link.entityType.startsWith("calendar.")
? "calendar"
: link.entityType.startsWith("notes.")
? "note"
: link.entityType.startsWith("lists.")
? "list"
: "link";
return (
<div
key={link.id}
className="flex items-center gap-3 rounded-[var(--r-md)] border-[0.5px] p-3"
style={{ borderColor: "var(--hair)" }}
>
<div
className="size-9 rounded-md flex items-center justify-center shrink-0"
style={{ background: "var(--paper-2)" }}
>
<NavIcon name={iconName} className="size-4 text-[var(--ink-soft)]" />
</div>
<div className="flex-1 min-w-0">
<div className="text-[13.5px] font-medium">{label}</div>
<div className="flex flex-wrap gap-2 items-center text-[11.5px] muted mt-0.5">
<code style={{ fontFamily: "var(--mono)" }}>
{link.capabilities.write ? "edit" : "view-only"}
</code>
{link.expiresAt && (
<span>· expires {link.expiresAt.toLocaleDateString()}</span>
)}
</div>
</div>
<form action={revokeShareLinkAction}>
<input type="hidden" name="id" value={link.id} />
<Button variant="destructive" size="sm" type="submit">
Revoke
</Button>
</form>
</div>
);
})}
</div>
)}
</CardContent>
</Card>
);
}
function NotificationsSection({
user,
vapidKey,
ntfyConfigured,
}: {
user: { notifPush: boolean; notifInApp: boolean; notifNtfy: boolean };
vapidKey: string;
ntfyConfigured: boolean;
}) {
return (
<>
<Card>
<CardHeader>
<CardTitle>Push notifications</CardTitle>
</CardHeader>
<CardContent>
<PushOptIn vapidKey={vapidKey} />
@@ -53,7 +192,7 @@ export default async function SettingsPage() {
<Card>
<CardHeader>
<CardTitle>Notification Channels</CardTitle>
<CardTitle>Notification channels</CardTitle>
</CardHeader>
<CardContent>
<NotifyChannelToggles
@@ -64,52 +203,149 @@ export default async function SettingsPage() {
/>
</CardContent>
</Card>
</>
);
}
async function CalendarsAndListsSection() {
const [calendars, lists] = await Promise.all([listCalendars(), listLists()]);
return (
<>
<Card>
<CardHeader>
<CardTitle>Calendars</CardTitle>
<Link
href="/calendar"
className="inline-flex items-center gap-1 px-2 py-1 rounded text-[12.5px] hover:bg-[var(--shade)]"
>
<Plus className="size-3.5" />
New
</Link>
</CardHeader>
<div>
{calendars.length === 0 ? (
<div className="muted px-[14px] py-4 text-[13px]">No calendars yet.</div>
) : (
calendars.map((c) => (
<div key={c.id} className="set-row">
<span
className="dot"
style={{ background: c.color ?? "var(--c-household)", width: 12, height: 12 }}
/>
<div className="label">
<div className="t">{c.name}</div>
<div className="d">
{c.visibility === "private" ? "Private" : "Household · everyone sees it"}
</div>
</div>
{c.visibility === "private" && <Lock className="size-3.5 text-[var(--ink-mute)]" />}
</div>
))
)}
</div>
</Card>
<Card>
<CardHeader>
<CardTitle>Active Share Links</CardTitle>
<CardTitle>Lists</CardTitle>
</CardHeader>
<CardContent>
{shareLinks.length === 0 ? (
<p className="text-sm text-muted-foreground">No active share links.</p>
) : (
<ul className="space-y-3">
{shareLinks.map((link) => {
const registration = getEntityType(link.entityType);
const label = registration?.label.singular ?? link.entityType;
return (
<li key={link.id} className="flex items-center justify-between gap-4 text-sm">
<div className="min-w-0">
<span className="font-medium">{label}</span>
<span className="text-muted-foreground ml-2">
{link.capabilities.write ? "read + write" : "read-only"}
</span>
{link.expiresAt && (
<span className="text-muted-foreground ml-2">
· expires {link.expiresAt.toLocaleDateString()}
</span>
)}
</div>
<form action={revokeShareLinkAction}>
<input type="hidden" name="id" value={link.id} />
<Button variant="destructive" size="sm" type="submit">
Revoke
</Button>
</form>
</li>
);
})}
</ul>
)}
<CompletionDelaySetting initialHours={24} />
</CardContent>
</Card>
<Link
href="/settings/household"
className="inline-flex items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium shadow-sm hover:bg-accent hover:text-accent-foreground"
>
Household Settings
</Link>
<div>
{lists.length === 0 ? (
<div className="muted px-[14px] py-4 text-[13px]">No lists yet.</div>
) : (
lists.map((l) => (
<div key={l.id} className="set-row">
<NavIcon
name={l.type === "shopping" ? "cart" : "check-square"}
className="size-4 text-[var(--ink-soft)]"
/>
<div className="label">
<div className="t">{l.name}</div>
<div className="d">
{l.type} · {l.openCount} open
</div>
</div>
</div>
))
)}
</div>
</Card>
</>
);
}
function AppearanceSection({
user,
}: {
user: {
themePalette: string;
themeMode: string;
themeFontPair: string;
themeDensity: string;
themeDashLayout: string;
themeCalView: string;
themeNavStyle: string;
};
}) {
return (
<Card>
<CardHeader>
<CardTitle>Appearance</CardTitle>
<Sun className="size-4 text-[var(--ink-mute)]" />
</CardHeader>
<CardContent>
<ThemePicker
initialPalette={user.themePalette as "clay" | "indigo" | "sage" | "plum" | "ink"}
initialMode={user.themeMode as "light" | "dark" | "system"}
initialFontPair={
user.themeFontPair as "serif-sans" | "newsreader" | "fraunces" | "sans-only"
}
initialDensity={user.themeDensity as "compact" | "regular" | "comfy"}
initialDashLayout={user.themeDashLayout as "classic" | "split" | "glance"}
initialCalView={user.themeCalView as "month" | "week" | "day"}
initialNavStyle={
user.themeNavStyle as "rail-desktop" | "compact-rail" | "top-nav" | "fab-only"
}
signedIn
/>
</CardContent>
</Card>
);
}
function DataSection() {
return (
<Card>
<CardHeader>
<CardTitle>Data & backups</CardTitle>
</CardHeader>
<div>
<div className="set-row">
<History className="size-4 text-[var(--ink-soft)]" />
<div className="label">
<div className="t">Auto-backup</div>
<div className="d">Daily 03:00 /var/backups/famapp/. Configured via host cron.</div>
</div>
</div>
<div className="set-row">
<Globe className="size-4 text-[var(--ink-soft)]" />
<div className="label">
<div className="t">Server</div>
<div className="d">Self-hosted via Docker Compose</div>
</div>
</div>
<div className="set-row" style={{ borderBottom: "0" }}>
<Mail className="size-4 text-[var(--ink-soft)]" />
<div className="label">
<div className="t">Export</div>
<div className="d">Not yet implemented coming in v0.5</div>
</div>
<Bell className="size-4 text-[var(--ink-faint)]" />
</div>
</div>
</Card>
);
}
+10 -3
View File
@@ -4,7 +4,7 @@ import { and, eq } from "drizzle-orm";
import { db } from "@/lib/db";
import { pushSubscriptions } from "@/modules/_core/schema";
import { getCurrentSession } from "@/lib/session";
import { sendPush } from "@/modules/_core/push";
import { sendPushToEndpoint } from "@/modules/_core/push";
type PushSubscriptionJSON = {
endpoint: string;
@@ -35,9 +35,16 @@ export async function unsubscribeFromPush(endpoint: string): Promise<void> {
.where(and(eq(pushSubscriptions.userId, user.id), eq(pushSubscriptions.endpoint, endpoint)));
}
export async function sendTestNotification(): Promise<void> {
export async function sendTestNotification(endpoint: string): Promise<void> {
const { user } = await getCurrentSession();
await sendPush(user.id, {
// Verify the endpoint belongs to the current user before sending.
const [owned] = await db
.select({ id: pushSubscriptions.id })
.from(pushSubscriptions)
.where(and(eq(pushSubscriptions.userId, user.id), eq(pushSubscriptions.endpoint, endpoint)))
.limit(1);
if (!owned) return;
await sendPushToEndpoint(endpoint, {
title: "famapp test",
body: "Push notifications are working!",
url: "/settings",
-82
View File
@@ -1,82 +0,0 @@
import Link from "next/link";
import { Settings } from "lucide-react";
import { desc, eq } from "drizzle-orm";
import { getRegistry } from "@/modules/_core/registry";
import type { DashboardMeta } from "@/app/d/actions";
import { notifications } from "@/modules/_core/schema";
import { db } from "@/lib/db";
import { auth } from "@/lib/auth";
import { DashboardSwitcher } from "./dashboard-switcher";
import { DashboardTab } from "./dashboard-tab";
import { NotificationBell } from "./notification-bell";
async function getNotifications(userId: string) {
const rows = await db
.select()
.from(notifications)
.where(eq(notifications.userId, userId))
.orderBy(desc(notifications.createdAt))
.limit(20);
const unread = rows.filter((n) => !n.readAt).length;
return { rows, unread };
}
export async function AppNav({ dashboards = [] }: { dashboards?: DashboardMeta[] }) {
const { modules } = getRegistry();
const navItems = modules.flatMap((m) => (m.nav ? [m.nav] : []));
const session = await auth();
const userId = session?.user?.id;
const { rows: notifRows, unread } = userId
? await getNotifications(userId)
: { rows: [], unread: 0 };
return (
<header className="border-b">
<nav className="px-4 py-3 flex items-center gap-6">
<Link href="/" className="font-semibold text-sm shrink-0">
famapp
</Link>
{navItems.map((item) => (
<Link
key={item.href}
href={item.href}
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
>
{item.label}
</Link>
))}
<div className="ml-auto flex items-center gap-3">
{userId && (
<NotificationBell
initialUnread={unread}
initialItems={notifRows.map((n) => ({
id: n.id,
title: n.title,
body: n.body,
url: n.url ?? null,
createdAt: n.createdAt,
}))}
/>
)}
<Link
href="/settings"
className="text-muted-foreground hover:text-foreground transition-colors"
aria-label="Settings"
>
<Settings className="size-4" />
</Link>
</div>
</nav>
{dashboards.length > 0 && (
<div className="flex items-center gap-1 border-t px-4 overflow-x-auto">
{dashboards.map((d) => (
<DashboardTab key={d.id} slug={d.slug} name={d.name} />
))}
<DashboardSwitcher dashboards={dashboards} />
</div>
)}
</header>
);
}
+43
View File
@@ -0,0 +1,43 @@
import { headers } from "next/headers";
import type { NavStyle } from "@/modules/_core/themes";
import type { DashboardMeta } from "@/app/d/actions";
import { Sidebar } from "@/components/sidebar";
import { Topbar } from "@/components/topbar";
import { BottomNav } from "@/components/bottom-nav";
import { NavModeProvider } from "@/components/nav-mode-provider";
const BARE_PREFIXES = ["/s/", "/login"];
interface Props {
signedIn: boolean;
navStyle: NavStyle;
dashboards: DashboardMeta[];
children: React.ReactNode;
}
export async function AppShell({ signedIn, navStyle, children }: Props) {
const h = await headers();
const pathname = h.get("x-pathname") ?? "";
const bare = BARE_PREFIXES.some(
(p) => pathname === p || pathname.startsWith(p + "/") || pathname === p.replace(/\/$/, ""),
);
if (bare || !signedIn) {
// No shell — share viewer and signed-out pages render bare.
return <>{children}</>;
}
const useTopVariant = navStyle === "top-nav";
return (
<div className="app">
{useTopVariant ? <Sidebar variant="top" /> : <Sidebar variant="side" />}
<main className="main">
<Topbar />
<div className="scroll-area">{children}</div>
</main>
<BottomNav />
<NavModeProvider navStyle={navStyle} />
</div>
);
}
+21
View File
@@ -0,0 +1,21 @@
import { getRegistry } from "@/modules/_core/registry";
import { NavLink } from "@/components/nav-link";
export async function BottomNav() {
const { modules } = getRegistry();
const moduleNav = modules.flatMap((m) => (m.nav ? [m.nav] : []));
const items = [
{ href: "/", label: "Dashboard", icon: "home" },
...moduleNav.map((n) => ({ href: n.href, label: n.label, icon: n.icon ?? "circle" })),
{ href: "/settings", label: "Settings", icon: "settings" },
];
return (
<nav className="bottom-nav" aria-label="Primary navigation">
{items.map((it) => (
<NavLink key={it.href} href={it.href} icon={it.icon} label={it.label} variant="bottom" />
))}
</nav>
);
}
+32
View File
@@ -0,0 +1,32 @@
import { cn } from "@/lib/utils";
export function BrandMark({ size = "md", className }: { size?: "sm" | "md"; className?: string }) {
const iconSize = size === "sm" ? 14 : 17;
return (
<span
className={cn("brand-mark", size === "sm" && "brand-mark-sm", className)}
aria-hidden="true"
>
<svg
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
width={iconSize}
height={iconSize}
fill="currentColor"
>
<polygon points="12,2 1,12 23,12" />
<rect x="3.5" y="11" width="17" height="12" />
<rect x="9.5" y="16" width="5" height="7" rx="1" style={{ fill: "var(--ink)" }} />
</svg>
</span>
);
}
export function BrandWordmark({ className }: { className?: string }) {
return (
<span className={cn("brand", className)}>
<BrandMark />
<span className="brand-name">famapp</span>
</span>
);
}
+54 -5
View File
@@ -7,8 +7,9 @@ import { useEffect, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { GridLayout } from "react-grid-layout";
import type { Layout } from "react-grid-layout";
import { GripVertical, Settings2, Trash2, RotateCcw, Plus } from "lucide-react";
import type { DashboardLayout, WidgetPlacement } from "@/lib/dashboard";
import { GripVertical, Settings2, Trash2, RotateCcw, Plus, LayoutGrid } from "lucide-react";
import type { DashboardLayout, WidgetPlacement, PresetId } from "@/lib/dashboard";
import { computePresetLayoutFromMetas } from "@/lib/dashboard";
import type { SerializedWidgetMeta } from "@/modules/_core/registry";
import { saveDashboardLayout, resetDashboardLayout } from "@/app/d/actions";
import { Button } from "@/components/ui/button";
@@ -34,6 +35,7 @@ export function DashboardEditor({
const [pickerOpen, setPickerOpen] = useState(false);
const [configuringIndex, setConfiguringIndex] = useState<number | null>(null);
const [containerWidth, setContainerWidth] = useState(1200);
const [presetMenuOpen, setPresetMenuOpen] = useState(false);
useEffect(() => {
function measure() {
@@ -107,6 +109,13 @@ export function DashboardEditor({
setConfiguringIndex(null);
}
function applyPreset(preset: PresetId) {
const next = computePresetLayoutFromMetas(preset, widgetMetas);
setPlacements(next.widgets);
setIsDirty(true);
setPresetMenuOpen(false);
}
const gridItems: Layout = placements.map((p, i) => ({
i: placementKey(p, i),
x: p.x,
@@ -119,10 +128,50 @@ export function DashboardEditor({
}));
return (
<div className="p-4 sm:p-6">
<div>
<div className="mb-6 flex items-center justify-between gap-4 flex-wrap">
<h1 className="text-2xl font-bold">{dashboard.name}</h1>
<div className="flex items-center gap-2 flex-wrap">
<h1 className="serif text-[26px] tracking-tight">{dashboard.name}</h1>
<div className="flex items-center gap-2 flex-wrap relative">
<div className="relative">
<Button
variant="outline"
size="sm"
onClick={() => setPresetMenuOpen((o) => !o)}
disabled={isPending}
>
<LayoutGrid className="size-4 mr-1" />
Preset
</Button>
{presetMenuOpen && (
<div
className="absolute right-0 top-9 z-50 min-w-[180px] rounded-md border-[0.5px] bg-card shadow-[var(--shadow-pop)]"
style={{ borderColor: "var(--hair-2)" }}
onMouseLeave={() => setPresetMenuOpen(false)}
>
<button
type="button"
onClick={() => applyPreset("classic")}
className="block w-full text-left px-3 py-2 text-sm hover:bg-[var(--shade)]"
>
Classic main + side rail
</button>
<button
type="button"
onClick={() => applyPreset("split")}
className="block w-full text-left px-3 py-2 text-sm hover:bg-[var(--shade)]"
>
Split two even columns
</button>
<button
type="button"
onClick={() => applyPreset("glance")}
className="block w-full text-left px-3 py-2 text-sm hover:bg-[var(--shade)]"
>
Glance single column
</button>
</div>
)}
</div>
<Button variant="outline" size="sm" onClick={handleReset} disabled={isPending}>
<RotateCcw className="size-4 mr-1" />
Reset
+1 -5
View File
@@ -7,11 +7,7 @@ export function EditDashboardButton() {
const pathname = usePathname();
return (
<button
type="button"
onClick={() => router.push(`${pathname}?edit=1`)}
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm font-medium shadow-sm hover:bg-accent hover:text-accent-foreground transition-colors"
>
<button type="button" onClick={() => router.push(`${pathname}?edit=1`)} className="btn btn-sm">
Edit dashboard
</button>
);
+14
View File
@@ -0,0 +1,14 @@
"use client";
import { useQuickAdd } from "@/components/quick-add-provider";
import { NavIcon } from "@/components/nav-icon";
export function Fab() {
const { openSheet } = useQuickAdd();
return (
<button type="button" className="fab" aria-label="Quick add" onClick={openSheet}>
<NavIcon name="plus" className="size-6" strokeWidth={2.4} />
</button>
);
}
+32 -17
View File
@@ -70,36 +70,51 @@ export function InstallPrompt() {
return (
<div
role="banner"
className="fixed bottom-0 left-0 right-0 z-50 flex items-start gap-3 border-t bg-background px-4 py-3 shadow-lg sm:bottom-4 sm:left-1/2 sm:right-auto sm:-translate-x-1/2 sm:rounded-xl sm:border sm:px-5 sm:py-4 sm:shadow-xl"
className="fixed bottom-[80px] left-0 right-0 z-50 flex items-start gap-3 px-4 py-3 sm:bottom-4 sm:left-1/2 sm:right-auto sm:-translate-x-1/2 sm:px-5 sm:py-4"
style={{
background: "var(--card)",
border: "0.5px solid var(--hair-2)",
borderRadius: "var(--r-lg)",
boxShadow: "var(--shadow-pop)",
margin: "0 14px",
}}
>
{/* App icon */}
<div className="mt-0.5 h-10 w-10 shrink-0 overflow-hidden rounded-xl bg-[#4F46E5]">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src="/icon-192.png" alt="" className="h-full w-full object-cover" />
<div
className="mt-0.5 size-10 shrink-0 overflow-hidden flex items-center justify-center"
style={{
borderRadius: 8,
background: "var(--ink)",
color: "var(--paper)",
fontFamily: "var(--serif)",
fontSize: 18,
fontWeight: 500,
}}
>
f
</div>
<div className="flex-1 text-sm">
<p className="font-semibold leading-snug">Add famapp to your home screen</p>
<div className="flex-1 text-[13.5px]">
<p className="font-medium leading-snug text-[var(--ink)] m-0">
Add famapp to your home screen
</p>
{prompt === "android" && (
<>
<p className="mt-0.5 text-muted-foreground">
<p className="mt-1 muted text-[12.5px] m-0">
Install for a faster, app-like experience.
</p>
<button
onClick={install}
className="mt-2 rounded-md bg-[#4F46E5] px-3 py-1.5 text-xs font-semibold text-white"
>
<button onClick={install} className="btn btn-sm btn-primary mt-2">
Install
</button>
</>
)}
{prompt === "ios" && (
<p className="mt-0.5 text-muted-foreground">
Tap <Share className="inline-block h-4 w-4 align-text-bottom" aria-label="Share" /> then{" "}
<p className="mt-1 muted text-[12.5px] m-0">
Tap <Share className="inline-block size-3.5 align-text-bottom" aria-label="Share" />{" "}
then{" "}
<strong className="font-medium">
<Plus className="inline-block h-3.5 w-3.5 align-text-bottom" />
<Plus className="inline-block size-3 align-text-bottom" />
&nbsp;Add to Home Screen
</strong>
.
@@ -110,9 +125,9 @@ export function InstallPrompt() {
<button
onClick={dismiss}
aria-label="Dismiss"
className="mt-0.5 shrink-0 rounded p-1 text-muted-foreground hover:bg-muted"
className="mt-0.5 shrink-0 rounded p-1 text-[var(--ink-mute)] hover:bg-[var(--shade)]"
>
<X className="h-4 w-4" />
<X className="size-4" />
</button>
</div>
);
+85
View File
@@ -0,0 +1,85 @@
import {
Bell,
Calendar,
Sprout,
CalendarDays,
CheckSquare,
ChevronDown,
ChevronLeft,
ChevronRight,
Circle,
Clock,
Eye,
FileText,
Filter,
Globe,
History,
Home,
Link as LinkIcon,
ListChecks,
Lock,
Mail,
Menu,
MoreHorizontal,
Pencil,
Phone,
Pin,
PinOff,
Plus,
Search,
Settings,
Share2,
ShoppingCart,
Sparkles,
Sun,
Trash2,
Users,
X,
} from "lucide-react";
import type { LucideProps } from "lucide-react";
const ICONS: Record<string, React.ComponentType<LucideProps>> = {
home: Home,
calendar: Calendar,
"calendar-days": CalendarDays,
list: ListChecks,
"check-square": CheckSquare,
"file-text": FileText,
note: FileText,
settings: Settings,
history: History,
link: LinkIcon,
people: Users,
users: Users,
plus: Plus,
search: Search,
bell: Bell,
pin: Pin,
"pin-off": PinOff,
cart: ShoppingCart,
"shopping-cart": ShoppingCart,
share: Share2,
lock: Lock,
eye: Eye,
clock: Clock,
sparkles: Sparkles,
pencil: Pencil,
trash: Trash2,
globe: Globe,
phone: Phone,
filter: Filter,
sun: Sun,
sprout: Sprout,
mail: Mail,
menu: Menu,
more: MoreHorizontal,
x: X,
"chevron-left": ChevronLeft,
"chevron-right": ChevronRight,
"chevron-down": ChevronDown,
};
export function NavIcon({ name, ...rest }: { name: string } & LucideProps) {
const Icon = ICONS[name] ?? Circle;
return <Icon strokeWidth={1.6} {...rest} />;
}
+55
View File
@@ -0,0 +1,55 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { NavIcon } from "@/components/nav-icon";
import { cn } from "@/lib/utils";
function isActive(pathname: string, href: string): boolean {
// Strip query/fragment from href before matching.
const cleaned = href.split("#")[0]?.split("?")[0] ?? href;
if (cleaned === "/") return pathname === "/" || pathname.startsWith("/d/");
return pathname === cleaned || pathname.startsWith(cleaned + "/");
}
interface Props {
href: string;
icon: string;
label: string;
className?: string;
iconClassName?: string;
variant?: "sidebar" | "bottom";
}
export function NavLink({
href,
icon,
label,
className,
iconClassName,
variant = "sidebar",
}: Props) {
const pathname = usePathname() ?? "";
const active = isActive(pathname, href);
if (variant === "bottom") {
return (
<Link href={href} aria-current={active ? "page" : undefined} className={className}>
<NavIcon name={icon} className={cn("size-5", iconClassName)} />
<span>{label}</span>
</Link>
);
}
return (
<Link
href={href}
aria-current={active ? "page" : undefined}
className={cn("nav-item", className)}
title={label}
>
<NavIcon name={icon} className={cn("size-4", iconClassName)} />
<span className="nav-label">{label}</span>
</Link>
);
}
+29
View File
@@ -0,0 +1,29 @@
"use client";
import { useEffect } from "react";
import type { NavStyle } from "@/modules/_core/themes";
import { navStyleToDataNav } from "@/modules/_core/themes";
const MOBILE_QUERY = "(max-width: 759px)";
/** Listens to the mobile breakpoint and overrides data-nav on <html>.
* The pre-paint script in layout.tsx already applies the correct value
* on first paint; this picks up subsequent resizes. Runs once and stays
* mounted as long as the shell is mounted. */
export function NavModeProvider({ navStyle }: { navStyle: NavStyle }) {
useEffect(() => {
const html = document.documentElement;
const desktopNav = navStyleToDataNav(navStyle);
const apply = () => {
const isMobile = window.matchMedia(MOBILE_QUERY).matches;
const next = isMobile ? (navStyle === "fab-only" ? "fab" : "bottom") : desktopNav;
html.setAttribute("data-nav", next);
};
apply();
const mq = window.matchMedia(MOBILE_QUERY);
mq.addEventListener("change", apply);
return () => mq.removeEventListener("change", apply);
}, [navStyle]);
return null;
}
+24 -4
View File
@@ -1,6 +1,6 @@
"use client";
import { useState, useTransition } from "react";
import { useState, useTransition, useEffect } from "react";
import { Button } from "@/components/ui/button";
import {
subscribeToPush,
@@ -23,6 +23,20 @@ export function PushOptIn({ vapidKey }: { vapidKey: string }) {
const [isPending, startTransition] = useTransition();
const [testSent, setTestSent] = useState(false);
// Hydrate subscription state from the browser on mount so the UI reflects
// reality even when the user navigates away and returns to Settings.
useEffect(() => {
if (!vapidKey || !("serviceWorker" in navigator) || !("PushManager" in window)) return;
navigator.serviceWorker.ready.then((reg) =>
reg.pushManager.getSubscription().then((existing) => {
if (existing) {
setEndpoint(existing.endpoint);
setStatus("subscribed");
}
}),
);
}, [vapidKey]);
if (!vapidKey) return null;
if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
return (
@@ -35,10 +49,15 @@ export function PushOptIn({ vapidKey }: { vapidKey: string }) {
async function subscribe() {
try {
const registration = await navigator.serviceWorker.ready;
const sub = await registration.pushManager.subscribe({
// Reuse an existing browser subscription rather than calling subscribe()
// again — avoids redundant prompts and inconsistent behaviour on iOS.
const existing = await registration.pushManager.getSubscription();
const sub =
existing ??
(await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidKey),
});
}));
const json = sub.toJSON() as { endpoint: string; keys: { p256dh: string; auth: string } };
startTransition(async () => {
await subscribeToPush(json, navigator.userAgent);
@@ -63,8 +82,9 @@ export function PushOptIn({ vapidKey }: { vapidKey: string }) {
}
function sendTest() {
if (!endpoint) return;
startTransition(async () => {
await sendTestNotification();
await sendTestNotification(endpoint);
setTestSent(true);
setTimeout(() => setTestSent(false), 3000);
});
-17
View File
@@ -1,17 +0,0 @@
"use client";
import { useQuickAdd } from "./quick-add-provider";
export function QuickAddFab() {
const { openSheet } = useQuickAdd();
return (
<button
aria-label="Quick add"
onClick={openSheet}
className="flex h-10 w-10 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-md transition-opacity hover:opacity-90"
>
<span className="text-xl leading-none">+</span>
</button>
);
}
+88 -28
View File
@@ -2,7 +2,9 @@
import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { Sparkles, X } from "lucide-react";
import { useQuickAdd } from "./quick-add-provider";
import { NavIcon } from "./nav-icon";
import type { SerializedQuickAddItem } from "@/modules/_core";
function groupByModule(
@@ -18,8 +20,23 @@ function groupByModule(
return map;
}
const QUICK_ADD_ICON: Record<string, string> = {
"calendar-plus": "calendar",
"calendar-days": "calendar",
"shopping-cart": "cart",
"list-checks": "check-square",
"list-plus": "list",
"file-plus": "note",
};
function useShortcutLabel() {
if (typeof navigator === "undefined") return "⌘K";
return /Mac|iPhone|iPad|iPod/.test(navigator.platform) ? "⌘K" : "Ctrl+K";
}
export function QuickAddSheet() {
const { sheetOpen, closeSheet, actions } = useQuickAdd();
const shortcut = useShortcutLabel();
const router = useRouter();
const backdropRef = useRef<HTMLDivElement>(null);
@@ -43,64 +60,107 @@ export function QuickAddSheet() {
return (
<>
{/* Backdrop */}
<div
ref={backdropRef}
className="fixed inset-0 z-40 bg-black/40"
className="fixed inset-0 z-40"
style={{ background: "rgba(31,27,22,.32)", backdropFilter: "blur(2px)" }}
onClick={closeSheet}
aria-hidden="true"
/>
{/* Sheet panel — bottom on mobile, right-anchored popover on sm+ */}
<div
role="dialog"
aria-modal="true"
aria-label="Quick add"
className="fixed bottom-0 left-0 right-0 z-50 rounded-t-2xl bg-background shadow-xl sm:bottom-auto sm:left-auto sm:right-6 sm:top-16 sm:w-72 sm:rounded-xl"
className="fixed bottom-0 left-0 right-0 z-50 sm:bottom-auto sm:left-1/2 sm:top-24 sm:-translate-x-1/2 sm:w-[480px] sm:max-w-[calc(100vw-32px)]"
style={{
background: "var(--paper)",
borderRadius: "18px 18px 0 0",
boxShadow: "0 -8px 32px rgba(31,27,22,.16)",
overflow: "hidden",
}}
>
<div className="flex items-center justify-between border-b px-4 py-3">
<span className="text-sm font-semibold">Quick add</span>
<div
style={{
padding: "16px 18px 12px",
display: "flex",
alignItems: "center",
justifyContent: "space-between",
borderBottom: "0.5px solid var(--hair)",
}}
>
<h2
className="serif"
style={{ fontSize: 18, fontWeight: 500, margin: 0, color: "var(--ink)" }}
>
Quick add
</h2>
<button
onClick={closeSheet}
aria-label="Close quick add"
className="rounded p-1 text-muted-foreground hover:bg-muted"
className="btn btn-icon btn-ghost btn-sm"
>
<X className="size-3.5" />
</button>
</div>
<div className="max-h-[60vh] overflow-y-auto p-2 sm:max-h-96">
{[...groups.entries()].map(([moduleId, group]) => (
<div key={moduleId} className="mb-2">
<p className="px-2 py-1 text-xs font-medium uppercase tracking-wide text-muted-foreground">
<div style={{ padding: "14px 18px" }}>
<div
className="muted"
style={{
fontSize: 12,
marginBottom: 14,
display: "flex",
alignItems: "center",
gap: 6,
}}
>
<Sparkles className="size-3" />
<span>Pick what to add or use {shortcut} to search.</span>
</div>
<div className="max-h-[60vh] overflow-y-auto">
{[...groups.entries()].map(([moduleId, group], i) => (
<div key={moduleId} className="mb-2.5">
<div className="eyebrow mb-2" style={{ marginTop: i === 0 ? 0 : 8 }}>
{group.name}
</p>
</div>
<div className="grid grid-cols-2 gap-1.5">
{group.items.map((action) => (
<button
key={action.id}
onClick={() => handleAction(action.url)}
className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground"
className="btn btn-sm justify-start"
>
<span className="text-base leading-none">{iconEmoji(action.icon)}</span>
{action.label}
<NavIcon
name={QUICK_ADD_ICON[action.icon ?? ""] ?? "plus"}
className="size-3.5"
/>
<span className="truncate">{action.label}</span>
</button>
))}
</div>
</div>
))}
</div>
</div>
<div
className="dialog-foot"
style={{
padding: "12px 18px",
display: "flex",
gap: 8,
justifyContent: "flex-end",
borderTop: "0.5px solid var(--hair)",
background: "var(--paper-2)",
}}
>
<button className="btn btn-sm btn-ghost" onClick={closeSheet}>
Close
</button>
</div>
</div>
</>
);
}
function iconEmoji(icon?: string): string {
const map: Record<string, string> = {
"calendar-plus": "📅",
"calendar-days": "🗓️",
"shopping-cart": "🛒",
"list-checks": "✅",
"list-plus": "📋",
"file-plus": "📝",
};
return icon ? (map[icon] ?? "") : "";
}
+121
View File
@@ -0,0 +1,121 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { NavIcon } from "@/components/nav-icon";
import { cn } from "@/lib/utils";
const SECTIONS = [
{ id: "household", label: "Household", icon: "people" },
{ id: "sharing", label: "Sharing & links", icon: "link" },
{ id: "notifications", label: "Notifications", icon: "bell" },
{ id: "calendars", label: "Calendars & lists", icon: "calendar" },
{ id: "appearance", label: "Appearance", icon: "sun" },
{ id: "data", label: "Data & backups", icon: "history" },
] as const;
export type SectionId = (typeof SECTIONS)[number]["id"];
export function SettingsSidebar({ active }: { active: SectionId }) {
const router = useRouter();
const pathname = usePathname();
return (
<nav
className="rounded-[var(--r-lg)] border-[0.5px] bg-[var(--card)] shadow-[var(--shadow-1)] h-fit"
style={{ borderColor: "var(--hair)" }}
aria-label="Settings sections"
>
<div className="card-h">
<h3 className="serif text-[15px] m-0 font-medium">Settings</h3>
</div>
<div className="p-1.5">
{SECTIONS.map((s) => (
<button
key={s.id}
type="button"
className={cn("nav-item h-9")}
aria-current={active === s.id ? "page" : undefined}
onClick={() => {
const url = new URL(window.location.href);
url.searchParams.set("s", s.id);
router.replace(url.pathname + "?" + url.searchParams.toString() + url.hash, {
scroll: false,
});
}}
>
<NavIcon name={s.icon} className="size-4" />
<span className="nav-label">{s.label}</span>
</button>
))}
<div className="nav-divider" />
<Link href="/settings/household" className="nav-item h-9">
<NavIcon name="users" className="size-4" />
<span className="nav-label">Manage household</span>
</Link>
</div>
<SectionHashSync pathname={pathname} />
</nav>
);
}
// When the URL changes with a hash like #sharing (used by sidebar Share-links link),
// ensure the matching section opens.
function SectionHashSync({ pathname }: { pathname: string | null }) {
const router = useRouter();
const searchParams = useSearchParams();
useEffect(() => {
if (typeof window === "undefined") return;
const hash = window.location.hash.slice(1);
if (!hash) return;
if (!SECTIONS.some((s) => s.id === hash)) return;
if (searchParams?.get("s") === hash) return;
const url = new URL(window.location.href);
url.searchParams.set("s", hash);
router.replace(url.pathname + "?" + url.searchParams.toString(), { scroll: false });
}, [pathname, router, searchParams]);
return null;
}
export function SettingsTabsMobile({ active }: { active: SectionId }) {
const router = useRouter();
return (
<div className="grid grid-cols-2 gap-1.5 mb-1">
{SECTIONS.map((s) => (
<button
key={s.id}
type="button"
aria-current={active === s.id ? "page" : undefined}
className={cn(
"flex items-center gap-2.5 px-3 py-2.5 rounded-[var(--r-md)] border-[0.5px] text-left text-[13px] font-medium transition-colors",
active === s.id
? "bg-[var(--card)] border-[var(--hair-2)] text-[var(--ink)] shadow-[var(--shadow-1)]"
: "border-transparent text-[var(--ink-soft)] hover:bg-[var(--shade)]",
)}
onClick={() => {
const url = new URL(window.location.href);
url.searchParams.set("s", s.id);
router.replace(url.pathname + "?" + url.searchParams.toString(), { scroll: false });
}}
>
<NavIcon name={s.icon} className="size-4 shrink-0" />
<span>{s.label.split(" ")[0]}</span>
</button>
))}
</div>
);
}
export function ResponsiveSidebar({ active }: { active: SectionId }) {
const [isMobile, setIsMobile] = useState(false);
useEffect(() => {
const mq = window.matchMedia("(max-width: 759px)");
const apply = () => setIsMobile(mq.matches);
apply();
mq.addEventListener("change", apply);
return () => mq.removeEventListener("change", apply);
}, []);
if (isMobile) return <SettingsTabsMobile active={active} />;
return <SettingsSidebar active={active} />;
}
+9
View File
@@ -19,15 +19,21 @@ export function ShareButton({
const [open, setOpen] = useState(false);
const [shareUrl, setShareUrl] = useState<string | null>(null);
const [copied, setCopied] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
function share() {
setError(null);
startTransition(async () => {
try {
const result = await createShareLink(entityType, entityId, {
capabilities: { read: true, write: canWrite },
});
setShareUrl(result.url);
setOpen(true);
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to create share link");
}
});
}
@@ -41,10 +47,13 @@ export function ShareButton({
return (
<>
<div className="flex flex-col items-end gap-1">
<Button variant="outline" onClick={share} disabled={isPending}>
<Link />
Share
</Button>
{error && <p className="text-xs text-red-500">{error}</p>}
</div>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
+53
View File
@@ -0,0 +1,53 @@
"use client";
import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { revokeShareLink } from "@/modules/_core/share";
import type { EntityShareLink } from "@/modules/_core/share";
type Props = {
links: EntityShareLink[];
};
export function ShareLinkList({ links }: Props) {
const [isPending, startTransition] = useTransition();
const router = useRouter();
if (links.length === 0) return null;
function handleRevoke(id: string) {
startTransition(async () => {
await revokeShareLink(id);
router.refresh();
});
}
return (
<div className="flex flex-col gap-1 pt-1 border-t border-[var(--ink-faint)]">
<p className="text-xs font-semibold uppercase text-[var(--ink-mute)] tracking-wide">
Active share links ({links.length})
</p>
{links.map((link) => (
<div key={link.id} className="flex items-center justify-between gap-2 text-sm py-0.5">
<div className="flex flex-col">
<span className="text-[var(--ink-mute)]">
Created {new Date(link.createdAt).toLocaleDateString()}
</span>
{link.expiresAt && (
<span className="text-xs text-[var(--ink-mute)]">
Expires {new Date(link.expiresAt).toLocaleDateString()}
</span>
)}
</div>
<button
className="btn btn-ghost btn-sm text-red-500 hover:text-red-600"
onClick={() => handleRevoke(link.id)}
disabled={isPending}
>
Revoke
</button>
</div>
))}
</div>
);
}
+43
View File
@@ -0,0 +1,43 @@
interface Props {
date: Date;
/** Optional time string e.g. "7:30 9:30 pm" */
time?: string;
}
export function MiniDayCard({ date, time }: Props) {
const month = date.toLocaleDateString(undefined, { weekday: "short", month: "short" });
const day = date.getDate();
return (
<div
className="rounded-[var(--r-md)] p-4"
style={{
background: "var(--card)",
border: "0.5px solid var(--hair)",
}}
>
<div
style={{
fontFamily: "var(--mono)",
fontSize: 11,
color: "var(--bad)",
textTransform: "uppercase",
letterSpacing: "0.08em",
}}
>
{month}
</div>
<div
style={{
fontFamily: "var(--serif)",
fontSize: 32,
lineHeight: 1,
color: "var(--ink)",
margin: "6px 0 4px",
}}
>
{day}
</div>
{time && <div style={{ fontSize: 13, color: "var(--ink-soft)" }}>{time}</div>}
</div>
);
}

Some files were not shown because too many files have changed in this diff Show More