Code-side

src/lib/dev-login-config.ts — startup assertion: throws if NODE_ENV=production + ENABLE_DEV_LOGIN=true, scoped to runtime (skipped during next build).
Container

scripts/migrate.mjs — runs Drizzle migrations against DATABASE_URL.
deploy/docker-entrypoint.sh — runs migrations then exec node server.js. Skip with RUN_MIGRATIONS=false.
Dockerfile — copies drizzle/, scripts/migrate.mjs, entrypoint into runner stage; ENTRYPOINT now points at the script.
Compose

deploy/compose.yaml — famapp now image: ${FAMAPP_IMAGE:-ghcr.io/ginnoir/famapp:latest} (build still works locally as fallback). Authentik pinned via AUTHENTIK_IMAGE_TAG (default 2024.12.3). New RUN_MIGRATIONS env passed through.
.env.production.example — documents FAMAPP_IMAGE, AUTHENTIK_IMAGE_TAG, RUN_MIGRATIONS.
CI/CD

.github/workflows/ci.yml — push/PR: typecheck + lint + format:check + build.
.github/workflows/release.yml — v* tag: build + push ghcr.io/ginnoir/famapp:vX.Y.Z, :X.Y, :latest to GHCR.
Docs

deploy/README.md — full deploy/rollback/release runbook.
CHANGELOG.md — release log seeded with an Unreleased entry.
docs/tasks/09-pre-deploy-checklist.md — task 09 reframed from one-shot removal to a recurring pre-deploy checklist.
STATUS.md — updated.
Verified: pnpm typecheck, pnpm format, pnpm build, and docker compose config all clean.
This commit is contained in:
ginnoir
2026-05-06 17:37:37 -05:00
parent 285a460eb8
commit c73338e256
73 changed files with 955 additions and 728 deletions
+10
View File
@@ -1,5 +1,15 @@
# ── famapp ────────────────────────────────────────────────────────────────────
# 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 in share links, OIDC redirect URIs, etc.)
NEXT_PUBLIC_APP_URL=https://fam.ginnoir.com
+37
View File
@@ -0,0 +1,37 @@
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
verify:
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: 22
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm typecheck
- run: pnpm lint
- run: pnpm format:check
- 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
+42
View File
@@ -0,0 +1,42 @@
name: Release
on:
push:
tags:
- "v*"
permissions:
contents: read
packages: write
jobs:
build-and-push:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- id: meta
uses: docker/metadata-action@v5
with:
images: ghcr.io/${{ github.repository }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,value=latest
- uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
+9
View File
@@ -0,0 +1,9 @@
# Changelog
One line per release. "What's in prod" = the highest tag listed under a date that's been deployed.
Format: `## vX.Y.Z — YYYY-MM-DD`
## Unreleased
- Production deployment scaffolding: tag-based release workflow (GHCR), migration entrypoint in container, prod-side dev-login startup assertion, image-pinned compose, pre-deploy checklist.
+8 -1
View File
@@ -32,6 +32,13 @@ COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
# Migration assets — drizzle/ holds SQL + meta journal; migrate.mjs uses
# drizzle-orm + postgres which Next.js standalone already traces in.
COPY --from=builder --chown=nextjs:nodejs /app/drizzle ./drizzle
COPY --from=builder --chown=nextjs:nodejs /app/scripts/migrate.mjs ./scripts/migrate.mjs
COPY --chown=nextjs:nodejs deploy/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
+1
View File
@@ -43,6 +43,7 @@ Living progress tracker. Update at the end of each task. Codex and Claude Code b
## Next up
- Phase 7 hardening complete. All acceptance criteria met for tasks 60, 61, 62.
- **09 — Production prep** (scaffolding landed): tag-based release workflow (`.github/workflows/release.yml` → GHCR), CI on push/PR (`.github/workflows/ci.yml`), migration entrypoint in container (`scripts/migrate.mjs` + `deploy/docker-entrypoint.sh`), startup assertion in `src/lib/dev-login-config.ts`, image-pinned compose with `FAMAPP_IMAGE`/`AUTHENTIK_IMAGE_TAG`, `deploy/README.md`, `CHANGELOG.md`. Task 09 itself is now a recurring pre-deploy checklist (`docs/tasks/09-pre-deploy-checklist.md`); run it before every tag.
## Development login/testing notes
+45
View File
@@ -0,0 +1,45 @@
# Deploying famapp
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.
## 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.
- `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`.
## Cutting a release
```bash
# from your dev machine, on main, with a clean working tree
git tag v0.1.0
git push origin v0.1.0
```
`.github/workflows/release.yml` builds + pushes `ghcr.io/ginnoir/famapp:v0.1.0`, `:0.1`, and `:latest` to GHCR.
## Deploying a release on the host
```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
docker compose pull famapp
docker compose up -d famapp
docker compose logs -f famapp # watch migrations + boot
```
The container's entrypoint runs `node scripts/migrate.mjs` before starting the server. To skip migrations on a given start (rare — e.g. emergency rollback to an older schema-compatible image), set `RUN_MIGRATIONS=false`.
## Rollback
Edit `.env` to point `FAMAPP_IMAGE` at the previous tag, then `docker compose up -d famapp`. If the rollback target predates a migration that's already applied, restore from backup (`deploy/backups/README.md`) before bringing the older image up.
## Pre-deploy checklist
Run [docs/tasks/09-pre-deploy-checklist.md](../docs/tasks/09-pre-deploy-checklist.md) before every deploy.
+1 -1
View File
@@ -23,7 +23,7 @@ compression, ~35× smaller than plain SQL).
## Retention
| Tier | Kept | Trigger |
| ------- | ---- | --------------------- |
| ------- | ---- | ---------------- |
| daily | 14 | every night |
| weekly | 8 | Sunday night |
| monthly | 6 | 1st of the month |
+11
View File
@@ -0,0 +1,11 @@
#!/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
+12 -4
View File
@@ -25,11 +25,19 @@ Cheap to set up before modules exist, painful to retrofit afterwards. Locking in
Use shadcn's CSS-variable conventions, scoped by `data-theme` on `<html>`:
```css
:root { /* default light tokens */ }
.dark { /* default dark tokens */ }
:root {
/* default light tokens */
}
.dark {
/* default dark tokens */
}
[data-theme="warm"] { /* warm light */ }
[data-theme="warm"].dark { /* warm dark */ }
[data-theme="warm"] {
/* warm light */
}
[data-theme="warm"].dark {
/* warm dark */
}
```
Ship at least **two** themes (`default` + one more) so the architecture is actually exercised. Token values can be placeholder — refining the palettes is a separate later concern.
+36
View File
@@ -0,0 +1,36 @@
# 09 — Pre-deploy checklist (recurring)
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.
## Env hygiene
- [ ] Server `.env` (next to `deploy/compose.yaml`) does **not** set:
- `ENABLE_DEV_LOGIN`
- `DEV_LOGIN_EMAIL`, `DEV_LOGIN_NAME`, `DEV_HOUSEHOLD_NAME`
- [ ] Server `.env` sets real values for:
- `NEXT_PUBLIC_APP_URL` (https)
- `AUTH_SECRET` (`openssl rand -base64 32`)
- `AUTH_OIDC_ISSUER`, `AUTH_OIDC_CLIENT_ID`, `AUTH_OIDC_CLIENT_SECRET`
- `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY`, `VAPID_SUBJECT`
- `FAMAPP_DB_*`, `AUTHENTIK_DB_*`, `AUTHENTIK_SECRET_KEY`
- [ ] `FAMAPP_IMAGE` pins a specific version tag (`ghcr.io/ginnoir/famapp:vX.Y.Z`), not `latest`, after first deploy.
## Code-side guard
`src/lib/dev-login-config.ts` throws on import if `NODE_ENV=production` and `ENABLE_DEV_LOGIN=true`. Container will refuse to start.
- [ ] Confirm guard is still present (do not remove without updating this checklist).
## Smoke after deploy
- [ ] `https://fam.ginnoir.com/login` shows only **Sign in with SSO** (no Dev login button).
- [ ] Real Authentik sign-in succeeds, lands on dashboard.
- [ ] First user appears in DB with household membership, default calendars, default lists.
- [ ] No `dev@famapp.local` row in production `users` table.
- [ ] Push opt-in works (settings → enable → test notification arrives).
- [ ] A share link created from `/settings` resolves at `/s/<token>` while signed out.
## Backup / rollback
- [ ] Last `famapp-backup` cron run succeeded (check container logs).
- [ ] Previous image tag is known and recorded in `CHANGELOG.md`, so rollback = bump `FAMAPP_IMAGE` and `docker compose up -d famapp`.
@@ -1,47 +0,0 @@
# 09 — Production dev-login removal gate
## Goal
Before the first production deployment, verify that development-only login/test shortcuts cannot be enabled accidentally in production.
## Depends on
- 06
- 07
- local dev-login setup in `docs/dev-login.md`
## Scope
- Review all production env sources:
- `.env.production.example`
- `deploy/compose.yaml`
- any host-level Docker Compose override files
- deployment secrets on the server
- Confirm production does not set:
- `ENABLE_DEV_LOGIN=true`
- `DEV_LOGIN_EMAIL`
- `DEV_LOGIN_NAME`
- `DEV_HOUSEHOLD_NAME`
- Confirm production Authentik variables are real:
- `AUTH_OIDC_ISSUER`
- `AUTH_OIDC_CLIENT_ID`
- `AUTH_OIDC_CLIENT_SECRET`
- Build with production-like env and verify `/login` renders only the SSO login path.
- Verify the app still protects private routes without a valid Auth.js session cookie.
- Verify real Authentik login creates the expected user, household membership, default calendars, and default lists.
- Remove any accidental dev users from the production database.
## Optional hardening
- Remove `src/lib/dev-login.ts` and the Dev login form from `src/app/login/page.tsx` entirely before first production deployment.
- If retaining the code for future local development, keep the current double gate:
- `NODE_ENV !== "production"`
- `ENABLE_DEV_LOGIN=true`
## Acceptance criteria
- [ ] Production env cannot enable Dev login accidentally.
- [ ] `/login` in production does not show **Dev login**.
- [ ] Direct dev-login action execution is unavailable in production.
- [ ] Real Authentik login works on the production domain.
- [ ] No `dev@famapp.local` or configured dev-login user exists in production data.
+1 -1
View File
@@ -6,7 +6,7 @@ Implement the `calendar` module: first-class **calendars** (multiple per househo
## Why
Calendars are entities, not a singleton concept. A user might run a *Personal* (private) calendar, a *Family* (household-shared) calendar, and a *Wedding planning* calendar that gets share-linked publicly. The calendar module ships that abstraction; widgets and the share-link service then reuse it generically.
Calendars are entities, not a singleton concept. A user might run a _Personal_ (private) calendar, a _Family_ (household-shared) calendar, and a _Wedding planning_ calendar that gets share-linked publicly. The calendar module ships that abstraction; widgets and the share-link service then reuse it generically.
## Depends on
+1 -1
View File
@@ -6,7 +6,7 @@ Each user can create any number of named dashboards, switch between them, and ch
## Why
Decouples "the dashboard" from "user's home page". A user might have a *Daily*, *Garden*, and *Wedding planning* dashboard, each composing different widgets. This task introduces the entity; task 26 adds the editor.
Decouples "the dashboard" from "user's home page". A user might have a _Daily_, _Garden_, and _Wedding planning_ dashboard, each composing different widgets. This task introduces the entity; task 26 adds the editor.
## Depends on
+9 -2
View File
@@ -52,8 +52,15 @@ Same component is reused for **Configure** on an already-placed widget. Re-runs
{
"version": 1,
"widgets": [
{ "widgetId": "lists.list", "config": { "listIds": ["..."], "showCompleted": false }, "x": 0, "y": 0, "w": 6, "h": 4 }
]
{
"widgetId": "lists.list",
"config": { "listIds": ["..."], "showCompleted": false },
"x": 0,
"y": 0,
"w": 6,
"h": 4,
},
],
}
```
+1 -8
View File
@@ -5,14 +5,7 @@ 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/**", "dist/**", "drizzle/**", "public/sw.js"],
},
js.configs.recommended,
...tseslint.configs.recommended,
+1 -2
View File
@@ -3,8 +3,7 @@ import { writeFileSync } from "fs";
import { resolve } from "path";
// Stable in dev to avoid cache churn on hot-reload; unique per production build.
const BUILD_TIME =
process.env.NODE_ENV === "development" ? "dev" : String(Date.now());
const BUILD_TIME = process.env.NODE_ENV === "development" ? "dev" : String(Date.now());
writeFileSync(resolve(process.cwd(), "public/sw.js"), buildSwContent(BUILD_TIME));
+34 -10
View File
@@ -1,4 +1,4 @@
<!DOCTYPE html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
@@ -6,12 +6,24 @@
<meta name="theme-color" content="#4F46E5" />
<title>famapp — offline</title>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
:root { --indigo: #4F46E5; --indigo-light: #E0E7FF; }
:root {
--indigo: #4f46e5;
--indigo-light: #e0e7ff;
}
body {
font-family: system-ui, -apple-system, sans-serif;
font-family:
system-ui,
-apple-system,
sans-serif;
min-height: 100dvh;
display: flex;
flex-direction: column;
@@ -34,11 +46,21 @@
justify-content: center;
}
.icon svg { width: 40px; height: 40px; }
.icon svg {
width: 40px;
height: 40px;
}
h1 { font-size: 1.25rem; font-weight: 600; }
h1 {
font-size: 1.25rem;
font-weight: 600;
}
p { font-size: 0.9375rem; color: #6b7280; max-width: 28ch; }
p {
font-size: 0.9375rem;
color: #6b7280;
max-width: 28ch;
}
button {
margin-top: 0.5rem;
@@ -52,15 +74,17 @@
cursor: pointer;
}
button:active { opacity: 0.85; }
button:active {
opacity: 0.85;
}
</style>
</head>
<body>
<div class="icon">
<!-- House silhouette -->
<svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
<polygon points="20,5 34,17 31,17 31,35 9,35 9,17 6,17" fill="white"/>
<rect x="15" y="22" width="10" height="13" rx="1" fill="#4F46E5"/>
<polygon points="20,5 34,17 31,17 31,35 9,35 9,17 6,17" fill="white" />
<rect x="15" y="22" width="10" height="13" rx="1" fill="#4F46E5" />
</svg>
</div>
+2 -2
View File
@@ -1,6 +1,6 @@
// famapp service worker — vdev
// famapp service worker — v1778106925247
// Generated at build time. Do not edit directly.
const CACHE_VERSION = "dev";
const CACHE_VERSION = "1778106925247";
const SHELL = "famapp-shell-" + CACHE_VERSION;
const API = "famapp-api-" + CACHE_VERSION;
const OFFLINE = "/offline.html";
+2 -3
View File
@@ -32,8 +32,7 @@ for (let i = 0; i < 256; i++) {
function crc32(buf) {
let crc = 0xffffffff;
for (let i = 0; i < buf.length; i++)
crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
for (let i = 0; i < buf.length; i++) crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
return (crc ^ 0xffffffff) >>> 0;
}
@@ -61,7 +60,7 @@ function solidPNG(size, r, g, b) {
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.
+25
View File
@@ -0,0 +1,25 @@
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";
const url = process.env.DATABASE_URL;
if (!url) {
console.error("DATABASE_URL is required");
process.exit(1);
}
const migrationsFolder = process.env.MIGRATIONS_FOLDER ?? "./drizzle";
const sql = postgres(url, { max: 1 });
const db = drizzle(sql);
try {
await migrate(db, { migrationsFolder });
console.log(
JSON.stringify({ level: "info", msg: "migrations applied", folder: migrationsFolder }),
);
} catch (err) {
console.error(JSON.stringify({ level: "error", msg: "migrations failed", err: String(err) }));
process.exit(1);
} finally {
await sql.end({ timeout: 5 });
}
+12 -4
View File
@@ -10,10 +10,18 @@ import { EditDashboardButton } from "@/components/edit-dashboard-button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
const smColSpan: Record<number, string> = {
1: "sm:col-span-1", 2: "sm:col-span-2", 3: "sm:col-span-3",
4: "sm:col-span-4", 5: "sm:col-span-5", 6: "sm:col-span-6",
7: "sm:col-span-7", 8: "sm:col-span-8", 9: "sm:col-span-9",
10: "sm:col-span-10", 11: "sm:col-span-11", 12: "sm:col-span-12",
1: "sm:col-span-1",
2: "sm:col-span-2",
3: "sm:col-span-3",
4: "sm:col-span-4",
5: "sm:col-span-5",
6: "sm:col-span-6",
7: "sm:col-span-7",
8: "sm:col-span-8",
9: "sm:col-span-9",
10: "sm:col-span-10",
11: "sm:col-span-11",
12: "sm:col-span-12",
};
export default async function DashboardPage({
+19 -9
View File
@@ -21,7 +21,13 @@ export type DashboardMeta = {
export async function listDashboards(): Promise<DashboardMeta[]> {
const { user } = await getCurrentSession();
const rows = await db
.select({ id: dashboards.id, name: dashboards.name, slug: dashboards.slug, isDefault: dashboards.isDefault, position: dashboards.position })
.select({
id: dashboards.id,
name: dashboards.name,
slug: dashboards.slug,
isDefault: dashboards.isDefault,
position: dashboards.position,
})
.from(dashboards)
.where(eq(dashboards.userId, user.id))
.orderBy(asc(dashboards.position), asc(dashboards.createdAt));
@@ -60,11 +66,12 @@ export async function getDashboardBySlug(slug: string) {
}
function toSlug(name: string): string {
return name
return (
name
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "")
|| "dashboard";
.replace(/^-|-$/g, "") || "dashboard"
);
}
async function uniqueSlug(userId: string, base: string): Promise<string> {
@@ -93,7 +100,13 @@ export async function createDashboard(name: string): Promise<DashboardMeta> {
const row = rows[0];
if (!row) throw new Error("Insert failed");
revalidatePath("/");
return { id: row.id, name: row.name, slug: row.slug, isDefault: row.isDefault, position: row.position };
return {
id: row.id,
name: row.name,
slug: row.slug,
isDefault: row.isDefault,
position: row.position,
};
}
export async function renameDashboard(id: string, name: string): Promise<void> {
@@ -134,10 +147,7 @@ export async function deleteDashboard(id: string): Promise<void> {
export async function setDefaultDashboard(id: string): Promise<void> {
const { user } = await getCurrentSession();
await db
.update(dashboards)
.set({ isDefault: false })
.where(eq(dashboards.userId, user.id));
await db.update(dashboards).set({ isDefault: false }).where(eq(dashboards.userId, user.id));
await db
.update(dashboards)
.set({ isDefault: true })
+7 -7
View File
@@ -130,7 +130,7 @@
--secondary-foreground: oklch(0.25 0.04 45);
--muted: oklch(0.93 0.018 58);
--muted-foreground: oklch(0.52 0.04 50);
--accent: oklch(0.90 0.03 55);
--accent: oklch(0.9 0.03 55);
--accent-foreground: oklch(0.22 0.04 45);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.88 0.025 60);
@@ -139,14 +139,14 @@
--chart-1: oklch(0.72 0.16 40);
--chart-2: oklch(0.62 0.14 55);
--chart-3: oklch(0.52 0.12 45);
--chart-4: oklch(0.45 0.10 40);
--chart-4: oklch(0.45 0.1 40);
--chart-5: oklch(0.35 0.08 35);
--radius: 0.625rem;
--sidebar: oklch(0.94 0.018 58);
--sidebar-foreground: oklch(0.18 0.03 50);
--sidebar-primary: oklch(0.52 0.18 40);
--sidebar-primary-foreground: oklch(0.98 0.01 60);
--sidebar-accent: oklch(0.90 0.03 55);
--sidebar-accent: oklch(0.9 0.03 55);
--sidebar-accent-foreground: oklch(0.22 0.04 45);
--sidebar-border: oklch(0.88 0.025 60);
--sidebar-ring: oklch(0.65 0.12 45);
@@ -166,7 +166,7 @@
--secondary-foreground: oklch(0.95 0.015 60);
--muted: oklch(0.28 0.035 48);
--muted-foreground: oklch(0.68 0.04 55);
--accent: oklch(0.30 0.045 50);
--accent: oklch(0.3 0.045 50);
--accent-foreground: oklch(0.95 0.015 60);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
@@ -174,14 +174,14 @@
--ring: oklch(0.55 0.08 50);
--chart-1: oklch(0.78 0.14 50);
--chart-2: oklch(0.65 0.12 55);
--chart-3: oklch(0.52 0.10 48);
--chart-3: oklch(0.52 0.1 48);
--chart-4: oklch(0.42 0.08 42);
--chart-5: oklch(0.32 0.06 38);
--sidebar: oklch(0.20 0.03 47);
--sidebar: oklch(0.2 0.03 47);
--sidebar-foreground: oklch(0.95 0.015 60);
--sidebar-primary: oklch(0.78 0.14 50);
--sidebar-primary-foreground: oklch(0.16 0.025 45);
--sidebar-accent: oklch(0.30 0.045 50);
--sidebar-accent: oklch(0.3 0.045 50);
--sidebar-accent-foreground: oklch(0.95 0.015 60);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.55 0.08 50);
+8 -6
View File
@@ -49,11 +49,7 @@ const prePaintScript = `(function(){
} catch(e) {}
})();`;
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
export default async function RootLayout({ children }: { children: React.ReactNode }) {
let theme = "default";
let themeMode = "system";
let userDashboards: DashboardMeta[] = [];
@@ -70,7 +66,13 @@ export default async function RootLayout({
themeMode = row.themeMode;
}
userDashboards = await db
.select({ id: dashboards.id, name: dashboards.name, slug: dashboards.slug, isDefault: dashboards.isDefault, position: dashboards.position })
.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));
+1 -5
View File
@@ -11,11 +11,7 @@ export const metadata: Metadata = {
// 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 }>;
}) {
export default async function SharePage({ params }: { params: Promise<{ token: string }> }) {
const { token } = await params;
const headersList = await headers();
const ip =
+3 -15
View File
@@ -9,21 +9,12 @@ import type { ThemeId, ThemeMode } 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;
}) {
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");
const { user } = await getCurrentSession();
await db
.update(users)
.set({ theme, themeMode: mode })
.where(eq(users.id, user.id));
await db.update(users).set({ theme, themeMode: mode }).where(eq(users.id, user.id));
}
export async function setCompletionVisibilityHours(hours: number): Promise<void> {
@@ -31,10 +22,7 @@ export async function setCompletionVisibilityHours(hours: number): Promise<void>
if (!Number.isInteger(parsed) || parsed < 0 || parsed > 8760)
throw new Error("Invalid hours value");
const { user } = await getCurrentSession();
await db
.update(users)
.set({ completionVisibilityHours: parsed })
.where(eq(users.id, user.id));
await db.update(users).set({ completionVisibilityHours: parsed }).where(eq(users.id, user.id));
revalidatePath("/settings");
}
+1 -4
View File
@@ -13,10 +13,7 @@ export async function renameHousehold(formData: FormData) {
const name = formData.get("name");
if (typeof name !== "string" || !name.trim()) throw new Error("Invalid name");
await db
.update(households)
.set({ name: name.trim() })
.where(eq(households.id, household.id));
await db.update(households).set({ name: name.trim() }).where(eq(households.id, household.id));
revalidatePath("/settings/household");
}
+2 -9
View File
@@ -4,12 +4,7 @@ import { getCurrentSession } from "@/lib/session";
import { householdMembers, users } from "@/modules/_core/schema";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { renameHousehold } from "./actions";
export default async function HouseholdSettingsPage() {
@@ -34,9 +29,7 @@ export default async function HouseholdSettingsPage() {
{members.map(({ user, role: memberRole }) => (
<li key={user.id} className="flex items-center justify-between">
<span>{user.name ?? user.email}</span>
<span className="text-sm text-muted-foreground capitalize">
{memberRole}
</span>
<span className="text-sm text-muted-foreground capitalize">{memberRole}</span>
</li>
))}
</ul>
+2 -7
View File
@@ -11,10 +11,7 @@ type PushSubscriptionJSON = {
keys: { p256dh: string; auth: string };
};
export async function subscribeToPush(
sub: PushSubscriptionJSON,
userAgent: string,
): Promise<void> {
export async function subscribeToPush(sub: PushSubscriptionJSON, userAgent: string): Promise<void> {
const { user } = await getCurrentSession();
await db
.insert(pushSubscriptions)
@@ -35,9 +32,7 @@ export async function unsubscribeFromPush(endpoint: string): Promise<void> {
const { user } = await getCurrentSession();
await db
.delete(pushSubscriptions)
.where(
and(eq(pushSubscriptions.userId, user.id), eq(pushSubscriptions.endpoint, endpoint)),
);
.where(and(eq(pushSubscriptions.userId, user.id), eq(pushSubscriptions.endpoint, endpoint)));
}
export async function sendTestNotification(): Promise<void> {
+10 -10
View File
@@ -27,11 +27,7 @@ export function CommandPalette() {
return (
<>
{/* Backdrop */}
<div
className="fixed inset-0 z-50 bg-black/50"
onClick={closePalette}
aria-hidden="true"
/>
<div className="fixed inset-0 z-50 bg-black/50" onClick={closePalette} aria-hidden="true" />
{/* Palette modal */}
<div
@@ -90,12 +86,16 @@ export function CommandPalette() {
);
}
type GroupEntry = [string, { name: string; items: import("@/modules/_core").SerializedQuickAddItem[] }];
type GroupEntry = [
string,
{ name: string; items: import("@/modules/_core").SerializedQuickAddItem[] },
];
function groupByModule(
actions: import("@/modules/_core").SerializedQuickAddItem[],
): GroupEntry[] {
const map = new Map<string, { name: string; items: import("@/modules/_core").SerializedQuickAddItem[] }>();
function groupByModule(actions: import("@/modules/_core").SerializedQuickAddItem[]): GroupEntry[] {
const map = new Map<
string,
{ name: string; items: import("@/modules/_core").SerializedQuickAddItem[] }
>();
for (const action of actions) {
if (!map.has(action.moduleId)) {
map.set(action.moduleId, { name: action.moduleName, items: [] });
+17 -6
View File
@@ -102,16 +102,17 @@ export function DashboardEditor({
}
function updateConfig(index: number, config: unknown) {
setPlacements((current) =>
current.map((p, i) => (i === index ? { ...p, config } : p)),
);
setPlacements((current) => current.map((p, i) => (i === index ? { ...p, config } : p)));
setIsDirty(true);
setConfiguringIndex(null);
}
const gridItems: Layout = placements.map((p, i) => ({
i: placementKey(p, i),
x: p.x, y: p.y, w: p.w, h: p.h,
x: p.x,
y: p.y,
w: p.w,
h: p.h,
minW: widgetMetas.find((m) => m.id === p.widgetId)?.minSize?.w ?? 2,
minH: widgetMetas.find((m) => m.id === p.widgetId)?.minSize?.h ?? 1,
maxW: widgetMetas.find((m) => m.id === p.widgetId)?.maxSize?.w ?? 12,
@@ -126,7 +127,12 @@ export function DashboardEditor({
<RotateCcw className="size-4 mr-1" />
Reset
</Button>
<Button variant="outline" size="sm" onClick={() => setPickerOpen(true)} disabled={isPending}>
<Button
variant="outline"
size="sm"
onClick={() => setPickerOpen(true)}
disabled={isPending}
>
<Plus className="size-4 mr-1" />
Add widget
</Button>
@@ -147,7 +153,12 @@ export function DashboardEditor({
<GridLayout
layout={gridItems}
width={containerWidth}
gridConfig={{ cols: 12, rowHeight: 60, margin: [16, 16] as [number, number], containerPadding: [0, 0] as [number, number] }}
gridConfig={{
cols: 12,
rowHeight: 60,
margin: [16, 16] as [number, number],
containerPadding: [0, 0] as [number, number],
}}
dragConfig={{ handle: ".drag-handle" }}
onLayoutChange={handleLayoutChange}
>
+6 -11
View File
@@ -73,7 +73,10 @@ export function DashboardSwitcher({ dashboards }: { dashboards: DashboardMeta[]
className="h-7 rounded border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
onKeyDown={(e) => e.key === "Escape" && setCreatingNew(false)}
/>
<button type="submit" className="text-xs text-muted-foreground hover:text-foreground px-1">
<button
type="submit"
className="text-xs text-muted-foreground hover:text-foreground px-1"
>
Add
</button>
<button
@@ -98,13 +101,7 @@ export function DashboardSwitcher({ dashboards }: { dashboards: DashboardMeta[]
{dashboards.map((d) => {
const isActive = activeSlug() === d.slug;
if (!isActive) return null;
return (
<DashboardKebab
key={d.id}
dashboard={d}
canDelete={dashboards.length > 1}
/>
);
return <DashboardKebab key={d.id} dashboard={d} canDelete={dashboards.length > 1} />;
})}
</div>
);
@@ -177,9 +174,7 @@ function DashboardKebab({
</DropdownMenuItem>
{!dashboard.isDefault && (
<DropdownMenuItem
onSelect={() =>
startTransition(() => setDefaultDashboard(dashboard.id))
}
onSelect={() => startTransition(() => setDefaultDashboard(dashboard.id))}
>
<Star className="size-4 mr-2" />
Set as default
+1 -6
View File
@@ -97,12 +97,7 @@ export function InstallPrompt() {
{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{" "}
Tap <Share className="inline-block h-4 w-4 align-text-bottom" aria-label="Share" /> then{" "}
<strong className="font-medium">
<Plus className="inline-block h-3.5 w-3.5 align-text-bottom" />
&nbsp;Add to Home Screen
+19 -7
View File
@@ -2,7 +2,11 @@
import { useState, useTransition } from "react";
import { Button } from "@/components/ui/button";
import { subscribeToPush, unsubscribeFromPush, sendTestNotification } from "@/app/settings/push-actions";
import {
subscribeToPush,
unsubscribeFromPush,
sendTestNotification,
} from "@/app/settings/push-actions";
const VAPID_KEY = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY ?? "";
@@ -16,16 +20,18 @@ function urlBase64ToUint8Array(base64String: string): Uint8Array<ArrayBuffer> {
}
export function PushOptIn() {
const [status, setStatus] = useState<"idle" | "subscribed" | "denied" | "unsupported">(
"idle",
);
const [status, setStatus] = useState<"idle" | "subscribed" | "denied" | "unsupported">("idle");
const [endpoint, setEndpoint] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const [testSent, setTestSent] = useState(false);
if (!VAPID_KEY) return null;
if (!("serviceWorker" in navigator) || !("PushManager" in window)) {
return <p className="text-sm text-muted-foreground">Push notifications not supported in this browser.</p>;
return (
<p className="text-sm text-muted-foreground">
Push notifications not supported in this browser.
</p>
);
}
async function subscribe() {
@@ -67,13 +73,19 @@ export function PushOptIn() {
}
if (status === "denied") {
return <p className="text-sm text-destructive">Notification permission denied. Enable it in browser settings.</p>;
return (
<p className="text-sm text-destructive">
Notification permission denied. Enable it in browser settings.
</p>
);
}
if (status === "subscribed") {
return (
<div className="flex items-center gap-3">
<span className="text-sm text-green-600 dark:text-green-400">Push notifications enabled</span>
<span className="text-sm text-green-600 dark:text-green-400">
Push notifications enabled
</span>
<Button size="sm" variant="outline" onClick={sendTest} disabled={isPending}>
{testSent ? "Sent!" : "Send test"}
</Button>
+4 -15
View File
@@ -16,7 +16,6 @@ export function PwaRegister() {
// fired between page load and this effect running (e.g. DevTools toggle).
const syncId = setTimeout(() => setIsOffline(!navigator.onLine), 0);
if (!("serviceWorker" in navigator)) {
return () => {
window.removeEventListener("offline", handleOffline);
@@ -35,10 +34,7 @@ export function PwaRegister() {
const handleControllerChange = () => {
if (hadController) setShowUpdate(true);
};
navigator.serviceWorker.addEventListener(
"controllerchange",
handleControllerChange
);
navigator.serviceWorker.addEventListener("controllerchange", handleControllerChange);
const handleMessage = (e: MessageEvent) => {
if (e.data?.type === "OFFLINE_MUTATION") {
@@ -52,10 +48,7 @@ export function PwaRegister() {
clearTimeout(syncId);
window.removeEventListener("offline", handleOffline);
window.removeEventListener("online", handleOnline);
navigator.serviceWorker.removeEventListener(
"controllerchange",
handleControllerChange
);
navigator.serviceWorker.removeEventListener("controllerchange", handleControllerChange);
navigator.serviceWorker.removeEventListener("message", handleMessage);
};
}, []);
@@ -67,9 +60,7 @@ export function PwaRegister() {
role="status"
className="fixed top-4 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 rounded-lg bg-amber-50 px-4 py-3 text-amber-900 shadow-lg ring-1 ring-amber-200 dark:bg-amber-950 dark:text-amber-100 dark:ring-amber-800"
>
<span className="text-sm font-medium">
You&rsquo;re offline showing cached content
</span>
<span className="text-sm font-medium">You&rsquo;re offline showing cached content</span>
<button
onClick={() => setIsOffline(false)}
aria-label="Dismiss"
@@ -85,9 +76,7 @@ export function PwaRegister() {
role="alert"
className="fixed top-4 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 rounded-lg bg-destructive px-4 py-3 text-destructive-foreground shadow-lg"
>
<span className="text-sm font-medium">
Changes can&rsquo;t be saved while offline
</span>
<span className="text-sm font-medium">Changes can&rsquo;t be saved while offline</span>
</div>
)}
+3 -1
View File
@@ -5,7 +5,9 @@ import { useRouter } from "next/navigation";
import { useQuickAdd } from "./quick-add-provider";
import type { SerializedQuickAddItem } from "@/modules/_core";
function groupByModule(actions: SerializedQuickAddItem[]): Map<string, { name: string; items: SerializedQuickAddItem[] }> {
function groupByModule(
actions: SerializedQuickAddItem[],
): Map<string, { name: string; items: SerializedQuickAddItem[] }> {
const map = new Map<string, { name: string; items: SerializedQuickAddItem[] }>();
for (const action of actions) {
if (!map.has(action.moduleId)) {
+1 -6
View File
@@ -3,12 +3,7 @@
import { useState, useTransition } from "react";
import { Link, Check, Copy } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { createShareLink } from "@/modules/_core/share";
+1 -5
View File
@@ -25,11 +25,7 @@ export function ThemePicker({
initialMode = "system",
signedIn = false,
}: Props) {
const { theme, mode, setTheme, setMode } = useTheme(
initialTheme,
initialMode,
signedIn,
);
const { theme, mode, setTheme, setMode } = useTheme(initialTheme, initialMode, signedIn);
return (
<div className="space-y-4">
+7 -7
View File
@@ -1,7 +1,7 @@
import { Button as ButtonPrimitive } from "@base-ui/react/button"
import { cva, type VariantProps } from "class-variance-authority"
import { Button as ButtonPrimitive } from "@base-ui/react/button";
import { cva, type VariantProps } from "class-variance-authority";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
@@ -37,8 +37,8 @@ const buttonVariants = cva(
variant: "default",
size: "default",
},
}
)
},
);
function Button({
className,
@@ -52,7 +52,7 @@ function Button({
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
);
}
export { Button, buttonVariants }
export { Button, buttonVariants };
+15 -26
View File
@@ -1,6 +1,6 @@
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Card({
className,
@@ -13,11 +13,11 @@ function Card({
data-size={size}
className={cn(
"group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
className
className,
)}
{...props}
/>
)
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
@@ -26,11 +26,11 @@ function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card-header"
className={cn(
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",
className
className,
)}
{...props}
/>
)
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
@@ -39,11 +39,11 @@ function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card-title"
className={cn(
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
className
className,
)}
{...props}
/>
)
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
@@ -53,20 +53,17 @@ function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
className={cn("col-start-2 row-span-2 row-start-1 self-start justify-self-end", className)}
{...props}
/>
)
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
@@ -76,7 +73,7 @@ function CardContent({ className, ...props }: React.ComponentProps<"div">) {
className={cn("px-4 group-data-[size=sm]/card:px-3", className)}
{...props}
/>
)
);
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
@@ -85,19 +82,11 @@ function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
data-slot="card-footer"
className={cn(
"flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",
className
className,
)}
{...props}
/>
)
);
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
+30 -52
View File
@@ -1,42 +1,39 @@
"use client"
"use client";
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import * as React from "react";
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { XIcon } from "lucide-react";
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
className,
...props
}: DialogPrimitive.Backdrop.Props) {
function DialogOverlay({ className, ...props }: DialogPrimitive.Backdrop.Props) {
return (
<DialogPrimitive.Backdrop
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
className,
)}
{...props}
/>
)
);
}
function DialogContent({
@@ -45,7 +42,7 @@ function DialogContent({
showCloseButton = true,
...props
}: DialogPrimitive.Popup.Props & {
showCloseButton?: boolean
showCloseButton?: boolean;
}) {
return (
<DialogPortal>
@@ -54,7 +51,7 @@ function DialogContent({
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
className,
)}
{...props}
>
@@ -62,32 +59,21 @@ function DialogContent({
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
render={
<Button
variant="ghost"
className="absolute top-2 right-2"
size="icon-sm"
/>
}
render={<Button variant="ghost" className="absolute top-2 right-2" size="icon-sm" />}
>
<XIcon
/>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Popup>
</DialogPortal>
)
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
<div data-slot="dialog-header" className={cn("flex flex-col gap-2", className)} {...props} />
);
}
function DialogFooter({
@@ -96,54 +82,46 @@ function DialogFooter({
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
showCloseButton?: boolean;
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close render={<Button variant="outline" />}>
Close
</DialogPrimitive.Close>
<DialogPrimitive.Close render={<Button variant="outline" />}>Close</DialogPrimitive.Close>
)}
</div>
)
);
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn(
"font-heading text-base leading-none font-medium",
className
)}
className={cn("font-heading text-base leading-none font-medium", className)}
{...props}
/>
)
);
}
function DialogDescription({
className,
...props
}: DialogPrimitive.Description.Props) {
function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
className,
)}
{...props}
/>
)
);
}
export {
@@ -157,4 +135,4 @@ export {
DialogPortal,
DialogTitle,
DialogTrigger,
}
};
+46 -56
View File
@@ -1,21 +1,21 @@
"use client"
"use client";
import * as React from "react"
import { Menu as MenuPrimitive } from "@base-ui/react/menu"
import * as React from "react";
import { Menu as MenuPrimitive } from "@base-ui/react/menu";
import { cn } from "@/lib/utils"
import { ChevronRightIcon, CheckIcon } from "lucide-react"
import { cn } from "@/lib/utils";
import { ChevronRightIcon, CheckIcon } from "lucide-react";
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
}
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
}
function DropdownMenuContent({
@@ -26,10 +26,7 @@ function DropdownMenuContent({
className,
...props
}: MenuPrimitive.Popup.Props &
Pick<
MenuPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset"
>) {
Pick<MenuPrimitive.Positioner.Props, "align" | "alignOffset" | "side" | "sideOffset">) {
return (
<MenuPrimitive.Portal>
<MenuPrimitive.Positioner
@@ -41,16 +38,19 @@ function DropdownMenuContent({
>
<MenuPrimitive.Popup
data-slot="dropdown-menu-content"
className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
className={cn(
"z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
{...props}
/>
</MenuPrimitive.Positioner>
</MenuPrimitive.Portal>
)
);
}
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
}
function DropdownMenuLabel({
@@ -58,7 +58,7 @@ function DropdownMenuLabel({
inset,
...props
}: MenuPrimitive.GroupLabel.Props & {
inset?: boolean
inset?: boolean;
}) {
return (
<MenuPrimitive.GroupLabel
@@ -66,11 +66,11 @@ function DropdownMenuLabel({
data-inset={inset}
className={cn(
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
className
className,
)}
{...props}
/>
)
);
}
function DropdownMenuItem({
@@ -79,8 +79,8 @@ function DropdownMenuItem({
variant = "default",
...props
}: MenuPrimitive.Item.Props & {
inset?: boolean
variant?: "default" | "destructive"
inset?: boolean;
variant?: "default" | "destructive";
}) {
return (
<MenuPrimitive.Item
@@ -89,15 +89,15 @@ function DropdownMenuItem({
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
className,
)}
{...props}
/>
)
);
}
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />;
}
function DropdownMenuSubTrigger({
@@ -106,7 +106,7 @@ function DropdownMenuSubTrigger({
children,
...props
}: MenuPrimitive.SubmenuTrigger.Props & {
inset?: boolean
inset?: boolean;
}) {
return (
<MenuPrimitive.SubmenuTrigger
@@ -114,14 +114,14 @@ function DropdownMenuSubTrigger({
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</MenuPrimitive.SubmenuTrigger>
)
);
}
function DropdownMenuSubContent({
@@ -135,14 +135,17 @@ function DropdownMenuSubContent({
return (
<DropdownMenuContent
data-slot="dropdown-menu-sub-content"
className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
className={cn(
"w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
{...props}
/>
)
);
}
function DropdownMenuCheckboxItem({
@@ -152,7 +155,7 @@ function DropdownMenuCheckboxItem({
inset,
...props
}: MenuPrimitive.CheckboxItem.Props & {
inset?: boolean
inset?: boolean;
}) {
return (
<MenuPrimitive.CheckboxItem
@@ -160,7 +163,7 @@ function DropdownMenuCheckboxItem({
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
checked={checked}
{...props}
@@ -170,22 +173,16 @@ function DropdownMenuCheckboxItem({
data-slot="dropdown-menu-checkbox-item-indicator"
>
<MenuPrimitive.CheckboxItemIndicator>
<CheckIcon
/>
<CheckIcon />
</MenuPrimitive.CheckboxItemIndicator>
</span>
{children}
</MenuPrimitive.CheckboxItem>
)
);
}
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
return (
<MenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
return <MenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
}
function DropdownMenuRadioItem({
@@ -194,7 +191,7 @@ function DropdownMenuRadioItem({
inset,
...props
}: MenuPrimitive.RadioItem.Props & {
inset?: boolean
inset?: boolean;
}) {
return (
<MenuPrimitive.RadioItem
@@ -202,7 +199,7 @@ function DropdownMenuRadioItem({
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
@@ -211,42 +208,35 @@ function DropdownMenuRadioItem({
data-slot="dropdown-menu-radio-item-indicator"
>
<MenuPrimitive.RadioItemIndicator>
<CheckIcon
/>
<CheckIcon />
</MenuPrimitive.RadioItemIndicator>
</span>
{children}
</MenuPrimitive.RadioItem>
)
);
}
function DropdownMenuSeparator({
className,
...props
}: MenuPrimitive.Separator.Props) {
function DropdownMenuSeparator({ className, ...props }: MenuPrimitive.Separator.Props) {
return (
<MenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
);
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
className
className,
)}
{...props}
/>
)
);
}
export {
@@ -265,4 +255,4 @@ export {
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
};
+6 -6
View File
@@ -1,7 +1,7 @@
import * as React from "react"
import { Input as InputPrimitive } from "@base-ui/react/input"
import * as React from "react";
import { Input as InputPrimitive } from "@base-ui/react/input";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
@@ -10,11 +10,11 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
className,
)}
{...props}
/>
)
);
}
export { Input }
export { Input };
+6 -6
View File
@@ -1,8 +1,8 @@
"use client"
"use client";
import * as React from "react"
import * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
function Label({ className, ...props }: React.ComponentProps<"label">) {
return (
@@ -10,11 +10,11 @@ function Label({ className, ...props }: React.ComponentProps<"label">) {
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
className,
)}
{...props}
/>
)
);
}
export { Label }
export { Label };
+31 -42
View File
@@ -1,12 +1,12 @@
"use client"
"use client";
import * as React from "react"
import { Select as SelectPrimitive } from "@base-ui/react/select"
import * as React from "react";
import { Select as SelectPrimitive } from "@base-ui/react/select";
import { cn } from "@/lib/utils"
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react"
import { cn } from "@/lib/utils";
import { ChevronDownIcon, CheckIcon, ChevronUpIcon } from "lucide-react";
const Select = SelectPrimitive.Root
const Select = SelectPrimitive.Root;
function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
return (
@@ -15,7 +15,7 @@ function SelectGroup({ className, ...props }: SelectPrimitive.Group.Props) {
className={cn("scroll-my-1 p-1", className)}
{...props}
/>
)
);
}
function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
@@ -25,7 +25,7 @@ function SelectValue({ className, ...props }: SelectPrimitive.Value.Props) {
className={cn("flex flex-1 text-left", className)}
{...props}
/>
)
);
}
function SelectTrigger({
@@ -34,7 +34,7 @@ function SelectTrigger({
children,
...props
}: SelectPrimitive.Trigger.Props & {
size?: "sm" | "default"
size?: "sm" | "default";
}) {
return (
<SelectPrimitive.Trigger
@@ -42,18 +42,16 @@ function SelectTrigger({
data-size={size}
className={cn(
"flex w-fit items-center justify-between gap-1.5 rounded-lg border border-input bg-transparent py-2 pr-2 pl-2.5 text-sm whitespace-nowrap transition-colors outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-8 data-[size=sm]:h-7 data-[size=sm]:rounded-[min(var(--radius-md),10px)] *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-1.5 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
{children}
<SelectPrimitive.Icon
render={
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
}
render={<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />}
/>
</SelectPrimitive.Trigger>
)
);
}
function SelectContent({
@@ -83,7 +81,10 @@ function SelectContent({
<SelectPrimitive.Popup
data-slot="select-content"
data-align-trigger={alignItemWithTrigger}
className={cn("relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
className={cn(
"relative isolate z-50 max-h-(--available-height) w-(--anchor-width) min-w-36 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[align-trigger=true]:animate-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className,
)}
{...props}
>
<SelectScrollUpButton />
@@ -92,33 +93,26 @@ function SelectContent({
</SelectPrimitive.Popup>
</SelectPrimitive.Positioner>
</SelectPrimitive.Portal>
)
);
}
function SelectLabel({
className,
...props
}: SelectPrimitive.GroupLabel.Props) {
function SelectLabel({ className, ...props }: SelectPrimitive.GroupLabel.Props) {
return (
<SelectPrimitive.GroupLabel
data-slot="select-label"
className={cn("px-1.5 py-1 text-xs text-muted-foreground", className)}
{...props}
/>
)
);
}
function SelectItem({
className,
children,
...props
}: SelectPrimitive.Item.Props) {
function SelectItem({ className, children, ...props }: SelectPrimitive.Item.Props) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
className,
)}
{...props}
>
@@ -133,20 +127,17 @@ function SelectItem({
<CheckIcon className="pointer-events-none" />
</SelectPrimitive.ItemIndicator>
</SelectPrimitive.Item>
)
);
}
function SelectSeparator({
className,
...props
}: SelectPrimitive.Separator.Props) {
function SelectSeparator({ className, ...props }: SelectPrimitive.Separator.Props) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
);
}
function SelectScrollUpButton({
@@ -158,14 +149,13 @@ function SelectScrollUpButton({
data-slot="select-scroll-up-button"
className={cn(
"top-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
<ChevronUpIcon
/>
<ChevronUpIcon />
</SelectPrimitive.ScrollUpArrow>
)
);
}
function SelectScrollDownButton({
@@ -177,14 +167,13 @@ function SelectScrollDownButton({
data-slot="select-scroll-down-button"
className={cn(
"bottom-0 z-10 flex w-full cursor-default items-center justify-center bg-popover py-1 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
<ChevronDownIcon
/>
<ChevronDownIcon />
</SelectPrimitive.ScrollDownArrow>
)
);
}
export {
@@ -198,4 +187,4 @@ export {
SelectSeparator,
SelectTrigger,
SelectValue,
}
};
+29 -8
View File
@@ -71,9 +71,17 @@ export function WidgetPicker({
</button>
)}
<h2 className="font-semibold flex-1 text-sm">
{step === "pick" ? "Add widget" : selected ? `Configure: ${selected.title}` : "Configure"}
{step === "pick"
? "Add widget"
: selected
? `Configure: ${selected.title}`
: "Configure"}
</h2>
<button type="button" onClick={onClose} className="text-muted-foreground hover:text-foreground">
<button
type="button"
onClick={onClose}
className="text-muted-foreground hover:text-foreground"
>
<X className="size-5" />
</button>
</div>
@@ -82,9 +90,13 @@ export function WidgetPicker({
<div className="flex-1 overflow-y-auto p-4">
{step === "pick" && (
<div className="space-y-4">
{Object.entries(grouped).sort(([a], [b]) => a.localeCompare(b)).map(([cat, items]) => (
{Object.entries(grouped)
.sort(([a], [b]) => a.localeCompare(b))
.map(([cat, items]) => (
<div key={cat}>
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground mb-2">{cat}</p>
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground mb-2">
{cat}
</p>
<div className="space-y-1">
{items.map((meta) => (
<button
@@ -116,7 +128,9 @@ export function WidgetPicker({
{/* Footer */}
{step === "configure" && (
<div className="flex justify-end gap-2 px-4 py-3 border-t">
<Button variant="outline" size="sm" onClick={onClose}>Cancel</Button>
<Button variant="outline" size="sm" onClick={onClose}>
Cancel
</Button>
<Button size="sm" onClick={handleAdd}>
{initialWidgetId ? "Apply" : "Add widget"}
</Button>
@@ -158,7 +172,10 @@ function WidgetConfigurator({
<div className="space-y-4">
{entries.map(([key, value]) => {
// "all" | string[] — multi-select with All toggle
if (value === "all" || (Array.isArray(value) && (key.endsWith("Ids") || key.endsWith("ids")))) {
if (
value === "all" ||
(Array.isArray(value) && (key.endsWith("Ids") || key.endsWith("ids")))
) {
const optKey = key.replace(/Ids?$/i, "s");
const items: FieldOption[] = (opts?.[optKey] as FieldOption[] | undefined) ?? [];
const isAll = value === "all";
@@ -253,7 +270,9 @@ function WidgetConfigurator({
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
{enumOpts.map((opt) => (
<option key={opt} value={opt}>{opt}</option>
<option key={opt} value={opt}>
{opt}
</option>
))}
</select>
</div>
@@ -277,7 +296,9 @@ function WidgetConfigurator({
className="rounded-md border border-input bg-background px-3 py-1.5 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
{known.map((opt) => (
<option key={opt} value={opt}>{opt}</option>
<option key={opt} value={opt}>
{opt}
</option>
))}
</select>
</div>
+1 -2
View File
@@ -9,8 +9,7 @@ function applyTheme(theme: ThemeId, mode: ThemeMode) {
html.setAttribute("data-theme", theme);
const dark =
mode === "dark" ||
(mode === "system" &&
window.matchMedia("(prefers-color-scheme: dark)").matches);
(mode === "system" && window.matchMedia("(prefers-color-scheme: dark)").matches);
html.classList.toggle("dark", dark);
try {
localStorage.setItem("theme", theme);
+11
View File
@@ -1,5 +1,16 @@
export const DEV_LOGIN_COOKIE = "authjs.session-token";
if (
process.env.NODE_ENV === "production" &&
process.env.ENABLE_DEV_LOGIN === "true" &&
process.env.NEXT_PHASE !== "phase-production-build"
) {
throw new Error(
"Refusing to start: ENABLE_DEV_LOGIN=true with NODE_ENV=production. " +
"Unset ENABLE_DEV_LOGIN in production env.",
);
}
export function isDevLoginEnabled() {
return process.env.NODE_ENV !== "production" && process.env.ENABLE_DEV_LOGIN === "true";
}
+3 -3
View File
@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
return twMerge(clsx(inputs));
}
+8 -1
View File
@@ -10,7 +10,14 @@ export type {
SearchResult,
ActivityLogEntry,
} from "./module";
export { registerModule, getRegistry, getEntityType, getWidget, getQuickAdds, getWidgetMetas } from "./registry";
export {
registerModule,
getRegistry,
getEntityType,
getWidget,
getQuickAdds,
getWidgetMetas,
} from "./registry";
export type { QuickAddItem, SerializedQuickAddItem, SerializedWidgetMeta } from "./registry";
export { logActivity, logShareActivity } from "./activity";
export { createShareLink, resolveShareToken, revokeShareLink } from "./share";
+1 -2
View File
@@ -30,8 +30,7 @@ async function ActivityWidget({ config }: { config: unknown }) {
{entries.map((entry) => {
const reg = getEntityType(entry.entityType);
const description =
reg?.renderActivity?.(entry as ActivityLogEntry) ??
`${entry.action} ${entry.entityType}`;
reg?.renderActivity?.(entry as ActivityLogEntry) ?? `${entry.action} ${entry.entityType}`;
return (
<li key={entry.id} className="flex items-start gap-2 text-sm">
<span className="mt-0.5 shrink-0 text-xs text-muted-foreground">
+6 -4
View File
@@ -15,7 +15,11 @@ export async function notify(userId: string, payload: NotifyPayload) {
const channels = payload.channels ?? ["push", "inapp"];
const [user] = await db
.select({ notifPush: users.notifPush, notifInApp: users.notifInApp, notifNtfy: users.notifNtfy })
.select({
notifPush: users.notifPush,
notifInApp: users.notifInApp,
notifNtfy: users.notifNtfy,
})
.from(users)
.where(eq(users.id, userId))
.limit(1);
@@ -25,9 +29,7 @@ export async function notify(userId: string, payload: NotifyPayload) {
const pushEnabled = process.env["VAPID_PUBLIC_KEY"] && process.env["VAPID_PRIVATE_KEY"];
if (channels.includes("push") && user.notifPush && pushEnabled) {
await sendPush(userId, payload).catch((err) =>
logger.error({ err }, "push channel failed"),
);
await sendPush(userId, payload).catch((err) => logger.error({ err }, "push channel failed"));
}
if (channels.includes("inapp") && user.notifInApp) {
+18 -4
View File
@@ -1,4 +1,9 @@
import type { ModuleManifest, EntityTypeRegistration, DashboardWidget, QuickAddAction } from "./module";
import type {
ModuleManifest,
EntityTypeRegistration,
DashboardWidget,
QuickAddAction,
} from "./module";
const modules = new Map<string, ModuleManifest>();
const entityTypes = new Map<string, EntityTypeRegistration>();
@@ -54,9 +59,18 @@ export type SerializedWidgetMeta = {
};
export function getWidgetMetas(): SerializedWidgetMeta[] {
return [...widgets.values()].map(({ id, title, description, category, defaultSize, minSize, maxSize, defaultConfig }) => ({
id, title, description, category, defaultSize, minSize, maxSize, defaultConfig,
}));
return [...widgets.values()].map(
({ id, title, description, category, defaultSize, minSize, maxSize, defaultConfig }) => ({
id,
title,
description,
category,
defaultSize,
minSize,
maxSize,
defaultConfig,
}),
);
}
export function getQuickAdds(): SerializedQuickAddItem[] {
+6 -1
View File
@@ -64,7 +64,12 @@ export async function tickReminders() {
await tx
.update(reminders)
.set({ firedAt: now })
.where(inArray(reminders.id, dueReminders.map((r) => r.id)));
.where(
inArray(
reminders.id,
dueReminders.map((r) => r.id),
),
);
}
});
} catch (err) {
+1 -2
View File
@@ -100,8 +100,7 @@ export const activityLog = pgTable(
.references(() => households.id, { onDelete: "cascade" }),
entityType: text("entity_type").notNull(),
entityId: uuid("entity_id").notNull(),
actorId: uuid("actor_id")
.references(() => users.id, { onDelete: "set null" }),
actorId: uuid("actor_id").references(() => users.id, { onDelete: "set null" }),
action: text("action").notNull(),
payload: jsonb("payload").$type<Record<string, unknown> | null>(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
+1 -3
View File
@@ -59,9 +59,7 @@ export async function createShareLink(
return { url: buildUrl(rawToken), token: rawToken, expiresAt };
}
export async function resolveShareToken(
rawToken: string,
): Promise<{
export async function resolveShareToken(rawToken: string): Promise<{
entityType: string;
entityId: string;
capabilities: ShareLinkCapabilities;
@@ -443,7 +443,8 @@ export function CalendarShell({
>
<SelectTrigger id="event-calendar">
<SelectValue>
{calendarRows.find((c) => c.id === selectedEvent.calendarId)?.name ?? "Select a calendar"}
{calendarRows.find((c) => c.id === selectedEvent.calendarId)?.name ??
"Select a calendar"}
</SelectValue>
</SelectTrigger>
<SelectContent>
@@ -50,9 +50,7 @@ export function CalendarSharedView({ data }: { data: CalendarShareData }) {
<div className="mx-auto max-w-xl space-y-4 p-4">
<header>
<h1 className="text-2xl font-semibold">{data.name}</h1>
<p className="text-sm text-muted-foreground">
Upcoming events next 90 days
</p>
<p className="text-sm text-muted-foreground">Upcoming events next 90 days</p>
</header>
{data.events.length === 0 ? (
<p className="text-sm text-muted-foreground">No upcoming events.</p>
+6 -7
View File
@@ -18,12 +18,7 @@ const upcomingConfigSchema = z.object({
const monthConfigSchema = z.object({ calendarIds: calendarIdsSchema });
async function UpcomingEventsWidget({
config,
}: {
config: unknown;
ctx: WidgetContext;
}) {
async function UpcomingEventsWidget({ config }: { config: unknown; ctx: WidgetContext }) {
const parsed = upcomingConfigSchema.parse(config);
const now = new Date();
const end = new Date(now.getTime() + parsed.days * 24 * 60 * 60 * 1000);
@@ -65,7 +60,11 @@ async function MonthWidget({ config }: { config: unknown; ctx: WidgetContext })
const now = new Date();
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const monthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);
const events = await listEvents({ from: monthStart, to: monthEnd, calendarIds: parsed.calendarIds });
const events = await listEvents({
from: monthStart,
to: monthEnd,
calendarIds: parsed.calendarIds,
});
const monthName = now.toLocaleDateString(undefined, { month: "long", year: "numeric" });
+1 -9
View File
@@ -1,13 +1,5 @@
import { sql } from "drizzle-orm";
import {
boolean,
check,
index,
pgTable,
text,
timestamp,
uuid,
} from "drizzle-orm/pg-core";
import { boolean, check, index, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
import { households, users } from "../_core/schema";
export const calendars = pgTable(
+30 -5
View File
@@ -58,7 +58,12 @@ export async function createCalendar(input: z.input<typeof calendarInput>) {
.returning();
if (!calendar) throw new Error("Calendar was not created");
await logActivity({ entityType: "calendar.calendar", entityId: calendar.id, action: "create", payload: { name: calendar.name } });
await logActivity({
entityType: "calendar.calendar",
entityId: calendar.id,
action: "create",
payload: { name: calendar.name },
});
revalidatePath("/calendar");
return calendar;
}
@@ -72,7 +77,12 @@ export async function renameCalendar(input: { id: string; name: string }) {
.set({ name: parsed.name, updatedAt: new Date() })
.where(eq(calendars.id, parsed.id));
await logActivity({ entityType: "calendar.calendar", entityId: parsed.id, action: "update", payload: { name: parsed.name } });
await logActivity({
entityType: "calendar.calendar",
entityId: parsed.id,
action: "update",
payload: { name: parsed.name },
});
revalidatePath("/calendar");
}
@@ -90,7 +100,12 @@ export async function setCalendarVisibility(input: {
.set({ visibility: parsed.visibility, updatedAt: new Date() })
.where(eq(calendars.id, parsed.id));
await logActivity({ entityType: "calendar.calendar", entityId: parsed.id, action: "update", payload: { visibility: parsed.visibility } });
await logActivity({
entityType: "calendar.calendar",
entityId: parsed.id,
action: "update",
payload: { visibility: parsed.visibility },
});
revalidatePath("/calendar");
}
@@ -149,7 +164,12 @@ export async function createEvent(input: z.input<typeof eventInput>) {
}
}
await logActivity({ entityType: "calendar.event", entityId: event.id, action: "create", payload: { title: event.title } });
await logActivity({
entityType: "calendar.event",
entityId: event.id,
action: "create",
payload: { title: event.title },
});
revalidatePath("/calendar");
return {
...event,
@@ -185,7 +205,12 @@ export async function updateEvent(input: { id: string } & Partial<z.input<typeof
})
.where(eq(calendarEvents.id, parsed.id));
await logActivity({ entityType: "calendar.event", entityId: parsed.id, action: "update", payload: parsed.title ? { title: parsed.title } : undefined });
await logActivity({
entityType: "calendar.event",
entityId: parsed.id,
action: "update",
payload: parsed.title ? { title: parsed.title } : undefined,
});
revalidatePath("/calendar");
}
+1 -4
View File
@@ -125,10 +125,7 @@ export async function searchCalendars(query: string, householdId: string) {
.select({ id: calendars.id, name: calendars.name })
.from(calendars)
.where(
and(
eq(calendars.householdId, householdId),
sql`${calendars.name} ilike ${`%${query}%`}`,
),
and(eq(calendars.householdId, householdId), sql`${calendars.name} ilike ${`%${query}%`}`),
)
.limit(10);
+1 -3
View File
@@ -95,9 +95,7 @@ function ItemRow({
)}
<span className={`text-sm ${item.done ? "text-muted-foreground line-through" : ""}`}>
{item.text}
{item.qty && (
<span className="ml-1 text-xs text-muted-foreground">×{item.qty}</span>
)}
{item.qty && <span className="ml-1 text-xs text-muted-foreground">×{item.qty}</span>}
</span>
</li>
);
+1 -5
View File
@@ -36,11 +36,7 @@ const manifest: ModuleManifest = {
resolveUrl: (id) => `/lists/${id}`,
loadForShare: (id) => loadListForShare(id),
renderSharedView: ({ data, capabilities, token }) => (
<ListSharedView
data={data as ListShareData}
canWrite={capabilities.write}
token={token}
/>
<ListSharedView data={data as ListShareData} canWrite={capabilities.write} token={token} />
),
renderActivity: (entry) => {
const name = entry.payload?.name as string | undefined;
+36 -6
View File
@@ -47,7 +47,12 @@ export async function createList(input: z.input<typeof listInput>) {
.returning();
if (!list) throw new Error("List was not created");
await logActivity({ entityType: "lists.list", entityId: list.id, action: "create", payload: { name: list.name } });
await logActivity({
entityType: "lists.list",
entityId: list.id,
action: "create",
payload: { name: list.name },
});
revalidatePath("/lists");
return list;
}
@@ -57,7 +62,12 @@ export async function renameList(input: { id: string; name: string }) {
const { household } = await getCurrentSession();
await assertCanAccessList(parsed.id, household.id);
await db.update(lists).set({ name: parsed.name }).where(eq(lists.id, parsed.id));
await logActivity({ entityType: "lists.list", entityId: parsed.id, action: "update", payload: { name: parsed.name } });
await logActivity({
entityType: "lists.list",
entityId: parsed.id,
action: "update",
payload: { name: parsed.name },
});
revalidatePath("/lists");
revalidatePath(`/lists/${parsed.id}`);
await notifyListChanged(parsed.id);
@@ -98,7 +108,12 @@ export async function addItem(input: z.input<typeof itemInput>) {
.returning();
if (!item) throw new Error("List item was not created");
await logActivity({ entityType: "lists.item", entityId: item.id, action: "create", payload: { text: item.text } });
await logActivity({
entityType: "lists.item",
entityId: item.id,
action: "create",
payload: { text: item.text },
});
revalidatePath(`/lists/${parsed.listId}`);
await notifyListChanged(parsed.listId);
return getList(parsed.listId);
@@ -127,7 +142,12 @@ export async function toggleItem(input: { id: string; done?: boolean }) {
.set({ done, updatedAt: new Date() })
.where(eq(listItems.id, parsed.id));
await logActivity({ entityType: "lists.item", entityId: parsed.id, action: "toggle", payload: { done, text: existing.text } });
await logActivity({
entityType: "lists.item",
entityId: parsed.id,
action: "toggle",
payload: { done, text: existing.text },
});
revalidatePath(`/lists/${existing.listId}`);
await notifyListChanged(existing.listId);
return getList(existing.listId);
@@ -150,7 +170,12 @@ export async function updateItem(input: z.input<typeof updateItemInput>) {
})
.where(eq(listItems.id, parsed.id));
await logActivity({ entityType: "lists.item", entityId: parsed.id, action: "update", payload: { text: parsed.text ?? existing.text } });
await logActivity({
entityType: "lists.item",
entityId: parsed.id,
action: "update",
payload: { text: parsed.text ?? existing.text },
});
revalidatePath(`/lists/${existing.listId}`);
await notifyListChanged(existing.listId);
return getList(existing.listId);
@@ -160,7 +185,12 @@ export async function deleteItem(input: { id: string }) {
const parsed = z.object({ id: z.string().uuid() }).parse(input);
const { household } = await getCurrentSession();
const existing = await getAuthorizedItem(parsed.id, household.id);
await logActivity({ entityType: "lists.item", entityId: parsed.id, action: "delete", payload: { text: existing.text } });
await logActivity({
entityType: "lists.item",
entityId: parsed.id,
action: "delete",
payload: { text: existing.text },
});
await db.delete(listItems).where(eq(listItems.id, parsed.id));
revalidatePath(`/lists/${existing.listId}`);
await notifyListChanged(existing.listId);
+4 -1
View File
@@ -193,7 +193,10 @@ export async function listListsWithItems(): Promise<ListWithItemsDto[]> {
.where(
and(
inArray(listItems.listId, listIds),
or(eq(listItems.done, false), and(eq(listItems.done, true), gt(listItems.updatedAt, cutoff))),
or(
eq(listItems.done, false),
and(eq(listItems.done, true), gt(listItems.updatedAt, cutoff)),
),
),
)
.orderBy(asc(listItems.done), asc(listItems.position), asc(listItems.createdAt));
+1 -4
View File
@@ -41,10 +41,7 @@ export async function toggleShareListItem(rawToken: string, itemId: string): Pro
if (!item) throw new Error("Item not found");
const done = !item.done;
await db
.update(listItems)
.set({ done, updatedAt: new Date() })
.where(eq(listItems.id, itemId));
await db.update(listItems).set({ done, updatedAt: new Date() }).where(eq(listItems.id, itemId));
await logShareActivity({
householdId: resolved.householdId,
+6 -4
View File
@@ -77,9 +77,7 @@ export function NoteEditor({ note }: { note?: NoteDto }) {
{pinned ? "Unpin note" : "Pin note"}
</Button>
) : null}
{currentNote ? (
<ShareButton entityType="notes.note" entityId={currentNote.id} />
) : null}
{currentNote ? <ShareButton entityType="notes.note" entityId={currentNote.id} /> : null}
{currentNote ? (
<Button variant="destructive" onClick={removeNote} disabled={isPending}>
<Trash2 />
@@ -97,7 +95,11 @@ export function NoteEditor({ note }: { note?: NoteDto }) {
<section className="grid gap-4 rounded-lg border bg-background p-4">
<div className="space-y-1.5">
<Label htmlFor="note-title">Title</Label>
<Input id="note-title" value={title} onChange={(event) => setTitle(event.target.value)} />
<Input
id="note-title"
value={title}
onChange={(event) => setTitle(event.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="note-body">Body</Label>
+1 -3
View File
@@ -20,9 +20,7 @@ export function NoteSharedView({ data }: { data: NoteShareData }) {
<h1 className="text-2xl font-semibold">{data.title}</h1>
<p className="text-xs text-muted-foreground">Updated {updatedAt}</p>
</header>
{data.body && (
<p className="whitespace-pre-wrap text-sm leading-relaxed">{data.body}</p>
)}
{data.body && <p className="whitespace-pre-wrap text-sm leading-relaxed">{data.body}</p>}
</div>
);
}
+1 -3
View File
@@ -26,9 +26,7 @@ async function NotesWidget({ config }: { config: unknown; ctx: WidgetContext })
{notes.map((note) => (
<li key={note.id} className="space-y-0.5">
<p className="text-sm font-medium leading-snug">{note.title}</p>
{note.body && (
<p className="line-clamp-2 text-xs text-muted-foreground">{note.body}</p>
)}
{note.body && <p className="line-clamp-2 text-xs text-muted-foreground">{note.body}</p>}
</li>
))}
</ul>
+24 -4
View File
@@ -53,7 +53,12 @@ export async function createNote(input: z.input<typeof noteInput>) {
});
}
await logActivity({ entityType: "notes.note", entityId: note.id, action: "create", payload: { title: note.title } });
await logActivity({
entityType: "notes.note",
entityId: note.id,
action: "create",
payload: { title: note.title },
});
revalidatePath("/notes");
return note;
}
@@ -91,7 +96,12 @@ export async function updateNote(input: z.input<typeof updateNoteInput>) {
}
}
await logActivity({ entityType: "notes.note", entityId: note.id, action: "update", payload: { title: note.title } });
await logActivity({
entityType: "notes.note",
entityId: note.id,
action: "update",
payload: { title: note.title },
});
revalidatePath("/notes");
revalidatePath(`/notes/${parsed.id}`);
return note;
@@ -108,7 +118,12 @@ export async function setNotePinned(input: { id: string; pinned: boolean }) {
.where(eq(notes.id, parsed.id));
const note = await getNote(parsed.id);
await logActivity({ entityType: "notes.note", entityId: parsed.id, action: parsed.pinned ? "pin" : "unpin", payload: note ? { title: note.title } : undefined });
await logActivity({
entityType: "notes.note",
entityId: parsed.id,
action: parsed.pinned ? "pin" : "unpin",
payload: note ? { title: note.title } : undefined,
});
revalidatePath("/notes");
revalidatePath(`/notes/${parsed.id}`);
return note;
@@ -120,7 +135,12 @@ export async function deleteNote(input: { id: string }) {
await assertCanAccessNote(parsed.id, household.id);
const note = await getNote(parsed.id);
await logActivity({ entityType: "notes.note", entityId: parsed.id, action: "delete", payload: note ? { title: note.title } : undefined });
await logActivity({
entityType: "notes.note",
entityId: parsed.id,
action: "delete",
payload: note ? { title: note.title } : undefined,
});
await cancelReminder("notes.note", parsed.id);
await db.delete(notes).where(eq(notes.id, parsed.id));
+4 -22
View File
@@ -1,11 +1,7 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": [
"ES2023",
"DOM",
"DOM.Iterable"
],
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
@@ -30,23 +26,9 @@
}
],
"paths": {
"@/*": [
"src/*"
]
"@/*": ["src/*"]
}
},
"include": [
"*.cts",
"*.mts",
"*.ts",
"src/**/*",
"scripts/**/*",
".next/types/**/*.ts"
],
"exclude": [
"node_modules",
".next",
"dist",
"drizzle"
]
"include": ["*.cts", "*.mts", "*.ts", "src/**/*", "scripts/**/*", ".next/types/**/*.ts"],
"exclude": ["node_modules", ".next", "dist", "drizzle"]
}