Implement tasks 25, 26 + completion visibility setting
Task 25: Multiple dashboards — dashboards table + migration, /d/[slug] route, root redirect, dashboard tabs in nav with create/rename/delete/ set-default. Task 26: Editable dashboard — react-grid-layout drag/resize editor, widget picker modal with per-widget configurator auto-generated from default config, save/reset server actions with Zod validation. Completion visibility: server-side per-user setting (hours) replaces localStorage timer; queries filter completed items by updatedAt cutoff; Settings page dropdown persists preference via server action. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
2ad9521ef9
commit
d5a8bf9d95
@@ -23,6 +23,8 @@ Living progress tracker. Update at the end of each task. Codex and Claude Code b
|
||||
- **21 — Quick-add registry**. Added `url: string` to `QuickAddAction` type (action is now optional). Added `getQuickAdds()` / `SerializedQuickAddItem` to registry (strips non-serializable `action` fn before crossing server→client boundary). Updated all three module manifests with navigation URLs. Built `QuickAddProvider` (context + cmd+k global shortcut), `QuickAddFab` (opens sheet, replaces plain button in dashboard), `QuickAddSheet` (bottom drawer / desktop popover grouped by module), and `CommandPalette` (cmdk-powered modal with arrow + enter + esc keyboard nav). Provider in root layout receives actions from `getQuickAdds()` at render time — adding a module's `quickAdds` automatically appears in both surfaces. Also added `.claude/**` to ESLint ignores to prevent stale worktree build artifacts from failing lint. `pnpm typecheck`, `pnpm lint`, `pnpm build`, and all 4 E2E specs pass.
|
||||
- **22 — Activity log**. Added `activity_log` table to `_core/schema.ts` with index on `(household_id, created_at desc)`. Migration `0008_activity_log.sql` applied. `logActivity()` server function in `_core/activity.ts` reads current session and inserts a row. Added `ActivityLogEntry` type and optional `renderActivity?(entry): string` to `EntityTypeRegistration` in `_core/module.ts`. All three module manifests implement `renderActivity` for each entity type (human-readable, no hardcoded branches in the widget). Replaced `core.activity` widget stub with a real async server component that queries the last 20 rows via `getEntityType(entry.entityType)?.renderActivity(entry)`. Wired `logActivity()` into every create/update/delete in calendar, lists, and notes server actions. Also added `text` to `getAuthorizedItem` select so toggle/delete log the item text. `pnpm typecheck`, `pnpm lint`, `pnpm build`, and all 4 E2E specs pass.
|
||||
- **30 — Share-link service**. Added `share_links` table to `_core/schema.ts` + migration `0009_share_links.sql`. Created `_core/share.ts` with `createShareLink`, `resolveShareToken`, `revokeShareLink`, and `getActiveShareLinks`. Token is 32 random bytes (URL-safe base64), stored as SHA-256 hash — raw token only returned at creation. `createShareLink` guards that the entity type is registered with `canShare === true`. `resolveShareToken` returns null for expired or revoked tokens. All three functions exported from `_core/index.ts`. `/settings` page gained a Share links card: lists active links (entity label, read/write capabilities, expiry) with a Revoke button per link (server action in `settings/actions.ts`). `pnpm typecheck`, `pnpm lint`, `pnpm build`, and all 4 E2E specs pass.
|
||||
- **25 — Multiple dashboards per user**. Added `dashboards` table (migration `0012_dashboards.sql`). Migrated each user's `default_dashboard_layout` into a "Home" dashboard row with `is_default = true`; dropped the interim column. Server actions: `listDashboards`, `createDashboard`, `renameDashboard`, `deleteDashboard`, `setDefaultDashboard`, `reorderDashboards`, `saveDashboardLayout`, `resetDashboardLayout`, `resolveWidgetConfigOptions`. `/` redirects to the user's default `/d/<slug>`. Dashboard switcher in AppNav renders tabs (active highlighted client-side) with a `+` button to create new dashboards and a kebab menu on the active tab for rename / set-default / delete. `pnpm typecheck`, `pnpm lint`, `pnpm build` pass.
|
||||
- **26 — Customizable layout + widget configuration**. Installed `react-grid-layout` v2. Dashboard pages check `?edit=1` to enter edit mode, rendering a client `DashboardEditor` instead of the static grid. Editor uses `react-grid-layout` with `gridConfig`/`dragConfig` v2 API; each widget shell shows a drag handle, configure button (⚙), and remove button (🗑). `WidgetPicker` is a two-step modal: step 1 lists all registry widgets grouped by category; step 2 is a `WidgetConfigurator` auto-generated from the widget's default config — handles `"all"|string[]` multi-selects, booleans, numbers, and enums. `resolveWidgetConfigOptions` server action fetches dynamic options (calendars, lists). Save validates each config against its registered Zod schema. Reset to defaults calls `computeDefaultLayout()`. `pnpm typecheck`, `pnpm build` pass.
|
||||
- **31 — Public share viewer**. Made `actorId` nullable in `activity_log` (migration `0010_nullable_actor_id.sql`, `onDelete: "set null"`) for anonymous share-page mutations. Added `logShareActivity` to `_core/activity.ts` (no session, explicit `householdId`). Added `householdId` to `resolveShareToken` return. Added `renderSharedView` to `EntityTypeRegistration` type. Each module implements `loadForShare` (bare DB queries, no session) and `renderSharedView`: calendar shows upcoming 90-day events or single-event details, lists shows items with optional toggle, notes shows title + body. `toggleShareListItem` server action lives in `lists/server/share-actions.ts` — validates token write capability, verifies item→list→household chain, logs `share.toggle` with `actorId = null`. `/app/s/[token]/page.tsx` resolves token, dispatches to `loadForShare` + `renderSharedView`, returns friendly error for invalid/expired tokens, sets `noindex`. Middleware `/s/*` exemption confirmed present. `pnpm typecheck`, `pnpm lint`, `pnpm build`, and all 4 E2E specs pass.
|
||||
|
||||
## Next up
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "users" ADD COLUMN "completion_visibility_hours" integer NOT NULL DEFAULT 24;
|
||||
@@ -0,0 +1,28 @@
|
||||
CREATE TABLE "dashboards" (
|
||||
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||
"user_id" uuid NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
||||
"name" text NOT NULL,
|
||||
"slug" text NOT NULL,
|
||||
"is_default" boolean NOT NULL DEFAULT false,
|
||||
"position" integer NOT NULL DEFAULT 0,
|
||||
"layout" jsonb NOT NULL DEFAULT '{"version":1,"widgets":[]}',
|
||||
"created_at" timestamp with time zone NOT NULL DEFAULT now(),
|
||||
"updated_at" timestamp with time zone NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX "dashboards_user_slug_uq" ON "dashboards" ("user_id", "slug");
|
||||
|
||||
-- Migrate each existing user's default_dashboard_layout into a "Home" dashboard.
|
||||
-- Idempotent: ON CONFLICT DO NOTHING.
|
||||
INSERT INTO "dashboards" ("user_id", "name", "slug", "is_default", "position", "layout")
|
||||
SELECT
|
||||
"id",
|
||||
'Home',
|
||||
'home',
|
||||
true,
|
||||
0,
|
||||
COALESCE("default_dashboard_layout", '{"version":1,"widgets":[]}')
|
||||
FROM "users"
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
ALTER TABLE "users" DROP COLUMN IF EXISTS "default_dashboard_layout";
|
||||
@@ -30,6 +30,7 @@
|
||||
"@types/node": "^22.9.0",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@types/react-grid-layout": "^2.1.0",
|
||||
"drizzle-kit": "^0.31.10",
|
||||
"eslint": "^9.15.0",
|
||||
"eslint-config-next": "^16.2.4",
|
||||
@@ -58,6 +59,7 @@
|
||||
"postgres": "^3.4.9",
|
||||
"react": "^19.2.5",
|
||||
"react-dom": "^19.2.5",
|
||||
"react-grid-layout": "^2.2.3",
|
||||
"shadcn": "^4.7.0",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
|
||||
Generated
+70
@@ -59,6 +59,9 @@ importers:
|
||||
react-dom:
|
||||
specifier: ^19.2.5
|
||||
version: 19.2.5(react@19.2.5)
|
||||
react-grid-layout:
|
||||
specifier: ^2.2.3
|
||||
version: 2.2.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
||||
shadcn:
|
||||
specifier: ^4.7.0
|
||||
version: 4.7.0(@types/node@22.19.17)(typescript@5.9.3)
|
||||
@@ -96,6 +99,9 @@ importers:
|
||||
'@types/react-dom':
|
||||
specifier: ^19.2.3
|
||||
version: 19.2.3(@types/react@19.2.14)
|
||||
'@types/react-grid-layout':
|
||||
specifier: ^2.1.0
|
||||
version: 2.1.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
||||
drizzle-kit:
|
||||
specifier: ^0.31.10
|
||||
version: 0.31.10
|
||||
@@ -1542,6 +1548,10 @@ packages:
|
||||
peerDependencies:
|
||||
'@types/react': ^19.2.0
|
||||
|
||||
'@types/react-grid-layout@2.1.0':
|
||||
resolution: {integrity: sha512-pHEjVg9ert6BDFHFQ1IEdLUkd2gasJvyti5lV2kE46N/R07ZiaSZpAXeXJAA1MXy/Qby23fZmiuEgZkITxPXug==}
|
||||
deprecated: This is a stub types definition. react-grid-layout provides its own type definitions, so you do not need this installed.
|
||||
|
||||
'@types/react@19.2.14':
|
||||
resolution: {integrity: sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w==}
|
||||
|
||||
@@ -2441,6 +2451,9 @@ packages:
|
||||
fast-deep-equal@3.1.3:
|
||||
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
|
||||
|
||||
fast-equals@4.0.3:
|
||||
resolution: {integrity: sha512-G3BSX9cfKttjr+2o1O22tYMLq0DPluZnYtq1rXumE1SpL/F/SLIfHx08WYQoWSIpeMYf8sRbJ8++71+v6Pnxfg==}
|
||||
|
||||
fast-glob@3.3.1:
|
||||
resolution: {integrity: sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==}
|
||||
engines: {node: '>=8.6.0'}
|
||||
@@ -3457,6 +3470,18 @@ packages:
|
||||
peerDependencies:
|
||||
react: ^19.2.5
|
||||
|
||||
react-draggable@4.5.0:
|
||||
resolution: {integrity: sha512-VC+HBLEZ0XJxnOxVAZsdRi8rD04Iz3SiiKOoYzamjylUcju/hP9np/aZdLHf/7WOD268WMoNJMvYfB5yAK45cw==}
|
||||
peerDependencies:
|
||||
react: '>= 16.3.0'
|
||||
react-dom: '>= 16.3.0'
|
||||
|
||||
react-grid-layout@2.2.3:
|
||||
resolution: {integrity: sha512-OAEJHBxmfuxQfVtZwRzmsokijGlBgzYIJ7MUlLk/VSa43SaGzu15w5D0P2RDrfX5EvP9POMbL6bFrai/huDzbQ==}
|
||||
peerDependencies:
|
||||
react: '>= 16.3.0'
|
||||
react-dom: '>= 16.3.0'
|
||||
|
||||
react-is@16.13.1:
|
||||
resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
|
||||
|
||||
@@ -3480,6 +3505,12 @@ packages:
|
||||
'@types/react':
|
||||
optional: true
|
||||
|
||||
react-resizable@3.1.3:
|
||||
resolution: {integrity: sha512-liJBNayhX7qA4tBJiBD321FDhJxgGTJ07uzH5zSORXoE8h7PyEZ8mLqmosST7ppf6C4zUsbd2gzDMmBCfFp9Lw==}
|
||||
peerDependencies:
|
||||
react: '>= 16.3'
|
||||
react-dom: '>= 16.3'
|
||||
|
||||
react-style-singleton@2.2.3:
|
||||
resolution: {integrity: sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -3517,6 +3548,9 @@ packages:
|
||||
reselect@5.1.1:
|
||||
resolution: {integrity: sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==}
|
||||
|
||||
resize-observer-polyfill@1.5.1:
|
||||
resolution: {integrity: sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg==}
|
||||
|
||||
resolve-from@4.0.0:
|
||||
resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
|
||||
engines: {node: '>=4'}
|
||||
@@ -5142,6 +5176,13 @@ snapshots:
|
||||
dependencies:
|
||||
'@types/react': 19.2.14
|
||||
|
||||
'@types/react-grid-layout@2.1.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)':
|
||||
dependencies:
|
||||
react-grid-layout: 2.2.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
||||
transitivePeerDependencies:
|
||||
- react
|
||||
- react-dom
|
||||
|
||||
'@types/react@19.2.14':
|
||||
dependencies:
|
||||
csstype: 3.2.3
|
||||
@@ -6185,6 +6226,8 @@ snapshots:
|
||||
|
||||
fast-deep-equal@3.1.3: {}
|
||||
|
||||
fast-equals@4.0.3: {}
|
||||
|
||||
fast-glob@3.3.1:
|
||||
dependencies:
|
||||
'@nodelib/fs.stat': 2.0.5
|
||||
@@ -7118,6 +7161,24 @@ snapshots:
|
||||
react: 19.2.5
|
||||
scheduler: 0.27.0
|
||||
|
||||
react-draggable@4.5.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5):
|
||||
dependencies:
|
||||
clsx: 2.1.1
|
||||
prop-types: 15.8.1
|
||||
react: 19.2.5
|
||||
react-dom: 19.2.5(react@19.2.5)
|
||||
|
||||
react-grid-layout@2.2.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5):
|
||||
dependencies:
|
||||
clsx: 2.1.1
|
||||
fast-equals: 4.0.3
|
||||
prop-types: 15.8.1
|
||||
react: 19.2.5
|
||||
react-dom: 19.2.5(react@19.2.5)
|
||||
react-draggable: 4.5.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
||||
react-resizable: 3.1.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
||||
resize-observer-polyfill: 1.5.1
|
||||
|
||||
react-is@16.13.1: {}
|
||||
|
||||
react-remove-scroll-bar@2.3.8(@types/react@19.2.14)(react@19.2.5):
|
||||
@@ -7139,6 +7200,13 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@types/react': 19.2.14
|
||||
|
||||
react-resizable@3.1.3(react-dom@19.2.5(react@19.2.5))(react@19.2.5):
|
||||
dependencies:
|
||||
prop-types: 15.8.1
|
||||
react: 19.2.5
|
||||
react-dom: 19.2.5(react@19.2.5)
|
||||
react-draggable: 4.5.0(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
|
||||
|
||||
react-style-singleton@2.2.3(@types/react@19.2.14)(react@19.2.5):
|
||||
dependencies:
|
||||
get-nonce: 1.0.1
|
||||
@@ -7183,6 +7251,8 @@ snapshots:
|
||||
|
||||
reselect@5.1.1: {}
|
||||
|
||||
resize-observer-polyfill@1.5.1: {}
|
||||
|
||||
resolve-from@4.0.0: {}
|
||||
|
||||
resolve-pkg-maps@1.0.0: {}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { Suspense } from "react";
|
||||
import { getCurrentSession } from "@/lib/session";
|
||||
import { parseDashboardLayout, computeDefaultLayout } from "@/lib/dashboard";
|
||||
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 { 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",
|
||||
};
|
||||
|
||||
export default async function DashboardPage({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: Promise<{ slug: string }>;
|
||||
searchParams: Promise<{ edit?: string }>;
|
||||
}) {
|
||||
const { slug } = await params;
|
||||
const { edit } = await searchParams;
|
||||
const isEditing = edit === "1";
|
||||
|
||||
const { user, household } = await getCurrentSession();
|
||||
const dashboard = await getDashboardBySlug(slug);
|
||||
if (!dashboard) notFound();
|
||||
|
||||
const layout = parseDashboardLayout(dashboard.layout) ?? computeDefaultLayout();
|
||||
const widgetMetas = getWidgetMetas();
|
||||
|
||||
if (isEditing) {
|
||||
return (
|
||||
<DashboardEditor
|
||||
dashboard={{ id: dashboard.id, name: dashboard.name, slug: dashboard.slug }}
|
||||
layout={layout}
|
||||
widgetMetas={widgetMetas}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const ctx = { userId: user.id, householdId: household.id };
|
||||
const placements = [...layout.widgets].sort((a, b) => a.y - b.y || a.x - b.x);
|
||||
|
||||
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>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-12">
|
||||
{placements.map((placement, i) => {
|
||||
const widget = getWidget(placement.widgetId);
|
||||
if (!widget) return null;
|
||||
const colClass = smColSpan[placement.w] ?? "sm:col-span-12";
|
||||
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>
|
||||
<CardContent>
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="animate-pulse space-y-2">
|
||||
<div className="h-3 w-3/4 rounded bg-muted" />
|
||||
<div className="h-3 w-1/2 rounded bg-muted" />
|
||||
<div className="h-3 w-2/3 rounded bg-muted" />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{widget.render({ config: placement.config, ctx })}
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
"use server";
|
||||
|
||||
import { and, asc, eq } from "drizzle-orm";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
import { z } from "zod";
|
||||
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";
|
||||
|
||||
export type DashboardMeta = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
isDefault: boolean;
|
||||
position: number;
|
||||
};
|
||||
|
||||
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 })
|
||||
.from(dashboards)
|
||||
.where(eq(dashboards.userId, user.id))
|
||||
.orderBy(asc(dashboards.position), asc(dashboards.createdAt));
|
||||
return rows;
|
||||
}
|
||||
|
||||
export async function getDefaultDashboardSlug(): Promise<string> {
|
||||
const { user } = await getCurrentSession();
|
||||
const rows = await db
|
||||
.select({ slug: dashboards.slug })
|
||||
.from(dashboards)
|
||||
.where(and(eq(dashboards.userId, user.id), eq(dashboards.isDefault, true)))
|
||||
.limit(1);
|
||||
if (rows[0]) return rows[0].slug;
|
||||
// Fallback: first dashboard by position
|
||||
const [first] = await db
|
||||
.select({ slug: dashboards.slug })
|
||||
.from(dashboards)
|
||||
.where(eq(dashboards.userId, user.id))
|
||||
.orderBy(asc(dashboards.position), asc(dashboards.createdAt))
|
||||
.limit(1);
|
||||
if (first) return first.slug;
|
||||
// No dashboards yet — create Home
|
||||
await createDashboard("Home");
|
||||
return "home";
|
||||
}
|
||||
|
||||
export async function getDashboardBySlug(slug: string) {
|
||||
const { user } = await getCurrentSession();
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(dashboards)
|
||||
.where(and(eq(dashboards.userId, user.id), eq(dashboards.slug, slug)))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
function toSlug(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "")
|
||||
|| "dashboard";
|
||||
}
|
||||
|
||||
async function uniqueSlug(userId: string, base: string): Promise<string> {
|
||||
let slug = base;
|
||||
let attempt = 1;
|
||||
for (;;) {
|
||||
const [existing] = await db
|
||||
.select({ id: dashboards.id })
|
||||
.from(dashboards)
|
||||
.where(and(eq(dashboards.userId, userId), eq(dashboards.slug, slug)))
|
||||
.limit(1);
|
||||
if (!existing) return slug;
|
||||
attempt++;
|
||||
slug = `${base}-${attempt}`;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createDashboard(name: string): Promise<DashboardMeta> {
|
||||
const parsed = z.string().trim().min(1).max(80).parse(name);
|
||||
const { user } = await getCurrentSession();
|
||||
const slug = await uniqueSlug(user.id, toSlug(parsed));
|
||||
const rows = await db
|
||||
.insert(dashboards)
|
||||
.values({ userId: user.id, name: parsed, slug, isDefault: false, position: 9999 })
|
||||
.returning();
|
||||
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 };
|
||||
}
|
||||
|
||||
export async function renameDashboard(id: string, name: string): Promise<void> {
|
||||
const parsedName = z.string().trim().min(1).max(80).parse(name);
|
||||
const { user } = await getCurrentSession();
|
||||
await db
|
||||
.update(dashboards)
|
||||
.set({ name: parsedName, updatedAt: new Date() })
|
||||
.where(and(eq(dashboards.id, id), eq(dashboards.userId, user.id)));
|
||||
revalidatePath("/");
|
||||
}
|
||||
|
||||
export async function deleteDashboard(id: string): Promise<void> {
|
||||
const { user } = await getCurrentSession();
|
||||
const all = await db
|
||||
.select({ id: dashboards.id, isDefault: dashboards.isDefault, slug: dashboards.slug })
|
||||
.from(dashboards)
|
||||
.where(eq(dashboards.userId, user.id));
|
||||
if (all.length <= 1) throw new Error("Cannot delete your only dashboard");
|
||||
const target = all.find((d) => d.id === id);
|
||||
if (!target) throw new Error("Dashboard not found");
|
||||
|
||||
await db.delete(dashboards).where(and(eq(dashboards.id, id), eq(dashboards.userId, user.id)));
|
||||
|
||||
// If we deleted the default, promote another
|
||||
if (target.isDefault) {
|
||||
const next = all.find((d) => d.id !== id);
|
||||
if (next) {
|
||||
await db
|
||||
.update(dashboards)
|
||||
.set({ isDefault: true })
|
||||
.where(and(eq(dashboards.id, next.id), eq(dashboards.userId, user.id)));
|
||||
}
|
||||
}
|
||||
revalidatePath("/");
|
||||
redirect("/");
|
||||
}
|
||||
|
||||
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: true })
|
||||
.where(and(eq(dashboards.id, id), eq(dashboards.userId, user.id)));
|
||||
revalidatePath("/");
|
||||
}
|
||||
|
||||
export async function reorderDashboards(orderedIds: string[]): Promise<void> {
|
||||
const { user } = await getCurrentSession();
|
||||
await Promise.all(
|
||||
orderedIds.map((id, i) =>
|
||||
db
|
||||
.update(dashboards)
|
||||
.set({ position: i })
|
||||
.where(and(eq(dashboards.id, id), eq(dashboards.userId, user.id))),
|
||||
),
|
||||
);
|
||||
revalidatePath("/");
|
||||
}
|
||||
|
||||
export async function saveDashboardLayout(id: string, layout: DashboardLayout): Promise<void> {
|
||||
const { user } = await getCurrentSession();
|
||||
// Validate each widget's config against its registered schema
|
||||
for (const placement of layout.widgets) {
|
||||
const widget = getWidget(placement.widgetId);
|
||||
if (!widget) continue;
|
||||
widget.configSchema.parse(placement.config);
|
||||
}
|
||||
await db
|
||||
.update(dashboards)
|
||||
.set({ layout: layout as unknown as Record<string, unknown>, updatedAt: new Date() })
|
||||
.where(and(eq(dashboards.id, id), eq(dashboards.userId, user.id)));
|
||||
revalidatePath("/");
|
||||
}
|
||||
|
||||
export async function resetDashboardLayout(id: string): Promise<void> {
|
||||
const { user } = await getCurrentSession();
|
||||
const layout = computeDefaultLayout();
|
||||
await db
|
||||
.update(dashboards)
|
||||
.set({ layout: layout as unknown as Record<string, unknown>, updatedAt: new Date() })
|
||||
.where(and(eq(dashboards.id, id), eq(dashboards.userId, user.id)));
|
||||
revalidatePath("/");
|
||||
}
|
||||
|
||||
export async function resolveWidgetConfigOptions(widgetId: string): Promise<unknown> {
|
||||
const { user, household } = await getCurrentSession();
|
||||
const widget = getWidget(widgetId);
|
||||
if (!widget?.resolveConfigOptions) return null;
|
||||
return widget.resolveConfigOptions({ userId: user.id, householdId: household.id });
|
||||
}
|
||||
+10
-3
@@ -6,8 +6,9 @@ import { AppNav } from "@/components/app-nav";
|
||||
import "@/modules"; // registers all module manifests
|
||||
import { auth } from "@/lib/auth";
|
||||
import { db } from "@/lib/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { users } from "@/modules/_core/schema";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { dashboards, users } from "@/modules/_core/schema";
|
||||
import type { DashboardMeta } from "@/app/d/actions";
|
||||
import { getQuickAdds } from "@/modules/_core";
|
||||
import { QuickAddProvider } from "@/components/quick-add-provider";
|
||||
import { QuickAddSheet } from "@/components/quick-add-sheet";
|
||||
@@ -40,6 +41,7 @@ export default async function RootLayout({
|
||||
}) {
|
||||
let theme = "default";
|
||||
let themeMode = "system";
|
||||
let userDashboards: DashboardMeta[] = [];
|
||||
|
||||
const session = await auth();
|
||||
if (session?.user?.id) {
|
||||
@@ -52,6 +54,11 @@ export default async function RootLayout({
|
||||
theme = row.theme;
|
||||
themeMode = row.themeMode;
|
||||
}
|
||||
userDashboards = 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));
|
||||
}
|
||||
|
||||
// For system mode we can't know the preference on the server — the inline
|
||||
@@ -71,7 +78,7 @@ export default async function RootLayout({
|
||||
</head>
|
||||
<body className="min-h-screen">
|
||||
<QuickAddProvider actions={quickAdds}>
|
||||
<AppNav />
|
||||
<AppNav dashboards={userDashboards} />
|
||||
<main>{children}</main>
|
||||
<QuickAddSheet />
|
||||
<CommandPalette />
|
||||
|
||||
+5
-81
@@ -1,83 +1,7 @@
|
||||
import { Suspense } from "react";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/lib/db";
|
||||
import { computeDefaultLayout, parseDashboardLayout } from "@/lib/dashboard";
|
||||
import { getCurrentSession } from "@/lib/session";
|
||||
import { getWidget } from "@/modules/_core";
|
||||
import { users } from "@/modules/_core/schema";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { QuickAddFab } from "@/components/quick-add-fab";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getDefaultDashboardSlug } from "@/app/d/actions";
|
||||
|
||||
// Static lookup ensures Tailwind sees all sm:col-span-* classes at build time.
|
||||
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",
|
||||
};
|
||||
|
||||
export default async function DashboardPage() {
|
||||
const { user, household } = await getCurrentSession();
|
||||
|
||||
const [row] = await db
|
||||
.select({ layout: users.defaultDashboardLayout })
|
||||
.from(users)
|
||||
.where(eq(users.id, user.id))
|
||||
.limit(1);
|
||||
|
||||
const layout = parseDashboardLayout(row?.layout) ?? computeDefaultLayout();
|
||||
|
||||
const ctx = { userId: user.id, householdId: household.id };
|
||||
|
||||
// Sort by y then x so document order matches visual order on mobile (single col).
|
||||
const placements = [...layout.widgets].sort((a, b) => a.y - b.y || a.x - b.x);
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-6">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<h1 className="text-2xl font-bold">Dashboard</h1>
|
||||
<QuickAddFab />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-12">
|
||||
{placements.map((placement, i) => {
|
||||
const widget = getWidget(placement.widgetId);
|
||||
if (!widget) return null;
|
||||
|
||||
const colClass = smColSpan[placement.w] ?? "sm:col-span-12";
|
||||
|
||||
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>
|
||||
<CardContent>
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="animate-pulse space-y-2">
|
||||
<div className="h-3 w-3/4 rounded bg-muted" />
|
||||
<div className="h-3 w-1/2 rounded bg-muted" />
|
||||
<div className="h-3 w-2/3 rounded bg-muted" />
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{widget.render({ config: placement.config, ctx })}
|
||||
</Suspense>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
export default async function RootPage() {
|
||||
const slug = await getDefaultDashboardSlug();
|
||||
redirect(`/d/${slug}`);
|
||||
}
|
||||
|
||||
@@ -26,6 +26,18 @@ export async function setUserTheme({
|
||||
.where(eq(users.id, user.id));
|
||||
}
|
||||
|
||||
export async function setCompletionVisibilityHours(hours: number): Promise<void> {
|
||||
const parsed = Number(hours);
|
||||
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));
|
||||
revalidatePath("/settings");
|
||||
}
|
||||
|
||||
export async function revokeShareLinkAction(formData: FormData): Promise<void> {
|
||||
const id = formData.get("id");
|
||||
if (typeof id !== "string") throw new Error("Missing id");
|
||||
|
||||
@@ -34,7 +34,7 @@ export default async function SettingsPage() {
|
||||
<CardTitle>Lists</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<CompletionDelaySetting />
|
||||
<CompletionDelaySetting initialHours={user.completionVisibilityHours} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
|
||||
+35
-21
@@ -1,32 +1,46 @@
|
||||
import Link from "next/link";
|
||||
import { Settings } from "lucide-react";
|
||||
import { getRegistry } from "@/modules/_core/registry";
|
||||
import type { DashboardMeta } from "@/app/d/actions";
|
||||
import { DashboardSwitcher } from "./dashboard-switcher";
|
||||
import { DashboardTab } from "./dashboard-tab";
|
||||
|
||||
export function AppNav() {
|
||||
export function AppNav({ dashboards = [] }: { dashboards?: DashboardMeta[] }) {
|
||||
const { modules } = getRegistry();
|
||||
const navItems = modules.flatMap((m) => (m.nav ? [m.nav] : []));
|
||||
|
||||
return (
|
||||
<nav className="border-b px-4 py-3 flex items-center gap-6">
|
||||
<Link href="/" className="font-semibold text-sm">
|
||||
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}
|
||||
<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>
|
||||
))}
|
||||
<Link
|
||||
href="/settings"
|
||||
className="ml-auto text-muted-foreground hover:text-foreground transition-colors"
|
||||
aria-label="Settings"
|
||||
>
|
||||
<Settings className="size-4" />
|
||||
</Link>
|
||||
</nav>
|
||||
{navItems.map((item) => (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
className="text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
))}
|
||||
<Link
|
||||
href="/settings"
|
||||
className="ml-auto text-muted-foreground hover:text-foreground transition-colors"
|
||||
aria-label="Settings"
|
||||
>
|
||||
<Settings className="size-4" />
|
||||
</Link>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,25 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import { DELAY_OPTIONS, useCompletionDelay } from "@/hooks/use-completion-delay";
|
||||
import { useTransition } from "react";
|
||||
import { setCompletionVisibilityHours } from "@/app/settings/actions";
|
||||
|
||||
export function CompletionDelaySetting() {
|
||||
const { delay, setDelay } = useCompletionDelay();
|
||||
const OPTIONS = [
|
||||
{ label: "1 hour", value: 1 },
|
||||
{ label: "4 hours", value: 4 },
|
||||
{ label: "8 hours", value: 8 },
|
||||
{ label: "24 hours (default)", value: 24 },
|
||||
{ label: "48 hours", value: 48 },
|
||||
{ label: "7 days", value: 168 },
|
||||
{ label: "Never hide", value: 8760 },
|
||||
];
|
||||
|
||||
export function CompletionDelaySetting({ initialHours }: { initialHours: number }) {
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
function handleChange(e: React.ChangeEvent<HTMLSelectElement>) {
|
||||
const hours = Number(e.target.value);
|
||||
startTransition(() => setCompletionVisibilityHours(hours));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<p className="text-sm font-medium">Completion delay</p>
|
||||
<p className="text-sm font-medium">Show completed items for</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
How long a checked-off item stays visible before disappearing from list cards and the
|
||||
dashboard.
|
||||
How long checked-off items remain visible on list cards and the dashboard.
|
||||
</p>
|
||||
</div>
|
||||
<select
|
||||
value={delay}
|
||||
onChange={(e) => setDelay(Number(e.target.value))}
|
||||
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"
|
||||
defaultValue={initialHours}
|
||||
onChange={handleChange}
|
||||
disabled={isPending}
|
||||
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 disabled:opacity-50"
|
||||
>
|
||||
{DELAY_OPTIONS.map((opt) => (
|
||||
{OPTIONS.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
"use client";
|
||||
|
||||
import "react-grid-layout/css/styles.css";
|
||||
import "react-resizable/css/styles.css";
|
||||
|
||||
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 type { SerializedWidgetMeta } from "@/modules/_core/registry";
|
||||
import { saveDashboardLayout, resetDashboardLayout } from "@/app/d/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { WidgetPicker } from "./widget-picker";
|
||||
|
||||
function placementKey(placement: WidgetPlacement, index: number) {
|
||||
return `${placement.widgetId}::${index}`;
|
||||
}
|
||||
|
||||
export function DashboardEditor({
|
||||
dashboard,
|
||||
layout: initialLayout,
|
||||
widgetMetas,
|
||||
}: {
|
||||
dashboard: { id: string; name: string; slug: string };
|
||||
layout: DashboardLayout;
|
||||
widgetMetas: SerializedWidgetMeta[];
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [placements, setPlacements] = useState<WidgetPlacement[]>(initialLayout.widgets);
|
||||
const [isDirty, setIsDirty] = useState(false);
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [configuringIndex, setConfiguringIndex] = useState<number | null>(null);
|
||||
const [containerWidth, setContainerWidth] = useState(1200);
|
||||
|
||||
useEffect(() => {
|
||||
function measure() {
|
||||
const el = document.getElementById("dashboard-editor-grid");
|
||||
if (el) setContainerWidth(el.offsetWidth);
|
||||
}
|
||||
measure();
|
||||
window.addEventListener("resize", measure);
|
||||
return () => window.removeEventListener("resize", measure);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
function onKey(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") handleCancel();
|
||||
}
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [dashboard.slug]);
|
||||
|
||||
function handleCancel() {
|
||||
router.push(`/d/${dashboard.slug}`);
|
||||
}
|
||||
|
||||
function handleSave() {
|
||||
startTransition(async () => {
|
||||
await saveDashboardLayout(dashboard.id, { version: 1, widgets: placements });
|
||||
router.push(`/d/${dashboard.slug}`);
|
||||
});
|
||||
}
|
||||
|
||||
function handleReset() {
|
||||
startTransition(async () => {
|
||||
await resetDashboardLayout(dashboard.id);
|
||||
router.push(`/d/${dashboard.slug}`);
|
||||
});
|
||||
}
|
||||
|
||||
function handleLayoutChange(items: Layout) {
|
||||
setPlacements((current) =>
|
||||
current.map((p, i) => {
|
||||
const key = placementKey(p, i);
|
||||
const item = items.find((it) => it.i === key);
|
||||
if (!item) return p;
|
||||
return { ...p, x: item.x, y: item.y, w: item.w, h: item.h };
|
||||
}),
|
||||
);
|
||||
setIsDirty(true);
|
||||
}
|
||||
|
||||
function removeWidget(index: number) {
|
||||
setPlacements((current) => current.filter((_, i) => i !== index));
|
||||
setIsDirty(true);
|
||||
}
|
||||
|
||||
function addWidget(widgetId: string, config: unknown) {
|
||||
const meta = widgetMetas.find((m) => m.id === widgetId);
|
||||
if (!meta) return;
|
||||
const maxY = placements.reduce((m, p) => Math.max(m, p.y + p.h), 0);
|
||||
setPlacements((current) => [
|
||||
...current,
|
||||
{ widgetId, config, x: 0, y: maxY, w: meta.defaultSize.w, h: meta.defaultSize.h },
|
||||
]);
|
||||
setIsDirty(true);
|
||||
setPickerOpen(false);
|
||||
}
|
||||
|
||||
function updateConfig(index: number, config: unknown) {
|
||||
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,
|
||||
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,
|
||||
}));
|
||||
|
||||
return (
|
||||
<div className="p-4 sm:p-6">
|
||||
<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">
|
||||
<Button variant="outline" size="sm" onClick={handleReset} disabled={isPending}>
|
||||
<RotateCcw className="size-4 mr-1" />
|
||||
Reset
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={() => setPickerOpen(true)} disabled={isPending}>
|
||||
<Plus className="size-4 mr-1" />
|
||||
Add widget
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={handleCancel} disabled={isPending}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button size="sm" onClick={handleSave} disabled={!isDirty || isPending}>
|
||||
{isPending ? "Saving…" : "Save"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mb-4 text-sm text-muted-foreground">
|
||||
Drag to reorder · resize from the bottom-right corner · ESC to cancel
|
||||
</p>
|
||||
|
||||
<div id="dashboard-editor-grid">
|
||||
<GridLayout
|
||||
layout={gridItems}
|
||||
width={containerWidth}
|
||||
gridConfig={{ cols: 12, rowHeight: 60, margin: [16, 16] as [number, number], containerPadding: [0, 0] as [number, number] }}
|
||||
dragConfig={{ handle: ".drag-handle" }}
|
||||
onLayoutChange={handleLayoutChange}
|
||||
>
|
||||
{placements.map((placement, i) => {
|
||||
const meta = widgetMetas.find((m) => m.id === placement.widgetId);
|
||||
return (
|
||||
<div
|
||||
key={placementKey(placement, i)}
|
||||
className="rounded-lg border bg-card text-card-foreground flex flex-col overflow-hidden"
|
||||
>
|
||||
<div className="drag-handle flex items-center gap-2 px-3 py-2 bg-muted/40 cursor-grab active:cursor-grabbing select-none border-b">
|
||||
<GripVertical className="size-4 text-muted-foreground shrink-0" />
|
||||
<span className="text-sm font-medium truncate flex-1">
|
||||
{meta?.title ?? placement.widgetId}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setConfiguringIndex(i)}
|
||||
className="text-muted-foreground hover:text-foreground transition-colors p-0.5"
|
||||
aria-label="Configure widget"
|
||||
>
|
||||
<Settings2 className="size-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeWidget(i)}
|
||||
className="text-muted-foreground hover:text-destructive transition-colors p-0.5"
|
||||
aria-label="Remove widget"
|
||||
>
|
||||
<Trash2 className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 flex items-center justify-center p-4">
|
||||
<p className="text-xs text-muted-foreground">{meta?.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</GridLayout>
|
||||
</div>
|
||||
|
||||
{placements.length === 0 && (
|
||||
<div className="flex flex-col items-center justify-center py-24 gap-4 text-center">
|
||||
<p className="text-muted-foreground">No widgets yet.</p>
|
||||
<Button onClick={() => setPickerOpen(true)}>
|
||||
<Plus className="size-4 mr-1" />
|
||||
Add widget
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{pickerOpen && (
|
||||
<WidgetPicker
|
||||
onClose={() => setPickerOpen(false)}
|
||||
widgetMetas={widgetMetas}
|
||||
onAdd={addWidget}
|
||||
/>
|
||||
)}
|
||||
|
||||
{configuringIndex !== null && (
|
||||
<WidgetPicker
|
||||
onClose={() => setConfiguringIndex(null)}
|
||||
widgetMetas={widgetMetas}
|
||||
onAdd={(_, config) => updateConfig(configuringIndex, config)}
|
||||
initialWidgetId={placements[configuringIndex]?.widgetId}
|
||||
initialConfig={placements[configuringIndex]?.config}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
"use client";
|
||||
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useState, useTransition } from "react";
|
||||
import { MoreHorizontal, Plus, Star, Trash2, PenLine } from "lucide-react";
|
||||
import {
|
||||
createDashboard,
|
||||
deleteDashboard,
|
||||
renameDashboard,
|
||||
setDefaultDashboard,
|
||||
} from "@/app/d/actions";
|
||||
import type { DashboardMeta } from "@/app/d/actions";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
export function DashboardSwitcher({ dashboards }: { dashboards: DashboardMeta[] }) {
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const [, startTransition] = useTransition();
|
||||
const [creatingNew, setCreatingNew] = useState(false);
|
||||
const [newName, setNewName] = useState("");
|
||||
|
||||
function activeSlug() {
|
||||
const m = pathname.match(/^\/d\/([^/]+)/);
|
||||
return m?.[1] ?? null;
|
||||
}
|
||||
|
||||
function handleCreate() {
|
||||
if (!newName.trim()) return;
|
||||
startTransition(async () => {
|
||||
const created = await createDashboard(newName.trim());
|
||||
setCreatingNew(false);
|
||||
setNewName("");
|
||||
router.push(`/d/${created.slug}`);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1">
|
||||
{/* Active tab highlights — overlay on top of the server-rendered links */}
|
||||
{dashboards.map((d) => {
|
||||
const isActive = activeSlug() === d.slug;
|
||||
return (
|
||||
<span
|
||||
key={d.id}
|
||||
aria-hidden
|
||||
className={`absolute pointer-events-none border-b-2 transition-colors ${
|
||||
isActive ? "border-primary" : "border-transparent"
|
||||
}`}
|
||||
style={{ display: "none" }}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{creatingNew ? (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleCreate();
|
||||
}}
|
||||
className="flex items-center gap-1 ml-1"
|
||||
>
|
||||
<input
|
||||
autoFocus
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
placeholder="Dashboard name"
|
||||
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">
|
||||
Add
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCreatingNew(false)}
|
||||
className="text-xs text-muted-foreground hover:text-foreground px-1"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCreatingNew(true)}
|
||||
className="shrink-0 flex items-center gap-1 px-2 py-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
|
||||
aria-label="New dashboard"
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{dashboards.map((d) => {
|
||||
const isActive = activeSlug() === d.slug;
|
||||
if (!isActive) return null;
|
||||
return (
|
||||
<DashboardKebab
|
||||
key={d.id}
|
||||
dashboard={d}
|
||||
canDelete={dashboards.length > 1}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DashboardKebab({
|
||||
dashboard,
|
||||
canDelete,
|
||||
}: {
|
||||
dashboard: DashboardMeta;
|
||||
canDelete: boolean;
|
||||
}) {
|
||||
const [, startTransition] = useTransition();
|
||||
const [renaming, setRenaming] = useState(false);
|
||||
const [newName, setNewName] = useState(dashboard.name);
|
||||
|
||||
function handleRename() {
|
||||
if (!newName.trim() || newName === dashboard.name) {
|
||||
setRenaming(false);
|
||||
return;
|
||||
}
|
||||
startTransition(async () => {
|
||||
await renameDashboard(dashboard.id, newName.trim());
|
||||
setRenaming(false);
|
||||
});
|
||||
}
|
||||
|
||||
if (renaming) {
|
||||
return (
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handleRename();
|
||||
}}
|
||||
className="flex items-center gap-1 ml-1"
|
||||
>
|
||||
<input
|
||||
autoFocus
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
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" && setRenaming(false)}
|
||||
/>
|
||||
<button type="submit" className="text-xs text-muted-foreground hover:text-foreground px-1">
|
||||
Save
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRenaming(false)}
|
||||
className="text-xs text-muted-foreground hover:text-foreground px-1"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
className="shrink-0 flex items-center px-1 py-2 text-muted-foreground hover:text-foreground transition-colors"
|
||||
aria-label="Dashboard options"
|
||||
>
|
||||
<MoreHorizontal className="size-4" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onSelect={() => setRenaming(true)}>
|
||||
<PenLine className="size-4 mr-2" />
|
||||
Rename
|
||||
</DropdownMenuItem>
|
||||
{!dashboard.isDefault && (
|
||||
<DropdownMenuItem
|
||||
onSelect={() =>
|
||||
startTransition(() => setDefaultDashboard(dashboard.id))
|
||||
}
|
||||
>
|
||||
<Star className="size-4 mr-2" />
|
||||
Set as default
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canDelete && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onSelect={() => startTransition(() => deleteDashboard(dashboard.id))}
|
||||
>
|
||||
<Trash2 className="size-4 mr-2" />
|
||||
Delete
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
|
||||
export function DashboardTab({ slug, name }: { slug: string; name: string }) {
|
||||
const pathname = usePathname();
|
||||
const isActive = pathname === `/d/${slug}` || pathname.startsWith(`/d/${slug}/`);
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={`/d/${slug}`}
|
||||
className={`shrink-0 px-3 py-2 text-sm transition-colors border-b-2 ${
|
||||
isActive
|
||||
? "border-primary text-foreground"
|
||||
: "border-transparent text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
{name}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
|
||||
export function EditDashboardButton() {
|
||||
const router = useRouter();
|
||||
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"
|
||||
>
|
||||
Edit dashboard
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
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 { Input } from "@/components/ui/input";
|
||||
import { createShareLink } from "@/modules/_core/share";
|
||||
|
||||
export function ShareButton({
|
||||
entityType,
|
||||
entityId,
|
||||
canWrite = false,
|
||||
}: {
|
||||
entityType: string;
|
||||
entityId: string;
|
||||
canWrite?: boolean;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [shareUrl, setShareUrl] = useState<string | null>(null);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
function share() {
|
||||
startTransition(async () => {
|
||||
const result = await createShareLink(entityType, entityId, {
|
||||
capabilities: { read: true, write: canWrite },
|
||||
});
|
||||
setShareUrl(result.url);
|
||||
setOpen(true);
|
||||
});
|
||||
}
|
||||
|
||||
function copyUrl() {
|
||||
if (!shareUrl) return;
|
||||
navigator.clipboard.writeText(shareUrl).then(() => {
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant="outline" onClick={share} disabled={isPending}>
|
||||
<Link />
|
||||
Share
|
||||
</Button>
|
||||
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Share link created</DialogTitle>
|
||||
</DialogHeader>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Anyone with this link can {canWrite ? "view and edit" : "view"} this{" "}
|
||||
{entityType.split(".")[1]}.
|
||||
</p>
|
||||
<div className="flex gap-2">
|
||||
<Input readOnly value={shareUrl ?? ""} className="font-mono text-xs" />
|
||||
<Button variant="outline" size="icon" onClick={copyUrl} aria-label="Copy link">
|
||||
{copied ? <Check className="text-green-600" /> : <Copy />}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
"use client"
|
||||
|
||||
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"
|
||||
|
||||
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
|
||||
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({ ...props }: MenuPrimitive.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} />
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
align = "start",
|
||||
alignOffset = 0,
|
||||
side = "bottom",
|
||||
sideOffset = 4,
|
||||
className,
|
||||
...props
|
||||
}: MenuPrimitive.Popup.Props &
|
||||
Pick<
|
||||
MenuPrimitive.Positioner.Props,
|
||||
"align" | "alignOffset" | "side" | "sideOffset"
|
||||
>) {
|
||||
return (
|
||||
<MenuPrimitive.Portal>
|
||||
<MenuPrimitive.Positioner
|
||||
className="isolate z-50 outline-none"
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
>
|
||||
<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 )}
|
||||
{...props}
|
||||
/>
|
||||
</MenuPrimitive.Positioner>
|
||||
</MenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
|
||||
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: MenuPrimitive.GroupLabel.Props & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.GroupLabel
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: MenuPrimitive.Item.Props & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
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
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
|
||||
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: MenuPrimitive.SubmenuTrigger.Props & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.SubmenuTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
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
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</MenuPrimitive.SubmenuTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
align = "start",
|
||||
alignOffset = -3,
|
||||
side = "right",
|
||||
sideOffset = 0,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuContent>) {
|
||||
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 )}
|
||||
align={align}
|
||||
alignOffset={alignOffset}
|
||||
side={side}
|
||||
sideOffset={sideOffset}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
inset,
|
||||
...props
|
||||
}: MenuPrimitive.CheckboxItem.Props & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
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
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
className="pointer-events-none absolute right-2 flex items-center justify-center"
|
||||
data-slot="dropdown-menu-checkbox-item-indicator"
|
||||
>
|
||||
<MenuPrimitive.CheckboxItemIndicator>
|
||||
<CheckIcon
|
||||
/>
|
||||
</MenuPrimitive.CheckboxItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
|
||||
return (
|
||||
<MenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
inset,
|
||||
...props
|
||||
}: MenuPrimitive.RadioItem.Props & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<MenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
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
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span
|
||||
className="pointer-events-none absolute right-2 flex items-center justify-center"
|
||||
data-slot="dropdown-menu-radio-item-indicator"
|
||||
>
|
||||
<MenuPrimitive.RadioItemIndicator>
|
||||
<CheckIcon
|
||||
/>
|
||||
</MenuPrimitive.RadioItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</MenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
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">) {
|
||||
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
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { X, ChevronLeft } from "lucide-react";
|
||||
import type { SerializedWidgetMeta } from "@/modules/_core/registry";
|
||||
import { resolveWidgetConfigOptions } from "@/app/d/actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
type Step = "pick" | "configure";
|
||||
|
||||
export function WidgetPicker({
|
||||
onClose,
|
||||
widgetMetas,
|
||||
onAdd,
|
||||
initialWidgetId,
|
||||
initialConfig,
|
||||
}: {
|
||||
onClose: () => void;
|
||||
widgetMetas: SerializedWidgetMeta[];
|
||||
onAdd: (widgetId: string, config: unknown) => void;
|
||||
initialWidgetId?: string;
|
||||
initialConfig?: unknown;
|
||||
}) {
|
||||
const [step, setStep] = useState<Step>(initialWidgetId ? "configure" : "pick");
|
||||
const [selectedId, setSelectedId] = useState<string | null>(initialWidgetId ?? null);
|
||||
const [options, setOptions] = useState<unknown>(null);
|
||||
const [config, setConfig] = useState<unknown>(initialConfig ?? null);
|
||||
const [, startTransition] = useTransition();
|
||||
|
||||
function selectWidget(id: string) {
|
||||
const meta = widgetMetas.find((m) => m.id === id);
|
||||
if (!meta) return;
|
||||
setSelectedId(id);
|
||||
setConfig(meta.defaultConfig);
|
||||
setOptions(null);
|
||||
setStep("configure");
|
||||
startTransition(async () => {
|
||||
const opts = await resolveWidgetConfigOptions(id);
|
||||
setOptions(opts);
|
||||
});
|
||||
}
|
||||
|
||||
function handleAdd() {
|
||||
if (!selectedId) return;
|
||||
onAdd(selectedId, config);
|
||||
}
|
||||
|
||||
const grouped = widgetMetas.reduce<Record<string, SerializedWidgetMeta[]>>((acc, m) => {
|
||||
const cat = m.category ?? "Other";
|
||||
(acc[cat] ??= []).push(m);
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
const selected = widgetMetas.find((m) => m.id === selectedId);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
|
||||
onClick={(e) => e.target === e.currentTarget && onClose()}
|
||||
>
|
||||
<div className="relative bg-background rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[80vh] flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex items-center gap-2 px-4 py-3 border-b">
|
||||
{step === "configure" && !initialWidgetId && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setStep("pick")}
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ChevronLeft className="size-5" />
|
||||
</button>
|
||||
)}
|
||||
<h2 className="font-semibold flex-1 text-sm">
|
||||
{step === "pick" ? "Add widget" : selected ? `Configure: ${selected.title}` : "Configure"}
|
||||
</h2>
|
||||
<button type="button" onClick={onClose} className="text-muted-foreground hover:text-foreground">
|
||||
<X className="size-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<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]) => (
|
||||
<div key={cat}>
|
||||
<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
|
||||
key={meta.id}
|
||||
type="button"
|
||||
onClick={() => selectWidget(meta.id)}
|
||||
className="w-full text-left rounded-md px-3 py-2 hover:bg-accent transition-colors"
|
||||
>
|
||||
<p className="text-sm font-medium">{meta.title}</p>
|
||||
<p className="text-xs text-muted-foreground">{meta.description}</p>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "configure" && selected && (
|
||||
<WidgetConfigurator
|
||||
meta={selected}
|
||||
config={config}
|
||||
options={options}
|
||||
onChange={setConfig}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 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 size="sm" onClick={handleAdd}>
|
||||
{initialWidgetId ? "Apply" : "Add widget"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Configurator ──────────────────────────────────────────────────────────────
|
||||
|
||||
type FieldOption = { id: string; name: string };
|
||||
|
||||
function WidgetConfigurator({
|
||||
meta,
|
||||
config,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
meta: SerializedWidgetMeta;
|
||||
config: unknown;
|
||||
options: unknown;
|
||||
onChange: (c: unknown) => void;
|
||||
}) {
|
||||
const cfg = (config ?? meta.defaultConfig) as Record<string, unknown>;
|
||||
const opts = options as Record<string, FieldOption[]> | null | undefined;
|
||||
|
||||
function set(key: string, value: unknown) {
|
||||
onChange({ ...cfg, [key]: value });
|
||||
}
|
||||
|
||||
const entries = Object.entries(cfg);
|
||||
if (entries.length === 0) {
|
||||
return <p className="text-sm text-muted-foreground">No options available.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<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")))) {
|
||||
const optKey = key.replace(/Ids?$/i, "s");
|
||||
const items: FieldOption[] = (opts?.[optKey] as FieldOption[] | undefined) ?? [];
|
||||
const isAll = value === "all";
|
||||
const selected = isAll ? [] : (value as string[]);
|
||||
|
||||
return (
|
||||
<div key={key}>
|
||||
<label className="block text-sm font-medium mb-1 capitalize">
|
||||
{key.replace(/([A-Z])/g, " $1").toLowerCase()}
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm mb-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isAll}
|
||||
onChange={(e) => set(key, e.target.checked ? "all" : [])}
|
||||
className="accent-primary"
|
||||
/>
|
||||
All
|
||||
</label>
|
||||
{!isAll && (
|
||||
<div className="space-y-1 max-h-40 overflow-y-auto border rounded p-2">
|
||||
{items.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground">None available</p>
|
||||
)}
|
||||
{items.map((item) => (
|
||||
<label key={item.id} className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(item.id)}
|
||||
onChange={(e) => {
|
||||
const next = e.target.checked
|
||||
? [...selected, item.id]
|
||||
: selected.filter((id) => id !== item.id);
|
||||
set(key, next);
|
||||
}}
|
||||
className="accent-primary"
|
||||
/>
|
||||
{item.name}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// boolean
|
||||
if (typeof value === "boolean") {
|
||||
return (
|
||||
<label key={key} className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={value}
|
||||
onChange={(e) => set(key, e.target.checked)}
|
||||
className="accent-primary"
|
||||
/>
|
||||
<span className="capitalize">{key.replace(/([A-Z])/g, " $1").toLowerCase()}</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
// number
|
||||
if (typeof value === "number") {
|
||||
return (
|
||||
<div key={key}>
|
||||
<label className="block text-sm font-medium mb-1 capitalize">
|
||||
{key.replace(/([A-Z])/g, " $1").toLowerCase()}
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
value={value}
|
||||
onChange={(e) => set(key, Number(e.target.value))}
|
||||
className="w-24 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"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// string (enum / plain)
|
||||
if (typeof value === "string") {
|
||||
// Detect enum-like: same key appears in options as an array of strings
|
||||
const enumOpts = opts?.[key] as string[] | undefined;
|
||||
if (Array.isArray(enumOpts)) {
|
||||
return (
|
||||
<div key={key}>
|
||||
<label className="block text-sm font-medium mb-1 capitalize">
|
||||
{key.replace(/([A-Z])/g, " $1").toLowerCase()}
|
||||
</label>
|
||||
<select
|
||||
value={value}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
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>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Hardcoded enum fallback for known fields
|
||||
const knownEnums: Record<string, string[]> = {
|
||||
filter: ["pinned", "all"],
|
||||
};
|
||||
const known = knownEnums[key];
|
||||
if (known) {
|
||||
return (
|
||||
<div key={key}>
|
||||
<label className="block text-sm font-medium mb-1 capitalize">
|
||||
{key.replace(/([A-Z])/g, " $1").toLowerCase()}
|
||||
</label>
|
||||
<select
|
||||
value={value}
|
||||
onChange={(e) => set(key, e.target.value)}
|
||||
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>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
const STORAGE_KEY = "completion-delay-ms";
|
||||
export const DEFAULT_DELAY_MS = 3000;
|
||||
|
||||
export const DELAY_OPTIONS = [
|
||||
{ label: "1 second", value: 1000 },
|
||||
{ label: "3 seconds", value: 3000 },
|
||||
{ label: "5 seconds", value: 5000 },
|
||||
{ label: "10 seconds", value: 10000 },
|
||||
{ label: "30 seconds", value: 30000 },
|
||||
];
|
||||
|
||||
function readDelay(): number {
|
||||
if (typeof window === "undefined") return DEFAULT_DELAY_MS;
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
const parsed = raw ? parseInt(raw, 10) : NaN;
|
||||
return Number.isFinite(parsed) ? parsed : DEFAULT_DELAY_MS;
|
||||
}
|
||||
|
||||
export function useCompletionDelay() {
|
||||
const [delay, setDelayState] = useState<number>(readDelay);
|
||||
|
||||
function setDelay(ms: number) {
|
||||
setDelayState(ms);
|
||||
localStorage.setItem(STORAGE_KEY, String(ms));
|
||||
}
|
||||
|
||||
return { delay, setDelay };
|
||||
}
|
||||
@@ -10,8 +10,8 @@ export type {
|
||||
SearchResult,
|
||||
ActivityLogEntry,
|
||||
} from "./module";
|
||||
export { registerModule, getRegistry, getEntityType, getWidget, getQuickAdds } from "./registry";
|
||||
export type { QuickAddItem, SerializedQuickAddItem } 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";
|
||||
export type { ShareLinkCapabilities, CreateShareLinkResult } from "./share";
|
||||
|
||||
@@ -42,6 +42,23 @@ export type SerializedQuickAddItem = {
|
||||
moduleName: string;
|
||||
};
|
||||
|
||||
export type SerializedWidgetMeta = {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
category?: string;
|
||||
defaultSize: { w: number; h: number };
|
||||
minSize?: { w: number; h: number };
|
||||
maxSize?: { w: number; h: number };
|
||||
defaultConfig: unknown;
|
||||
};
|
||||
|
||||
export function getWidgetMetas(): SerializedWidgetMeta[] {
|
||||
return [...widgets.values()].map(({ id, title, description, category, defaultSize, minSize, maxSize, defaultConfig }) => ({
|
||||
id, title, description, category, defaultSize, minSize, maxSize, defaultConfig,
|
||||
}));
|
||||
}
|
||||
|
||||
export function getQuickAdds(): SerializedQuickAddItem[] {
|
||||
return [...modules.values()].flatMap((manifest) =>
|
||||
(manifest.quickAdds ?? []).map(({ id, label, icon, url }) => ({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { AdapterAccountType } from "@auth/core/adapters";
|
||||
import {
|
||||
boolean,
|
||||
index,
|
||||
integer,
|
||||
jsonb,
|
||||
@@ -24,7 +25,7 @@ export const users = pgTable("users", {
|
||||
image: text("image"),
|
||||
theme: text("theme").notNull().default("default"),
|
||||
themeMode: text("theme_mode").notNull().default("system"),
|
||||
defaultDashboardLayout: jsonb("default_dashboard_layout"),
|
||||
completionVisibilityHours: integer("completion_visibility_hours").notNull().default(24),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
@@ -129,6 +130,24 @@ export const shareLinks = pgTable(
|
||||
],
|
||||
);
|
||||
|
||||
export const dashboards = pgTable(
|
||||
"dashboards",
|
||||
{
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
userId: uuid("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
slug: text("slug").notNull(),
|
||||
isDefault: boolean("is_default").notNull().default(false),
|
||||
position: integer("position").notNull().default(0),
|
||||
layout: jsonb("layout").notNull().default({ version: 1, widgets: [] }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(t) => [uniqueIndex("dashboards_user_slug_uq").on(t.userId, t.slug)],
|
||||
);
|
||||
|
||||
export const reminders = pgTable(
|
||||
"reminders",
|
||||
{
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRef, useState, useTransition } from "react";
|
||||
import { useCompletionDelay } from "@/hooks/use-completion-delay";
|
||||
import { useState, useTransition } from "react";
|
||||
import { toggleItem } from "../server/actions";
|
||||
|
||||
type WidgetItem = {
|
||||
@@ -16,31 +15,9 @@ type WidgetItem = {
|
||||
export function ListWidget({ initialItems }: { initialItems: WidgetItem[] }) {
|
||||
const [items, setItems] = useState<WidgetItem[]>(initialItems);
|
||||
const [, startTransition] = useTransition();
|
||||
const { delay } = useCompletionDelay();
|
||||
const timers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
|
||||
|
||||
function toggle(item: WidgetItem, done: boolean) {
|
||||
if (done) {
|
||||
setItems((current) =>
|
||||
current.map((i) => (i.id === item.id ? { ...i, done: true } : i)),
|
||||
);
|
||||
|
||||
const t = setTimeout(() => {
|
||||
setItems((current) => current.filter((i) => i.id !== item.id));
|
||||
timers.current.delete(item.id);
|
||||
}, delay);
|
||||
timers.current.set(item.id, t);
|
||||
} else {
|
||||
const existing = timers.current.get(item.id);
|
||||
if (existing) {
|
||||
clearTimeout(existing);
|
||||
timers.current.delete(item.id);
|
||||
}
|
||||
setItems((current) =>
|
||||
current.map((i) => (i.id === item.id ? { ...i, done: false } : i)),
|
||||
);
|
||||
}
|
||||
|
||||
setItems((current) => current.map((i) => (i.id === item.id ? { ...i, done } : i)));
|
||||
startTransition(async () => {
|
||||
await toggleItem({ id: item.id, done });
|
||||
});
|
||||
|
||||
@@ -2,11 +2,10 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { ChevronDown, ChevronRight, ExternalLink, Plus } from "lucide-react";
|
||||
import { useMemo, useRef, useState, useTransition } from "react";
|
||||
import { useMemo, useState, useTransition } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { useCompletionDelay } from "@/hooks/use-completion-delay";
|
||||
import type { ListIndexItem, ListWithItemsDto } from "../server/queries";
|
||||
import { createList, toggleItem } from "../server/actions";
|
||||
|
||||
@@ -15,8 +14,6 @@ export function ListsIndex({ lists }: { lists: ListWithItemsDto[] }) {
|
||||
const [type, setType] = useState("shopping");
|
||||
const [name, setName] = useState("");
|
||||
const [, startTransition] = useTransition();
|
||||
const { delay } = useCompletionDelay();
|
||||
const timers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());
|
||||
|
||||
const grouped = useMemo(() => {
|
||||
const groups = new Map<string, ListWithItemsDto[]>();
|
||||
@@ -47,55 +44,18 @@ export function ListsIndex({ lists }: { lists: ListWithItemsDto[] }) {
|
||||
}
|
||||
|
||||
function handleToggle(listId: string, item: ListIndexItem, done: boolean) {
|
||||
const timerId = `${listId}:${item.id}`;
|
||||
|
||||
if (done) {
|
||||
// Mark done immediately (strikethrough) and schedule removal
|
||||
setListRows((current) =>
|
||||
current.map((list) =>
|
||||
list.id !== listId
|
||||
? list
|
||||
: {
|
||||
...list,
|
||||
openCount: list.openCount - 1,
|
||||
doneCount: list.doneCount + 1,
|
||||
items: list.items.map((i) => (i.id === item.id ? { ...i, done: true } : i)),
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
const t = setTimeout(() => {
|
||||
setListRows((current) =>
|
||||
current.map((list) =>
|
||||
list.id !== listId
|
||||
? list
|
||||
: { ...list, items: list.items.filter((i) => i.id !== item.id) },
|
||||
),
|
||||
);
|
||||
timers.current.delete(timerId);
|
||||
}, delay);
|
||||
timers.current.set(timerId, t);
|
||||
} else {
|
||||
// Cancel pending removal and restore item
|
||||
const existing = timers.current.get(timerId);
|
||||
if (existing) {
|
||||
clearTimeout(existing);
|
||||
timers.current.delete(timerId);
|
||||
}
|
||||
setListRows((current) =>
|
||||
current.map((list) =>
|
||||
list.id !== listId
|
||||
? list
|
||||
: {
|
||||
...list,
|
||||
openCount: list.openCount + 1,
|
||||
doneCount: list.doneCount - 1,
|
||||
items: list.items.map((i) => (i.id === item.id ? { ...i, done: false } : i)),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
setListRows((current) =>
|
||||
current.map((list) =>
|
||||
list.id !== listId
|
||||
? list
|
||||
: {
|
||||
...list,
|
||||
openCount: list.openCount + (done ? -1 : 1),
|
||||
doneCount: list.doneCount + (done ? 1 : -1),
|
||||
items: list.items.map((i) => (i.id === item.id ? { ...i, done } : i)),
|
||||
},
|
||||
),
|
||||
);
|
||||
startTransition(async () => {
|
||||
await toggleItem({ id: item.id, done });
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use server";
|
||||
|
||||
import { and, asc, eq, inArray, or, sql } from "drizzle-orm";
|
||||
import { and, asc, eq, gt, inArray, or, sql } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db";
|
||||
import { getCurrentSession } from "@/lib/session";
|
||||
@@ -166,7 +166,7 @@ export type ListIndexItem = {
|
||||
export type ListWithItemsDto = ListDto & { items: ListIndexItem[] };
|
||||
|
||||
export async function listListsWithItems(): Promise<ListWithItemsDto[]> {
|
||||
const { household } = await getCurrentSession();
|
||||
const { user, household } = await getCurrentSession();
|
||||
await ensureDefaultListsForHousehold(household.id);
|
||||
|
||||
const listsRows = await db
|
||||
@@ -178,8 +178,8 @@ export async function listListsWithItems(): Promise<ListWithItemsDto[]> {
|
||||
if (listsRows.length === 0) return [];
|
||||
|
||||
const listIds = listsRows.map((l) => l.id);
|
||||
const cutoff = completionCutoff(user.completionVisibilityHours);
|
||||
|
||||
// Fetch all open items for these lists, ordered so we can take top 10 per list in JS
|
||||
const itemRows = await db
|
||||
.select({
|
||||
id: listItems.id,
|
||||
@@ -190,8 +190,13 @@ export async function listListsWithItems(): Promise<ListWithItemsDto[]> {
|
||||
createdAt: listItems.createdAt,
|
||||
})
|
||||
.from(listItems)
|
||||
.where(and(inArray(listItems.listId, listIds), eq(listItems.done, false)))
|
||||
.orderBy(asc(listItems.position), asc(listItems.createdAt));
|
||||
.where(
|
||||
and(
|
||||
inArray(listItems.listId, listIds),
|
||||
or(eq(listItems.done, false), and(eq(listItems.done, true), gt(listItems.updatedAt, cutoff))),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(listItems.done), asc(listItems.position), asc(listItems.createdAt));
|
||||
|
||||
const itemsByList = new Map<string, ListIndexItem[]>();
|
||||
for (const item of itemRows) {
|
||||
@@ -254,8 +259,12 @@ export async function listWidgetItems(input: {
|
||||
|
||||
if (visibleIds.length === 0) return [];
|
||||
|
||||
const conditions = [inArray(listItems.listId, visibleIds)];
|
||||
if (!parsed.showCompleted) conditions.push(eq(listItems.done, false));
|
||||
const { user } = await getCurrentSession();
|
||||
const cutoff = completionCutoff(user.completionVisibilityHours);
|
||||
|
||||
const doneFilter = parsed.showCompleted
|
||||
? undefined
|
||||
: or(eq(listItems.done, false), and(eq(listItems.done, true), gt(listItems.updatedAt, cutoff)));
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
@@ -267,7 +276,7 @@ export async function listWidgetItems(input: {
|
||||
})
|
||||
.from(listItems)
|
||||
.innerJoin(lists, eq(listItems.listId, lists.id))
|
||||
.where(and(...conditions))
|
||||
.where(and(inArray(listItems.listId, visibleIds), doneFilter))
|
||||
.orderBy(asc(listItems.done), asc(listItems.position), asc(listItems.createdAt))
|
||||
.limit(parsed.limit ?? 10);
|
||||
|
||||
@@ -318,6 +327,10 @@ function toListDto(list: typeof lists.$inferSelect, items: ListItemDto[]): ListD
|
||||
};
|
||||
}
|
||||
|
||||
function completionCutoff(hours: number): Date {
|
||||
return new Date(Date.now() - hours * 60 * 60 * 1000);
|
||||
}
|
||||
|
||||
function toItemDto(item: typeof listItems.$inferSelect): ListItemDto {
|
||||
return {
|
||||
id: item.id,
|
||||
|
||||
Reference in New Issue
Block a user