initial commit on Federted servers
release gate / check (push) Failing after 8m35s

This commit is contained in:
Andrew S Erwin
2026-10-19 16:23:55 -05:00
commit b9721ff13f
217 changed files with 31534 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
node_modules
.next
.env*
.git
out
*.log
+21
View File
@@ -0,0 +1,21 @@
# Copy to .env for local (non-Docker) development of the web app only.
# The Docker stack is configured from the repository-root .env instead —
# see ../.env.example and ../RUNNING.md. The frontend has no database
# connection; all persistence goes through the Go API.
# Shared secret used to verify NextAuth sessions and sign the 60-second
# identity assertions for the Go API. Must equal the root AUTH_SECRET.
AUTH_SECRET="<SAME_RANDOM_SECRET_AS_ROOT_ENV>"
# Public URL the app is served on (used for auth callbacks).
NEXTAUTH_URL="http://localhost:3000"
# Go API base URL. Server-side only: inside Docker Compose this is the
# service DNS name http://app:8080. For local `next dev` use the host URL.
API_BASE_URL="http://localhost:8080"
# Authelia OIDC: stubbed until the client integration is complete
# (see docs/AUTHELIA.md). Setting values enables the config display only.
OIDC_ISSUER=
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
+22
View File
@@ -0,0 +1,22 @@
# Pinned patch level for reproducible builds.
FROM node:22.23.3-alpine3.24 AS deps
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile --ignore-scripts
FROM node:22.23.3-alpine3.24 AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1
RUN yarn build
FROM node:22.23.3-alpine3.24 AS runtime
WORKDIR /app
ENV NODE_ENV=production NEXT_TELEMETRY_DISABLED=1 PORT=3000 HOSTNAME=0.0.0.0
COPY --from=build --chown=node:node /app/.next/standalone ./
COPY --from=build --chown=node:node /app/.next/static ./.next/static
COPY --from=build --chown=node:node /app/public ./public
USER node
EXPOSE 3000
CMD ["node", "server.js"]
+106
View File
@@ -0,0 +1,106 @@
# computer — web UI
This app runs inside the root Compose stack. The root [../README.md](../README.md)
is the single authoritative deployment/operations guide; [../API.md](../API.md)
documents the Go API contract. This file covers only what a frontend
developer needs.
Ownership boundary: the Go API owns persistence, previews, integrations and
authentication semantics; this Next.js server owns browser sessions
(NextAuth), the trusted API bridge (`lib/api.ts` signs short-lived
assertions — the browser never supplies a trusted identity), and rendering.
Data requests go through `app/api/[...path]/route.ts`, not local Prisma
routes; the pre-port Prisma layer is gone. Schema and seeding live in the Go
stack (`../db/schema.sql`, `../db/migrations/`, `make seed`).
## Requirements
- Node.js 20.9 or newer
- Yarn (Corepack: `corepack enable`)
- A running Go API (`API_BASE_URL` — server-only Docker DNS, e.g.
`http://app:8080`); the browser uses relative `/api/*` URLs
## Setup
```bash
cp .env.example .env # fill in AUTH_SECRET, NEXTAUTH_URL, API_BASE_URL
yarn install
```
## Run
```bash
yarn dev # development: http://localhost:3000
yarn build && yarn start # production
```
Production deployments run behind the Compose stack and the nginx template
in `../deploy/nginx/`. The Content-Security-Policy is emitted per response
by `middleware.ts` (nonce-based, so Next's inline bootstrap scripts run);
do not add a second `script-src` policy at the proxy — browsers intersect
multiple CSPs and the nonce would be stripped.
## Authentication
- **Email and password** work out of the box. Sign up at `/signup`. Signup
responses are uniform (`{ok:true}`) for fresh, duplicate and reserved
addresses — account existence is never disclosed.
- **Authelia OIDC is fail-closed.** Setting `OIDC_ISSUER`,
`OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET` only makes the provider appear
in configuration; the Go login/callback endpoints deliberately answer
**501** until verified external identities are mapped to local users with
explicit account-linking rules, and `auth.ts` rejects Authelia sign-ins
until then. Configured variables are NOT working sign-in. See
[docs/AUTHELIA.md](docs/AUTHELIA.md) and the root `AGENTS.md` boundary.
- Sign-out means **sign out everywhere**: the UI first calls
`/api/session/revoke` (Go tokenVersion bump) and reports honestly when
global revocation fails; the NextAuth `signOut` event is the backstop.
Don't remove either path.
## Encryption and key retention (operator-relevant)
IMAP mailbox passwords are encrypted with AES-256-GCM. The key derives from
the dedicated `ENCRYPTION_KEY` when set, otherwise from the auth secret
(`NEXTAUTH_SECRET`/`AUTH_SECRET`). Rows encrypted before `ENCRYPTION_KEY`
existed decrypt via the auth-secret fallback and re-encrypt transparently
(compare-and-swap — a concurrent password change always wins). Consequences:
- Back up `ENCRYPTION_KEY`/`AUTH_SECRET` **with** the database; without the
matching keys, stored mailbox credentials are unrecoverable.
- Rotating an already-dedicated `ENCRYPTION_KEY` needs old-key-aware
migration, not just a changed environment variable. Keep the old secret
until every credential row has been re-encrypted and verified.
## Project layout
| Path | Contents |
|---|---|
| `app/(app)/` | Signed-in screens: pages (primary workspace), bookmark filters (all, calendar, tags, contacts, kanban), collections, settings; `/dashboard` redirects to `/bookmarks` |
| `app/api/` | Next routes only: the Go proxy (`[...path]`), NextAuth (`auth/*`), session revoke; everything else is Go's |
| `app/share/bookmark/[id]` | Public read-only bookmark page |
| `components/` | UI components |
| `lib/` | Server-side API bridge (`api.ts`), OIDC config, autosave/pagination helpers |
| `middleware.ts` | Per-response nonce CSP (review CR-10) |
| `auth.ts` | Auth.js configuration |
| `docs/` | Integration docs |
## Notes
- URL previews are fetched **server-side by the Go API**
(`internal/preview`, guarded by `internal/netguard` and a shared
per-user/global budget) when a bookmark is saved or its URL changes —
not by this app and not by `open-graph-scraper`.
- Date alerts are polled by the browser every 5 minutes and shown as
browser notifications; email signal ingestion is Go-side (IMAP).
## Admins
Administrator provisioning is operator-driven: list addresses in
`ADMIN_EMAILS` and run `make seed` (it never changes existing accounts).
As a bootstrap convenience the FIRST signup on a fresh installation may be
promoted once (AppSetting `adminBootstrap`, disable with
`ALLOW_BOOTSTRAP_SIGNUP=0`); after bootstrap completes, signup never
auto-promotes again — even with no admins left. Promotion of an existing
allowlisted user requires `emailVerified`; DB roles remain authoritative.
Admins can open any account via Admin → "View as" (mutations are blocked
while impersonating).
+211
View File
@@ -0,0 +1,211 @@
## Layout
The root layout, `app/layout.tsx`, is the single place for app-wide providers and global infrastructure.
**Do not remove any existing entries without a reason.** Current infrastructure in the layout:
| Entry | Purpose |
|-------|---------|
| `ThemeProvider` | Light/dark mode via `next-themes` |
| `Toaster` | Global toast notifications via Sonner |
| `ChunkLoadErrorHandler` | Required — prevents known ChunkLoadError race condition bug |
---
## Typography
| Role | Font | Tailwind Class | Default Usage |
|------|------|---------------|-------|
| Body | DM Sans | `font-sans` | All body text, labels, descriptions |
| Display | Plus Jakarta Sans | `font-display` | Page titles, hero headings, section headers |
| Mono | JetBrains Mono | `font-mono` | Code snippets, numeric data, IDs, timestamps |
**Size hierarchy:** Use Tailwind's scale. Headings: `text-4xl`→`text-3xl`→`text-2xl`→`text-xl`. Body: `text-base`→`text-sm`. Captions: `text-xs`.
Always use `tracking-tight` on large headings (`text-2xl` and above).
---
## Color System (Design Tokens)
All colors use CSS variables — **never hardcode color values**.
| Token | Purpose |
|-------|---------|
| `background` / `foreground` | Page-level bg and text |
| `card` / `card-foreground` | Card surfaces |
| `primary` / `primary-foreground` | Brand buttons, links, accents |
| `secondary` / `secondary-foreground` | Secondary buttons, subtle highlights |
| `muted` / `muted-foreground` | Disabled states, helper text, subtle backgrounds |
| `accent` / `accent-foreground` | Hover states, active nav items |
| `destructive` / `destructive-foreground` | Errors, delete actions |
| `border` | Borders and dividers |
| `input` | Form input borders |
| `ring` | Focus rings |
Usage: `bg-primary`, `text-muted-foreground`, `border-border`, etc.
---
## Spacing Scale
Based on an 8px grid. Use these CSS variables or Tailwind equivalents:
| Token | Value | Tailwind |
|-------|-------|----------|
| `--spacing-xs` | 4px | `p-1`, `gap-1` |
| `--spacing-sm` | 8px | `p-2`, `gap-2` |
| `--spacing-md` | 16px | `p-4`, `gap-4` |
| `--spacing-lg` | 24px | `p-6`, `gap-6` |
| `--spacing-xl` | 32px | `p-8`, `gap-8` |
| `--spacing-2xl` | 48px | `p-12`, `gap-12` |
| `--spacing-3xl` | 64px | `p-16`, `gap-16` |
**Vary spacing rhythm** — don't use the same gap everywhere. Hero → large gap → content → medium gap → footer.
---
## Shadow Scale
| Token | Default Usage |
|-------|-------|
| `--shadow-sm` | Subtle card lift, input focus |
| `--shadow-md` | Cards, dropdowns, popovers |
| `--shadow-lg` | Modals, elevated panels |
These are CSS variables only — use them directly in inline styles or custom CSS as `var(--shadow-sm)` etc. They are not mapped to Tailwind's `shadow-*` utilities.
---
## Border Radius
| Token | Value | Default Usage |
|-------|-------|-------|
| `--radius` | 0.625rem | Default (buttons, inputs, cards) |
| `--radius-sm` | calc(var(--radius) - 4px) | Small elements (badges, chips) |
| `--radius-lg` | calc(var(--radius) + 4px) | Large containers, hero cards |
| `--radius-full` | 9999px | Avatars, pills, circular buttons |
---
## Animation Timing
| Token | Value | Tailwind Class | Default Usage |
|-------|-------|---------------|-------|
| `--duration-fast` | 150ms | `duration-fast` | Hover states, toggles |
| `--duration-normal` | 250ms | `duration-normal` | Page transitions, reveals |
| `--duration-slow` | 350ms | `duration-slow` | Complex animations, modals |
---
## Layout Components
The live app shell is `@/components/app-shell` (sidebar + top bar + main
content, wired through `app/(app)/layout.tsx`); screens render their own
headers inline. Login/signup use a centered card built directly in their
route files. The generic `components/layouts/*` wrappers documented here
previously were never imported and have been removed — reintroduce shared
layout primitives only when a second consumer exists.
---
## Animation Components — `@/components/ui/animate`
| Component | Default Usage | Key Props |
|-----------|-------|-----------|
| `FadeIn` | Reveal content on scroll | `delay`, `duration` |
| `ScaleIn` | Pop-in effect | `delay` |
| `SlideIn` | Directional entrance | `from` (`top`\|`bottom`\|`left`\|`right`), `delay` |
| `Stagger` + `StaggerItem` | Sequential reveal for lists/grids | `staggerDelay` |
| `HoverLift` | Lift effect on hover (cards, links) | — |
| `PressScale` | Press-down feedback for buttons | — |
| `SkeletonPulse` | Loading placeholder | `className` (set width/height) |
**Pattern:** Wrap page sections in `FadeIn`, list items in `Stagger`/`StaggerItem`, interactive cards in `HoverLift`.
---
## UI Components — `@/components/ui/`
### Core
| Component | Import | Key Props |
|-----------|--------|-----------|
| `Button` | `@/components/ui/button` | `variant` (`default`\|`secondary`\|`outline`\|`ghost`\|`destructive`\|`link`\|`glass-dark`\|`glass-light`), `size` (`default`\|`xs`\|`sm`\|`lg`\|`icon`\|`icon-sm`), `loading` (boolean). **`glass-dark`**: for dark/vivid backgrounds. **`glass-light`**: for light/pale backgrounds. **Link**: focus uses underline, not ring. |
| `Badge` | `@/components/ui/badge` | `variant` (`default`\|`secondary`\|`outline`\|`destructive`) |
| `Card` | `@/components/ui/card` | `variant` (`default`\|`interactive`\|`glass-dark`\|`glass-dark-interactive`\|`glass-light`\|`glass-light-interactive`\|`ghost`). Composed: `Card`, `CardHeader`, `CardTitle`, `CardDescription`, `CardContent`, `CardFooter`. **Interactive**: always wrap in `<a>` or `<button>` for keyboard access. |
| `Separator` | `@/components/ui/separator` | `orientation` (`horizontal`\|`vertical`) |
### Forms
| Component | Import |
|-----------|--------|
| `Input` | `@/components/ui/input` | `variant` (`default`\|`error`\|`success`\|`ghost`), `size` (`default`\|`sm`\|`lg`) |
| `Textarea` | `@/components/ui/textarea` | `variant` (`default`\|`error`\|`success`\|`ghost`) |
| `Label` | `@/components/ui/label` |
| `Select` | `@/components/ui/select` |
| `Checkbox` | `@/components/ui/checkbox` |
| `RadioGroup` | `@/components/ui/radio-group` |
| `Switch` | `@/components/ui/switch` |
| `Slider` | `@/components/ui/slider` |
| `Calendar` | `@/components/ui/calendar` |
| `DateRangePicker` | `@/components/ui/date-range-picker` |
| `InputOTP` | `@/components/ui/input-otp` |
| `Form` | `@/components/ui/form` (react-hook-form integration) |
### Navigation & Layout
| Component | Import |
|-----------|--------|
| `Tabs` | `@/components/ui/tabs` — `Tabs`, `TabsList`, `TabsTrigger`, `TabsContent` |
| `Accordion` | `@/components/ui/accordion` — `Accordion`, `AccordionItem`, `AccordionTrigger`, `AccordionContent` |
| `NavigationMenu` | `@/components/ui/navigation-menu` |
| `Breadcrumb` | `@/components/ui/breadcrumb` |
| `Pagination` | `@/components/ui/pagination` |
| `Menubar` | `@/components/ui/menubar` |
| `ScrollArea` | `@/components/ui/scroll-area` |
| `Resizable` | `@/components/ui/resizable` |
### Overlays & Feedback
| Component | Import |
|-----------|--------|
| `Dialog` | `@/components/ui/dialog` |
| `AlertDialog` | `@/components/ui/alert-dialog` |
| `Sheet` | `@/components/ui/sheet` — side-panel overlay |
| `Drawer` | `@/components/ui/drawer` — bottom sheet (great for mobile) |
| `Popover` | `@/components/ui/popover` |
| `Tooltip` | `@/components/ui/tooltip` |
| `HoverCard` | `@/components/ui/hover-card` |
| `ContextMenu` | `@/components/ui/context-menu` |
| `DropdownMenu` | `@/components/ui/dropdown-menu` |
| `Command` | `@/components/ui/command` — command palette / searchable list |
| `Alert` | `@/components/ui/alert` |
| `toast` | `import { toast } from 'sonner'` — `toast.success()`, `toast.error()` |
### Data Display
| Component | Import |
|-----------|--------|
| `Table` | `@/components/ui/table` — `Table`, `TableHeader`, `TableBody`, `TableRow`, `TableHead`, `TableCell` |
| `Avatar` | `@/components/ui/avatar` |
| `Progress` | `@/components/ui/progress` |
| `Skeleton` | `@/components/ui/skeleton` |
| `AspectRatio` | `@/components/ui/aspect-ratio` |
| `Carousel` | `@/components/ui/carousel` |
### Misc
| Component | Import |
|-----------|--------|
| `Toggle` | `@/components/ui/toggle` |
| `ToggleGroup` | `@/components/ui/toggle-group` |
| `Collapsible` | `@/components/ui/collapsible` |
| `ThemeToggle` | `@/components/theme-toggle` — light/dark mode switch |
## SSR / Hydration Safety — `@/components/client-only`, `@/components/safe-format`
Server-rendered HTML must match the client's first render. An automated SSR lint
(`eslint.ssr.config.mjs` — do not delete) runs after every build and fails it on unsafe
patterns. Use these primitives instead of hand-rolling fixes:
| Primitive | Import | Use for |
|-----------|--------|---------|
| `ClientOnly` | `@/components/client-only` | Anything browser-only or non-deterministic: `window`/`localStorage` reads, live clocks, random values, third-party widgets. Pass a `fallback` sized like the content. |
| `useMounted()` | `@/components/client-only` | Hook variant when you need the boolean directly. |
| `SafeDate` / `SafeTime` | `@/components/safe-format` | Dates/times — formats with explicit locale + UTC so SSR matches client. `localize` re-renders in the visitor's timezone after mount. Props: `date` (Date\|string\|number), `options?` (Intl.DateTimeFormatOptions), `locale?`, `localize?`, `className?` — there is no `format`/`value` prop; e.g. `<SafeDate date={post.createdAt} options={{ dateStyle: 'medium' }} />`. |
| `SafeNumber` | `@/components/safe-format` | Numbers/currency, same guarantees. Props: `value` (number), `options?` (Intl.NumberFormatOptions), `currency?` (`currency="USD"`), `locale?`, `localize?`, `className?`. |
Rules of thumb: never touch `window`/`document` at module scope; never seed `useState` with
`Date.now()`/`Math.random()`/`new Date()`; never call `toLocaleString`-style methods without
an explicit locale (and `timeZone` for dates).
+52
View File
@@ -0,0 +1,52 @@
'use client'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { Eye, Shield } from 'lucide-react'
import { Button } from '@/components/ui/button'
type U = { id: string; name: string | null; email: string; role: string; _count?: { bookmarks: number; pages: number; tags: number } }
export function AdminClient({ currentUserId }: { currentUserId: string }) {
const [users, setUsers] = useState<U[]>([])
const load = () =>
fetch('/api/admin/users')
.then((r) => (r.ok ? r.json() : []))
.then((d) => setUsers(Array.isArray(d) ? d : d?.users ?? []))
.catch((e) => console.error('Failed to load users', e))
useEffect(() => { load() }, [])
const viewAs = async (userId: string) => {
const res = await fetch('/api/admin/view-as', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId }) })
if (!res.ok) return toast.error('Could not switch account')
window.location.href = '/pages'
}
const toggleRole = async (u: U) => {
const res = await fetch('/api/admin/users', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId: u.id, role: u.role === 'ADMIN' ? 'USER' : 'ADMIN' }) })
if (!res.ok) return toast.error((await res.json().catch(() => null))?.error ?? 'Could not change role')
load()
}
return (
<div className="mx-auto max-w-4xl">
<h1 className="font-display text-2xl font-bold">Admin</h1>
<p className="mb-6 text-sm text-muted-foreground">All accounts in the group. “View as” opens an account with a visible banner; exit any time.</p>
<div className="divide-y divide-border/60 rounded-xl bg-card shadow-sm ring-1 ring-border/50">
{users.map((u) => (
<div key={u.id} className="flex flex-wrap items-center gap-3 p-4">
<div className="min-w-0 flex-1">
<p className="truncate font-medium">{u.name || u.email} {u.role === 'ADMIN' && <Shield className="ml-1 inline h-3.5 w-3.5 text-primary" />}</p>
<p className="truncate text-xs text-muted-foreground">{u.email} · {u._count?.bookmarks ?? 0} bookmarks · {u._count?.pages ?? 0} pages</p>
</div>
<Button size="sm" variant="outline" disabled={u.id === currentUserId} onClick={() => toggleRole(u)}>{u.role === 'ADMIN' ? 'Make user' : 'Make admin'}</Button>
<Button size="sm" disabled={u.id === currentUserId} onClick={() => viewAs(u.id)}><Eye className="mr-1 h-4 w-4" />View as</Button>
</div>
))}
{users.length === 0 && <p className="p-6 text-center text-sm text-muted-foreground">No users found.</p>}
</div>
</div>
)
}
+11
View File
@@ -0,0 +1,11 @@
export const dynamic = 'force-dynamic'
import { redirect } from 'next/navigation'
import { getRealUser } from '@/lib/auth-guard'
import { AdminClient } from './client'
export default async function AdminPage() {
const user = await getRealUser()
if (!user) redirect('/login')
if (user.role !== 'ADMIN') redirect('/pages')
return <AdminClient currentUserId={user.id} />
}
+192
View File
@@ -0,0 +1,192 @@
'use client'
import { useState, useEffect, useCallback, useRef } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
import { ExternalLink, Search, Trash2, ChevronUp, ChevronDown, Inbox, Share2 } from 'lucide-react'
import { toast } from 'sonner'
import type { Bookmark } from '@/components/app-shell'
import { fetchBookmarks } from '@/lib/bookmarks'
export function BookmarksClient({ initialSearch = null, initialOpen = null }: { initialSearch?: string | null; initialOpen?: string | null }) {
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
const [sharedBookmarks, setSharedBookmarks] = useState<Bookmark[]>([])
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState('')
const [selected, setSelected] = useState<Bookmark | null>(null)
// Review CR-04: the sheet must receive the CURRENT row after mutations —
// its conflict banner ("Load latest version") and successful saves need
// the fresh version, or the next save would send a stale base.
const selectedRef = useRef<Bookmark | null>(null)
selectedRef.current = selected
const refreshSelected = useCallback(async () => {
const id = selectedRef.current?.id
if (!id) return
try {
const res = await fetch(`/api/bookmarks/${encodeURIComponent(id)}`, { cache: 'no-store' })
if (res.ok) setSelected(await res.json())
} catch { /* the list load surfaces errors */ }
}, [])
const [tab, setTab] = useState<'mine' | 'shared'>('mine')
const [sortField, setSortField] = useState<'title' | 'updatedAt' | 'kanbanStatus'>('updatedAt')
const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc')
// Debounced, abortable, sequence-guarded load: a slow response for an older
// query can never overwrite newer results (same discipline as pages client).
const loadSeq = useRef(0)
const abortRef = useRef<AbortController | null>(null)
const load = useCallback(() => {
abortRef.current?.abort()
const ac = new AbortController()
abortRef.current = ac
const seq = ++loadSeq.current
setLoading(true)
const params = new URLSearchParams()
if (search) params.set('search', search)
;(async () => {
try {
const mine = await fetchBookmarks(params, ac.signal)
if (seq !== loadSeq.current) return
setBookmarks(mine ?? [])
} catch {
if (seq === loadSeq.current && !ac.signal.aborted) toast.error('Could not load bookmarks')
} finally {
if (seq === loadSeq.current) setLoading(false)
}
})()
}, [search])
// The shared list is not search-filtered; load it once and on changes only.
const loadShared = useCallback(async () => {
try { setSharedBookmarks(await fetchBookmarks(new URLSearchParams({ shared: 'true' })) ?? []) }
catch { /* the mine-tab load surfaces errors */ }
}, [])
useEffect(() => {
const timer = setTimeout(load, search ? 250 : 0)
const reload = () => { load(); void loadShared() }
window.addEventListener('computer:bookmarks-changed', reload)
return () => { clearTimeout(timer); window.removeEventListener('computer:bookmarks-changed', reload); abortRef.current?.abort() }
}, [load, loadShared, search])
useEffect(() => { const timer = setTimeout(loadShared, 0); return () => clearTimeout(timer) }, [loadShared])
// Quick Find and the dashboard redirect land here with ?search=; the prop
// comes from the server component so query changes apply without a remount.
useEffect(() => {
const timer = setTimeout(() => setSearch(initialSearch || ''), 0)
return () => clearTimeout(timer)
}, [initialSearch])
// Quick Find deep-links straight to a bookmark's detail sheet via ?open=<id>.
useEffect(() => {
if (!initialOpen) return
const timer = setTimeout(async () => {
try {
const res = await fetch(`/api/bookmarks/${encodeURIComponent(initialOpen)}`)
if (res.ok) setSelected(await res.json())
} catch { /* stale or inaccessible id; the list still renders */ }
}, 0)
return () => clearTimeout(timer)
}, [initialOpen])
const displayBookmarks = tab === 'mine' ? bookmarks : sharedBookmarks
const sorted = [...(displayBookmarks ?? [])].sort((a: any, b: any) => {
const va = a?.[sortField] ?? ''
const vb = b?.[sortField] ?? ''
return sortDir === 'asc' ? String(va).localeCompare(String(vb)) : String(vb).localeCompare(String(va))
})
const toggleSort = (field: typeof sortField) => {
if (sortField === field) setSortDir(d => d === 'asc' ? 'desc' : 'asc')
else { setSortField(field); setSortDir('asc') }
}
const sortIcon = (field: typeof sortField) => {
if (sortField !== field) return null
return sortDir === 'asc' ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />
}
return (
<div className="space-y-6">
<div>
<h1 className="font-display text-2xl font-bold tracking-tight">All Bookmarks</h1>
<p className="text-sm text-muted-foreground mt-1">Every saved link. Use the sidebar to filter by calendar, tags, board, or contacts.</p>
</div>
<div className="flex items-center gap-3">
<div className="relative flex-1 max-w-sm">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input placeholder="Filter..." value={search} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearch(e.target.value)} className="pl-9" />
</div>
<div className="flex rounded-lg border overflow-hidden">
<button onClick={() => setTab('mine')} className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${tab === 'mine' ? 'bg-primary text-primary-foreground' : 'bg-card hover:bg-muted'}`}>
<Inbox className="h-3.5 w-3.5" /> Mine
</button>
<button onClick={() => setTab('shared')} className={`flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium transition-colors ${tab === 'shared' ? 'bg-primary text-primary-foreground' : 'bg-card hover:bg-muted'}`}>
<Share2 className="h-3.5 w-3.5" /> Shared
</button>
</div>
</div>
<div className="rounded-lg border overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="bg-muted/50 text-left">
<th className="px-4 py-3 font-medium cursor-pointer" onClick={() => toggleSort('title')}>
<span className="flex items-center gap-1">Title {sortIcon('title')}</span>
</th>
<th className="px-4 py-3 font-medium">URL</th>
<th className="px-4 py-3 font-medium">Tags</th>
<th className="px-4 py-3 font-medium cursor-pointer" onClick={() => toggleSort('kanbanStatus')}>
<span className="flex items-center gap-1">Status {sortIcon('kanbanStatus')}</span>
</th>
<th className="px-4 py-3 font-medium cursor-pointer" onClick={() => toggleSort('updatedAt')}>
<span className="flex items-center gap-1">Updated {sortIcon('updatedAt')}</span>
</th>
<th className="px-4 py-3 font-medium w-20">Actions</th>
</tr>
</thead>
<tbody className="divide-y">
{loading ? (
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">Loading...</td></tr>
) : sorted.length === 0 ? (
<tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">No bookmarks found</td></tr>
) : sorted.map((b: Bookmark) => (
<tr key={b.id} tabIndex={0} className="hover:bg-muted/30 cursor-pointer focus-visible:outline-2 focus-visible:outline-primary" onClick={() => setSelected(b)} onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelected(b) } }}>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
{b.favicon && <img src={b.favicon} alt="" referrerPolicy="no-referrer" className="h-4 w-4 rounded" onError={(e: any) => { e.target.style.display = 'none' }} />}
<span className="truncate max-w-[200px]">{b.title ?? 'Untitled'}</span>
</div>
</td>
<td className="px-4 py-3">
<a href={b.url} target="_blank" rel="noopener noreferrer" onClick={(e: React.MouseEvent) => e.stopPropagation()} className="text-primary hover:underline truncate max-w-[200px] block">
{(() => { try { return new URL(b.url).hostname } catch { return b.url } })()}
</a>
</td>
<td className="px-4 py-3">
<div className="flex gap-1">
{(b.tags ?? []).slice(0, 2).map((bt: any) => (
<Badge key={bt?.tag?.id} variant="secondary" className="text-[10px] px-1.5 py-0" style={{ backgroundColor: `${bt?.tag?.color}20`, color: bt?.tag?.color }}>{bt?.tag?.name}</Badge>
))}
</div>
</td>
<td className="px-4 py-3"><Badge variant="outline" className="text-[10px]">{b.kanbanStatus?.replace('_', ' ')}</Badge></td>
<td className="px-4 py-3 text-xs text-muted-foreground">{new Date(b.updatedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })}</td>
<td className="px-4 py-3">
<div className="flex gap-1" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
<a href={b.url} target="_blank" rel="noopener noreferrer"><ExternalLink className="h-4 w-4 text-muted-foreground hover:text-primary" /></a>
{tab === 'mine' && (
<button onClick={async () => { if (!confirm('Delete?')) return; try { const res = await fetch(`/api/bookmarks/${b.id}`, { method: 'DELETE' }); if (res.ok) { toast.success('Deleted'); load() } else toast.error('Could not delete bookmark') } catch { toast.error('Could not delete bookmark') } }}><Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" /></button>
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
<BookmarkDetailSheet bookmark={selected} onClose={() => setSelected(null)} onUpdate={() => { load(); void refreshSelected() }} />
</div>
)
}
+8
View File
@@ -0,0 +1,8 @@
import { BookmarksClient } from './client'
// Quick Find deep-links (?open=<id>, ?search=<q>) arrive through searchParams
// so the client reacts to query changes without remounting.
export default async function BookmarksPage({ searchParams }: { searchParams: Promise<{ search?: string; open?: string }> }) {
const { search, open } = await searchParams
return <BookmarksClient initialSearch={search ?? null} initialOpen={open ?? null} />
}
+171
View File
@@ -0,0 +1,171 @@
'use client'
import { useState, useEffect, useCallback, useMemo } from 'react'
import { Button } from '@/components/ui/button'
import { BookmarkCard } from '@/components/bookmark-card'
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
import { ChevronLeft, ChevronRight, Share2 } from 'lucide-react'
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isSameDay, isSameMonth, addMonths, subMonths, getDay } from 'date-fns'
import type { Bookmark } from '@/components/app-shell'
import { Input } from '@/components/ui/input'
import { toast } from 'sonner'
import { fetchBookmarks } from '@/lib/bookmarks'
const INITIAL_DATE = new Date(2026, 9, 1)
export function CalendarClient() {
const [currentMonth, setCurrentMonth] = useState<Date>(INITIAL_DATE)
const [today, setToday] = useState<Date>(INITIAL_DATE)
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
const [selectedDay, setSelectedDay] = useState<Date | null>(null)
const [selectedBookmark, setSelectedBookmark] = useState<Bookmark | null>(null)
const [loading, setLoading] = useState(true)
const [sharedDates, setSharedDates] = useState<any[]>([])
const [shareQuery, setShareQuery] = useState('')
const [shareUsers, setShareUsers] = useState<any[]>([])
// Debounced user search; failures keep the previous results silently.
useEffect(() => {
const q = shareQuery.trim()
const t = setTimeout(async () => {
if (q.length < 2) { setShareUsers([]); return }
try {
const res = await fetch(`/api/users/search?q=${encodeURIComponent(q)}`)
if (res.ok) setShareUsers(await res.json())
} catch { /* transient; retried on next keystroke */ }
}, q.length < 2 ? 0 : 250)
return () => clearTimeout(t)
}, [shareQuery])
useEffect(() => {
const timer = setTimeout(() => { const now = new Date(); setCurrentMonth(now); setToday(now) }, 0)
return () => clearTimeout(timer)
}, [])
const load = useCallback(async () => {
setLoading(true)
try {
const [mine, shared, dates] = await Promise.all([fetchBookmarks(), fetchBookmarks(new URLSearchParams({ shared: 'true' })), fetch('/api/shared-dates')])
setBookmarks([...mine, ...shared])
if (dates.ok) setSharedDates(await dates.json())
} catch { toast.error('Could not load calendar') }
finally { setLoading(false) }
}, [])
useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('computer:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('computer:bookmarks-changed', load) } }, [load])
const days = useMemo(() => {
const start = startOfMonth(currentMonth)
const end = endOfMonth(currentMonth)
return eachDayOfInterval({ start, end })
}, [currentMonth])
const startDayOfWeek = getDay(startOfMonth(currentMonth))
const bookmarksByDay = useMemo(() => {
const map: Record<string, Bookmark[]> = {}
for (const b of bookmarks) {
if (b?.dueDate) {
const key = b.dueDate.slice(0, 10)
if (!map[key]) map[key] = []
map[key].push(b)
}
}
return map
}, [bookmarks])
const selectedBookmarks = useMemo(() => {
if (!selectedDay) return []
const key = format(selectedDay, 'yyyy-MM-dd')
return bookmarksByDay[key] ?? []
}, [selectedDay, bookmarksByDay])
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="font-display text-2xl font-bold tracking-tight">Calendar</h1>
<p className="text-sm text-muted-foreground mt-1">Bookmarks organized by due date</p>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="icon-sm" onClick={() => setCurrentMonth(subMonths(currentMonth, 1))}>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="font-medium text-sm min-w-[140px] text-center">{format(currentMonth, 'MMMM yyyy')}</span>
<Button variant="outline" size="icon-sm" onClick={() => setCurrentMonth(addMonths(currentMonth, 1))}>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
<div className="grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden">
{['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(d => (
<div key={d} className="bg-muted/50 px-2 py-2 text-center text-xs font-medium text-muted-foreground">{d}</div>
))}
{Array.from({ length: startDayOfWeek }).map((_, i) => (
<div key={`empty-${i}`} className="bg-card min-h-[80px]" />
))}
{days.map(day => {
const key = format(day, 'yyyy-MM-dd')
const dayBookmarks = bookmarksByDay[key] ?? []
const isSelected = selectedDay ? isSameDay(day, selectedDay) : false
const isToday = isSameDay(day, today)
return (
<div
key={key}
role="button"
tabIndex={0}
aria-pressed={isSelected}
aria-label={format(day, 'EEEE, MMMM d, yyyy')}
onClick={() => setSelectedDay(day)}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedDay(day) } }}
className={`bg-card min-h-[80px] p-1.5 cursor-pointer transition-colors hover:bg-muted/50 focus-visible:outline-2 focus-visible:outline-primary ${
isSelected ? 'ring-2 ring-primary ring-inset' : ''
}`}
>
<span className={`text-xs font-medium inline-flex h-6 w-6 items-center justify-center rounded-full ${
isToday ? 'bg-primary text-primary-foreground' : 'text-foreground'
}`}>
{format(day, 'd')}
</span>
<div className="space-y-0.5 mt-0.5">
{sharedDates.filter(s => s.date.slice(0, 10) === key).map(s => <p key={s.id} className="truncate text-[10px] text-primary" title={s.note || ''}>Shared: {s.creator.name || s.creator.email}</p>)}
{dayBookmarks.slice(0, 2).map((b: Bookmark) => (
<div key={b.id} role="button" tabIndex={0} className="text-[10px] truncate rounded bg-primary/10 text-primary px-1 py-0.5 cursor-pointer focus-visible:outline-1 focus-visible:outline-primary" onClick={(e: React.MouseEvent) => { e.stopPropagation(); setSelectedBookmark(b) }} onKeyDown={(e: React.KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); setSelectedBookmark(b) } }}>
{b.title ?? 'Untitled'}
</div>
))}
{dayBookmarks.length > 2 && (
<div className="text-[10px] text-muted-foreground px-1">+{dayBookmarks.length - 2} more</div>
)}
</div>
</div>
)
})}
</div>
{selectedDay && (
<div className="space-y-3">
<div className="flex items-center justify-between">
<h2 className="font-medium">{format(selectedDay, 'EEEE, MMMM d, yyyy')}</h2>
<div className="flex gap-2"><Input placeholder="Share date with user…" value={shareQuery} onChange={e => setShareQuery(e.target.value)} /></div>
</div>
{shareUsers.map(u => <Button key={u.id} size="sm" variant="outline" onClick={async () => { const res = await fetch('/api/shared-dates', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ date: format(selectedDay, 'yyyy-MM-dd'), recipientIds: [u.id] }) }); if (!res.ok) { toast.error('Could not share date'); return } toast.success('Date shared'); setShareQuery(''); setShareUsers([]); load() }}>Share with {u.name || u.email}</Button>)}
{sharedDates.filter(s => s.date.slice(0, 10) === format(selectedDay, 'yyyy-MM-dd')).map(s => <div key={s.id} className="flex items-center gap-2 text-xs text-muted-foreground"><span>{s.creator.name || s.creator.email} shared with {s.recipient.name || s.recipient.email}</span><Button size="xs" variant="ghost" onClick={async () => { const res = await fetch(`/api/shared-dates/${s.id}`, { method: 'DELETE' }); if (!res.ok) { toast.error('Only the owner can stop sharing'); return } load() }}>Stop sharing</Button></div>)}
{selectedBookmarks.length === 0 ? (
<p className="text-sm text-muted-foreground">No bookmarks on this date</p>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
{selectedBookmarks.map((b: Bookmark) => (
<BookmarkCard key={b.id} bookmark={b} compact onClick={() => setSelectedBookmark(b)} />
))}
</div>
)}
</div>
)}
<BookmarkDetailSheet bookmark={selectedBookmark} onClose={() => setSelectedBookmark(null)} onUpdate={load} />
</div>
)
}
+5
View File
@@ -0,0 +1,5 @@
import { CalendarClient } from './client'
export default function CalendarPage() {
return <CalendarClient />
}
+883
View File
@@ -0,0 +1,883 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { CalendarDays, Columns3, Filter, GripVertical, Kanban, Layers, List, Plus, Table2, Trash2, X } from 'lucide-react'
import { toast } from 'sonner'
import type { Bookmark } from '@/components/app-shell'
import { cn } from '@/lib/utils'
// Collections workspace (Notion-like upgrades phase 2). Contextual workflow
// state over existing bookmarks: the same link can be "Done" in one
// collection and "Unread" in another, and removing a membership never
// deletes the bookmark. Every mutating PATCH carries the expected version;
// a 409 reloads instead of clobbering (the DATA-05 contract).
type PropertyOption = { id: string; label: string; color?: string }
type CollectionProperty = {
id: string; name: string
type: 'TEXT' | 'NUMBER' | 'SELECT' | 'MULTI_SELECT' | 'DATE' | 'CHECKBOX' | 'URL'
position: number; config: { options?: PropertyOption[]; mode?: 'date' | 'datetime' }; version: number
}
type FilterClause = { propertyId: string; op: string; value?: unknown }
type CollectionView = {
id: string; name: string; type: 'TABLE' | 'BOARD' | 'CALENDAR' | 'LIST'; position: number
filters: { operator: 'AND' | 'OR'; clauses: FilterClause[] }
sorts: { field: string; dir: string }[]
groupByPropertyId: string | null; displaySettings: Record<string, unknown>; version: number
}
type CollectionItem = {
id: string; collectionId: string; bookmarkId: string
propertyValues: Record<string, unknown>; position: number; version: number
addedAt: string; updatedAt: string; bookmark: Bookmark
}
type CollectionSummary = {
id: string; name: string; description: string | null; icon: string | null
version: number; createdAt: string; updatedAt: string
_count: { items: number; properties: number; views: number }
}
type CollectionDetail = CollectionSummary & { properties: CollectionProperty[]; views: CollectionView[] }
const VIEW_ICONS = { TABLE: Table2, BOARD: Columns3, CALENDAR: CalendarDays, LIST: List } as const
const OP_LABELS: Record<string, string> = {
eq: 'is', ne: 'is not', contains: 'contains', gt: 'after/above', gte: '≥', lt: 'before/below', lte: '≤',
empty: 'is empty', notEmpty: 'is not empty',
}
// Mirrors the server allowlists in internal/handlers/collections.go.
const FILTER_OPS: Record<string, string[]> = {
TEXT: ['eq', 'ne', 'contains', 'empty', 'notEmpty'],
URL: ['eq', 'ne', 'contains', 'empty', 'notEmpty'],
NUMBER: ['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'empty', 'notEmpty'],
DATE: ['eq', 'ne', 'gt', 'gte', 'lt', 'lte', 'empty', 'notEmpty'],
SELECT: ['eq', 'ne', 'empty', 'notEmpty'],
CHECKBOX: ['eq', 'ne', 'empty', 'notEmpty'],
MULTI_SELECT: ['contains', 'empty', 'notEmpty'],
}
const PROPERTY_TYPES = ['TEXT', 'NUMBER', 'SELECT', 'MULTI_SELECT', 'DATE', 'CHECKBOX', 'URL'] as const
const NONE = '__none__'
async function json(res: Response): Promise<any> { return res.json().catch(() => null) }
// datetime-local inputs need local "YYYY-MM-DDTHH:mm"; the server stores a
// fixed-width UTC RFC3339 string, so convert through Date on both ends.
function toLocalInput(stored: unknown): string {
if (typeof stored !== 'string' || !stored) return ''
const d = new Date(stored)
if (Number.isNaN(d.getTime())) return ''
const pad = (n: number) => String(n).padStart(2, '0')
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`
}
function BookmarkCell({ bookmark }: { bookmark: Bookmark }) {
const host = (() => { try { return new URL(bookmark.url).hostname } catch { return bookmark.url } })()
return (
<Link href={`/bookmarks?open=${bookmark.id}`} className="flex min-w-0 items-center gap-2 hover:underline">
{bookmark.favicon
// eslint-disable-next-line @next/next/no-img-element -- remote favicons stay no-referrer (web/AGENTS.md)
? <img src={bookmark.favicon} alt="" referrerPolicy="no-referrer" className="h-4 w-4 shrink-0 rounded-sm" />
: <Layers className="h-4 w-4 shrink-0 text-muted-foreground" />}
<span className="min-w-0">
<span className="block max-w-[16rem] truncate text-sm">{bookmark.title || bookmark.url}</span>
<span className="block max-w-[16rem] truncate text-xs text-muted-foreground">{host}</span>
</span>
</Link>
)
}
const asText = (v: unknown) => (typeof v === 'string' || typeof v === 'number' ? String(v) : '')
// Per-type inline value editor. Saves immediately on commit gestures
// (change/blur/Enter); failures toast and the prop value re-renders the
// server state, so a rejected edit never sticks locally.
function ValueEditor({ prop, value, onSave }: { prop: CollectionProperty; value: unknown; onSave: (v: unknown) => Promise<void> }) {
const [text, setText] = useState(() => asText(value))
const [seen, setSeen] = useState(value)
// Adjusting state when a prop changes: the React-documented render-time
// pattern (guarded, converges immediately) instead of a cascading effect.
if (value !== seen) {
setSeen(value)
setText(asText(value))
}
const [open, setOpen] = useState(false)
const commitText = async () => {
const next = text.trim()
const current = asText(value)
if (next === current) return
if (next === '') { await onSave(null); return }
await onSave(prop.type === 'NUMBER' ? Number(next) : next)
}
switch (prop.type) {
case 'CHECKBOX':
return <Checkbox aria-label={prop.name} checked={value === true} onCheckedChange={(c) => { void onSave(c === true) }} />
case 'SELECT': {
const options = prop.config.options ?? []
return (
<Select
value={typeof value === 'string' && value ? value : NONE}
onValueChange={(id) => { void onSave(id === NONE ? null : id) }}
>
<SelectTrigger className="h-8 w-[9.5rem]" aria-label={prop.name}><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>—</SelectItem>
{options.map((o) => (
<SelectItem key={o.id} value={o.id}>
<span className="flex items-center gap-1.5">
{o.color && <span className="h-2 w-2 rounded-full" style={{ backgroundColor: o.color }} />}
{o.label}
</span>
</SelectItem>
))}
</SelectContent>
</Select>
)
}
case 'MULTI_SELECT': {
const options = prop.config.options ?? []
const selected = new Set(Array.isArray(value) ? (value as string[]) : [])
const toggle = async (id: string) => {
const next = new Set(selected)
if (next.has(id)) next.delete(id); else next.add(id)
await onSave([...next])
}
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button type="button" aria-label={`Edit ${prop.name}`} className="flex min-h-8 w-[9.5rem] flex-wrap items-center gap-1 rounded-md border border-input px-2 py-1 text-left hover:bg-muted">
{selected.size === 0 && <span className="text-xs text-muted-foreground">—</span>}
{options.filter((o) => selected.has(o.id)).map((o) => (
<Badge key={o.id} variant="secondary" className="gap-1 text-xs" style={o.color ? { borderColor: o.color } : undefined}>{o.label}</Badge>
))}
</button>
</PopoverTrigger>
<PopoverContent className="w-52 space-y-2" align="start">
{options.map((o) => (
<label key={o.id} className="flex items-center gap-2 text-sm">
<Checkbox checked={selected.has(o.id)} onCheckedChange={() => { void toggle(o.id) }} />
{o.color && <span className="h-2 w-2 rounded-full" style={{ backgroundColor: o.color }} />}
{o.label}
</label>
))}
{options.length === 0 && <p className="text-xs text-muted-foreground">No options yet</p>}
</PopoverContent>
</Popover>
)
}
case 'DATE':
return prop.config.mode === 'datetime'
? <Input type="datetime-local" aria-label={prop.name} className="h-8 w-[13rem]" value={toLocalInput(value)} onChange={(e) => { const v = e.target.value; void onSave(v ? new Date(v).toISOString() : null) }} />
: <Input type="date" aria-label={prop.name} className="h-8 w-[9.5rem]" value={typeof value === 'string' ? value : ''} onChange={(e) => { void onSave(e.target.value || null) }} />
case 'NUMBER':
case 'TEXT':
case 'URL':
default:
return (
<Input
aria-label={prop.name}
className="h-8 w-[9.5rem]"
type={prop.type === 'NUMBER' ? 'number' : 'text'}
value={text}
onChange={(e) => setText(e.target.value)}
onBlur={() => { void commitText() }}
onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur() }}
/>
)
}
}
export function CollectionsClient() {
const [collections, setCollections] = useState<CollectionSummary[]>([])
const [activeId, setActiveId] = useState<string | null>(null)
const [detail, setDetail] = useState<CollectionDetail | null>(null)
const [items, setItems] = useState<CollectionItem[]>([])
const [cursor, setCursor] = useState<string | null>(null)
const [draggedItemId, setDraggedItemId] = useState<string | null>(null)
const [boardDropKey, setBoardDropKey] = useState<string | null>(null)
const [viewId, setViewId] = useState<string | null>(null)
const [newName, setNewName] = useState('')
const [nameDraft, setNameDraft] = useState('')
const [addOpen, setAddOpen] = useState(false)
const [addQuery, setAddQuery] = useState('')
const [addResults, setAddResults] = useState<Bookmark[]>([])
const [propOpen, setPropOpen] = useState(false)
const [propName, setPropName] = useState('')
const [propType, setPropType] = useState<(typeof PROPERTY_TYPES)[number]>('SELECT')
const [propOptions, setPropOptions] = useState<{ label: string; color: string }[]>([])
const [propMode, setPropMode] = useState<'date' | 'datetime'>('date')
const [viewOpen, setViewOpen] = useState(false)
const [viewName, setViewName] = useState('')
const [viewType, setViewType] = useState<'TABLE' | 'BOARD' | 'CALENDAR' | 'LIST'>('TABLE')
const [filterOpen, setFilterOpen] = useState(false)
const [fProp, setFProp] = useState('')
const [fOp, setFOp] = useState('eq')
const [fValue, setFValue] = useState('')
const loadCollections = useCallback(async () => {
try {
const res = await fetch('/api/collections')
if (res.ok) setCollections(await res.json())
} catch { toast.error('Could not load collections') }
}, [])
const loadDetail = useCallback(async (id: string) => {
try {
const res = await fetch(`/api/collections/${id}`)
if (!res.ok) { setDetail(null); return }
const data: CollectionDetail = await res.json()
setDetail(data)
setNameDraft(data.name)
setViewId((current) => (current && data.views.some((v) => v.id === current) ? current : data.views[0]?.id ?? null))
} catch { toast.error('Could not load collection') }
}, [])
const loadItems = useCallback(async (id: string, view: string | null, append?: string | null) => {
try {
const params = new URLSearchParams({ limit: '200' })
if (view) params.set('viewId', view)
if (append) params.set('cursor', append)
const res = await fetch(`/api/collections/${id}/items?${params}`)
if (!res.ok) return
const rows: CollectionItem[] = await res.json()
setItems((current) => (append ? [...current, ...rows] : rows))
setCursor(res.headers.get('X-Next-Cursor'))
} catch { toast.error('Could not load items') }
}, [])
useEffect(() => { const t = setTimeout(loadCollections, 0); return () => clearTimeout(t) }, [loadCollections])
useEffect(() => {
const t = setTimeout(() => {
if (!activeId && collections.length) setActiveId(collections[0].id)
}, 0)
return () => clearTimeout(t)
}, [collections, activeId])
useEffect(() => {
const t = setTimeout(() => {
if (!activeId) { setDetail(null); return }
loadDetail(activeId)
}, 0)
return () => clearTimeout(t)
}, [activeId, loadDetail])
useEffect(() => {
const t = setTimeout(() => {
if (!activeId) { setItems([]); return }
loadItems(activeId, viewId)
}, 0)
return () => clearTimeout(t)
}, [activeId, viewId, loadItems])
// Versioned mutation helper: 409 means another session moved first — the
// server state wins, we reload, and nothing is clobbered (DATA-05 lesson).
const mutate = async (res: Response, reload: () => void, okMessage?: string): Promise<boolean> => {
if (res.ok) { if (okMessage) toast.success(okMessage); return true }
if (res.status === 409) {
const body = await json(res)
toast.error(body?.error || 'Changed elsewhere; reloaded the latest version')
reload()
return false
}
const body = await json(res)
toast.error(body?.error || 'Request failed')
return false
}
const patch = (url: string, body: Record<string, unknown>) =>
fetch(url, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
const activeView = detail?.views.find((v) => v.id === viewId) ?? null
const groupProp = activeView?.groupByPropertyId ? detail?.properties.find((p) => p.id === activeView.groupByPropertyId) : null
const createCollection = async () => {
const name = newName.trim()
if (!name) return
const res = await fetch('/api/collections', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) })
if (!res.ok) { await mutate(res, loadCollections); return }
const created = await res.json().catch(() => null)
toast.success('Collection created')
setNewName('')
await loadCollections()
if (created?.id) setActiveId(created.id)
}
const saveName = async () => {
if (!detail) return
const name = nameDraft.trim()
if (!name || name === detail.name) { setNameDraft(detail.name); return }
const res = await patch(`/api/collections/${detail.id}`, { version: detail.version, name })
if (await mutate(res, () => loadDetail(detail.id), 'Renamed')) {
setDetail((d) => (d ? { ...d, name, version: d.version + 1 } : d))
loadCollections()
} else setNameDraft(detail.name)
}
const deleteCollection = async () => {
if (!detail || !confirm(`Delete collection "${detail.name}"? Bookmarks are kept.`)) return
const res = await fetch(`/api/collections/${detail.id}`, { method: 'DELETE' })
if (await mutate(res, loadCollections, 'Collection deleted')) {
setActiveId(null)
setDetail(null)
loadCollections()
}
}
const createProperty = async () => {
if (!detail) return
const name = propName.trim()
if (!name) return
const config: Record<string, unknown> = {}
if (propType === 'SELECT' || propType === 'MULTI_SELECT') {
config.options = propOptions.filter((o) => o.label.trim()).map((o) => ({ label: o.label.trim(), ...(o.color ? { color: o.color } : {}) }))
}
if (propType === 'DATE') config.mode = propMode
const res = await fetch(`/api/collections/${detail.id}/properties`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name, type: propType, config }),
})
if (await mutate(res, () => loadDetail(detail.id), 'Property added')) {
setPropOpen(false); setPropName(''); setPropOptions([])
loadDetail(detail.id)
}
}
const deleteProperty = async (prop: CollectionProperty) => {
if (!detail || !confirm(`Delete property "${prop.name}"? Its values are removed from every item.`)) return
const res = await fetch(`/api/collections/${detail.id}/properties/${prop.id}`, { method: 'DELETE' })
if (await mutate(res, () => loadDetail(detail.id), 'Property deleted')) {
loadDetail(detail.id)
loadItems(detail.id, viewId)
}
}
const createView = async () => {
if (!detail) return
const name = viewName.trim()
if (!name) return
const res = await fetch(`/api/collections/${detail.id}/views`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, type: viewType }),
})
if (!res.ok) { await mutate(res, () => loadDetail(detail.id)); return }
const created = await res.json().catch(() => null)
toast.success('View added')
setViewOpen(false); setViewName('')
await loadDetail(detail.id)
if (created?.id) setViewId(created.id)
}
const deleteView = async () => {
if (!detail || !activeView || !confirm(`Delete view "${activeView.name}"?`)) return
const res = await fetch(`/api/collections/${detail.id}/views/${activeView.id}`, { method: 'DELETE' })
if (await mutate(res, () => loadDetail(detail.id), 'View deleted')) {
setViewId(null)
loadDetail(detail.id)
}
}
const patchView = async (changes: Record<string, unknown>) => {
if (!detail || !activeView) return
const res = await patch(`/api/collections/${detail.id}/views/${activeView.id}`, { version: activeView.version, ...changes })
if (res.ok) {
const updated: CollectionView = await res.json()
setDetail((d) => (d ? { ...d, views: d.views.map((v) => (v.id === updated.id ? updated : v)) } : d))
loadItems(detail.id, updated.id)
} else await mutate(res, () => loadDetail(detail.id))
}
const addItem = async (bookmarkId: string) => {
if (!detail) return
const res = await fetch(`/api/collections/${detail.id}/items`, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ bookmarkId }),
})
if (res.ok) {
loadItems(detail.id, viewId)
loadCollections()
} else if (res.status === 409) toast.error('Already in this collection')
else { const body = await json(res); toast.error(body?.error || 'Could not add bookmark') }
}
const removeItem = async (item: CollectionItem) => {
if (!detail) return
const res = await fetch(`/api/collections/${detail.id}/items/${item.id}`, { method: 'DELETE' })
if (await mutate(res, () => loadItems(detail.id, viewId))) {
setItems((current) => current.filter((i) => i.id !== item.id))
loadCollections()
}
}
const saveValue = async (item: CollectionItem, propId: string, value: unknown) => {
if (!detail) return
const res = await patch(`/api/collections/${detail.id}/items/${item.id}`, {
version: item.version, propertyValues: { [propId]: value },
})
if (res.ok) {
const updated: CollectionItem = await res.json()
setItems((current) => current.map((i) => (i.id === updated.id ? updated : i)))
} else await mutate(res, () => loadItems(detail.id, viewId))
}
// Board drag-and-drop and the per-card select both go through the same
// versioned membership PATCH. Update optimistically, then reconcile with the
// server; any failure reloads so a rejected value never sticks locally.
const moveItemToGroup = async (item: CollectionItem, next: string | null) => {
if (!detail || !groupProp) return
const current = item.propertyValues?.[groupProp.id]
const normalized = current === undefined || current === '' ? null : current
if (normalized === next) return
setItems((current) => current.map((i) => i.id === item.id ? {
...i, propertyValues: { ...i.propertyValues, [groupProp.id]: next },
} : i))
const res = await patch(`/api/collections/${detail.id}/items/${item.id}`, {
version: item.version, propertyValues: { [groupProp.id]: next },
})
if (res.ok) {
const updated: CollectionItem = await res.json()
setItems((current) => current.map((i) => (i.id === updated.id ? updated : i)))
return
}
const handled = await mutate(res, () => loadItems(detail.id, viewId))
if (!handled && res.status !== 409) await loadItems(detail.id, viewId)
}
// Debounced bookmark search for the add dialog.
useEffect(() => {
if (!addOpen) return
const q = addQuery.trim()
const t = setTimeout(async () => {
try {
const params = new URLSearchParams({ limit: '8' })
if (q) params.set('search', q)
const res = await fetch(`/api/bookmarks?${params}`)
if (res.ok) setAddResults((await res.json()).slice(0, 8))
} catch { /* transient; retried on next keystroke */ }
}, 250)
return () => clearTimeout(t)
}, [addQuery, addOpen])
const filterClauses = activeView?.filters?.clauses ?? []
const setClause = (clauses: FilterClause[]) => { void patchView({ filters: { operator: activeView?.filters?.operator ?? 'AND', clauses } }) }
const addClause = () => {
if (!fProp || !fOp) return
const prop = detail?.properties.find((p) => p.id === fProp)
if (!prop) return
let value: unknown
if (!['empty', 'notEmpty'].includes(fOp)) {
if (prop.type === 'NUMBER') value = Number(fValue)
else if (prop.type === 'CHECKBOX') value = fValue === 'true'
else value = fValue
if (fValue === '' || (prop.type === 'NUMBER' && Number.isNaN(value))) { toast.error('Filter value required'); return }
}
setClause([...filterClauses, value === undefined ? { propertyId: fProp, op: fOp } : { propertyId: fProp, op: fOp, value }])
setFilterOpen(false); setFValue('')
}
const clauseLabel = (c: FilterClause) => {
const prop = detail?.properties.find((p) => p.id === c.propertyId)
if (!prop) return 'unknown'
let shown = c.value
if (prop.type === 'SELECT' && typeof c.value === 'string') shown = prop.config.options?.find((o) => o.id === c.value)?.label ?? c.value
if (prop.type === 'CHECKBOX') shown = c.value === true ? 'checked' : 'unchecked'
return `${prop.name} ${OP_LABELS[c.op] ?? c.op}${shown !== undefined ? ` ${shown}` : ''}`
}
const renderTable = () => (
<div className="overflow-x-auto rounded-lg border border-border/60">
<Table>
<TableHeader>
<TableRow>
<TableHead className="min-w-[16rem]">Bookmark</TableHead>
{(detail?.properties ?? []).map((p) => (
<TableHead key={p.id} className="min-w-[11rem]">
<span className="flex items-center gap-1.5">
{p.name}
<button type="button" aria-label={`Delete property ${p.name}`} className="text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100" onClick={() => deleteProperty(p)}>
<Trash2 className="h-3 w-3" />
</button>
</span>
</TableHead>
))}
<TableHead className="w-10" />
</TableRow>
</TableHeader>
<TableBody>
{items.map((item) => (
<TableRow key={item.id} className="group">
<TableCell><BookmarkCell bookmark={item.bookmark} /></TableCell>
{(detail?.properties ?? []).map((p) => (
<TableCell key={p.id}><ValueEditor prop={p} value={item.propertyValues?.[p.id]} onSave={(v) => saveValue(item, p.id, v)} /></TableCell>
))}
<TableCell>
<button type="button" aria-label="Remove from collection" className="text-muted-foreground hover:text-destructive" onClick={() => removeItem(item)}>
<Trash2 className="h-4 w-4" />
</button>
</TableCell>
</TableRow>
))}
{items.length === 0 && (
<TableRow>
<TableCell colSpan={(detail?.properties.length ?? 0) + 2} className="py-10 text-center text-sm text-muted-foreground">
No items{filterClauses.length ? " match this view's filters" : ''}. Add existing bookmarks — nothing is duplicated.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
)
const renderBoard = () => {
if (!groupProp || groupProp.type !== 'SELECT') {
return (
<div className="rounded-lg border border-dashed border-border p-8 text-center">
<Kanban className="mx-auto mb-2 h-8 w-8 text-muted-foreground" />
<p className="text-sm text-muted-foreground">Board views group by a select property.</p>
<div className="mx-auto mt-3 w-56">
<Select
value={NONE}
onValueChange={(id) => { if (id !== NONE) patchView({ groupByPropertyId: id }) }}
>
<SelectTrigger aria-label="Group by property"><SelectValue placeholder="Choose a select property…" /></SelectTrigger>
<SelectContent>
{(detail?.properties ?? []).filter((p) => p.type === 'SELECT').map((p) => (
<SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
)
}
const options = groupProp.config.options ?? []
const columns = [...options.map((o) => ({ key: o.id, label: o.label, color: o.color })), { key: NONE, label: 'No value', color: undefined }]
return (
<div className="flex gap-3 overflow-x-auto pb-2">
{columns.map((col) => {
const colItems = items.filter((i) => {
const v = i.propertyValues?.[groupProp.id]
return col.key === NONE ? (v === undefined || v === null) : v === col.key
})
const isDropTarget = !!draggedItemId && boardDropKey === col.key
return (
<div
key={col.key}
data-board-group={col.key}
onDragOver={(e) => {
if (!draggedItemId) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
setBoardDropKey(col.key)
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setBoardDropKey(null)
}}
onDrop={(e) => {
e.preventDefault()
const item = items.find((i) => i.id === draggedItemId)
if (item) void moveItemToGroup(item, col.key === NONE ? null : col.key)
setDraggedItemId(null)
setBoardDropKey(null)
}}
className={cn(
'w-64 shrink-0 rounded-lg border border-border/60 bg-muted/30 p-2 transition-[box-shadow,background-color,border-color] duration-150',
isDropTarget && 'border-primary/40 bg-primary/[0.04] ring-2 ring-primary/40',
)}
>
<div className="mb-2 flex items-center gap-1.5 px-1 text-sm font-medium">
{col.color && <span className="h-2 w-2 rounded-full" style={{ backgroundColor: col.color }} />}
{col.label}
<span className="ml-auto text-xs text-muted-foreground">{colItems.length}</span>
</div>
<div className="space-y-2">
{colItems.map((item) => (
<div
key={item.id}
data-collection-item-id={item.id}
className={cn(
'rounded-md border border-border bg-card p-2 shadow-sm transition-[transform,box-shadow,opacity] duration-150 group',
draggedItemId === item.id && 'opacity-40',
)}
>
<div className="flex items-start gap-1">
<span
data-drag-handle
draggable
onDragStart={(e) => {
setDraggedItemId(item.id)
e.dataTransfer.effectAllowed = 'move'
e.dataTransfer.setData('text/plain', item.id)
}}
onDragEnd={() => {
setDraggedItemId(null)
setBoardDropKey(null)
}}
className="mt-0.5 cursor-grab text-muted-foreground/50 transition-colors hover:text-muted-foreground active:cursor-grabbing"
title="Drag to another group"
aria-label={`Drag ${item.bookmark.title ?? 'bookmark'}`}
>
<GripVertical className="h-3.5 w-3.5" />
</span>
<div className="min-w-0 flex-1">
<BookmarkCell bookmark={item.bookmark} />
</div>
</div>
<div className="mt-1.5 flex items-center justify-between gap-1">
<Select
value={typeof item.propertyValues?.[groupProp.id] === 'string' ? (item.propertyValues[groupProp.id] as string) : NONE}
onValueChange={(id) => { void moveItemToGroup(item, id === NONE ? null : id) }}
>
<SelectTrigger className="h-7 w-28 text-xs" aria-label={`Move ${item.bookmark.title ?? 'card'}`}><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={NONE}>—</SelectItem>
{options.map((o) => <SelectItem key={o.id} value={o.id}>{o.label}</SelectItem>)}
</SelectContent>
</Select>
<button type="button" aria-label="Remove from collection" className="text-muted-foreground hover:text-destructive" onClick={() => removeItem(item)}>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
))}
{colItems.length === 0 && (
<p className={cn('px-1 py-3 text-center text-xs text-muted-foreground', isDropTarget && 'text-primary')}>
{isDropTarget ? 'Drop here' : 'Empty'}
</p>
)}
</div>
</div>
)
})}
</div>
)
}
return (
<div className="flex h-full flex-col">
<div className="flex flex-1 overflow-hidden">
{/* Collection list */}
<div className="flex w-60 shrink-0 flex-col border-r border-border/60 p-3">
<h1 className="mb-3 flex items-center gap-2 font-display text-lg font-semibold tracking-tight">
<Layers className="h-4 w-4" /> Collections
</h1>
<div className="mb-3 flex gap-1.5">
<Input value={newName} onChange={(e) => setNewName(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') createCollection() }} placeholder="New collection" className="h-8 text-sm" aria-label="New collection name" />
<Button size="sm" variant="outline" className="h-8 shrink-0 px-2" onClick={createCollection} aria-label="Create collection"><Plus className="h-4 w-4" /></Button>
</div>
<div className="flex-1 space-y-1 overflow-y-auto">
{collections.map((c) => (
<button
key={c.id}
onClick={() => { setActiveId(c.id); setViewId(null) }}
className={cn('flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors', c.id === activeId ? 'bg-primary/10 font-medium text-primary' : 'text-muted-foreground hover:bg-muted hover:text-foreground')}
>
<Layers className="h-3.5 w-3.5 shrink-0" />
<span className="min-w-0 flex-1 truncate">{c.name}</span>
<span className="shrink-0 text-xs text-muted-foreground">{c._count.items}</span>
</button>
))}
{collections.length === 0 && (
<p className="px-2 py-6 text-center text-xs text-muted-foreground">
Collections hold workflow state per project. The same bookmark can live in many — nothing is duplicated.
</p>
)}
</div>
</div>
{/* Detail */}
<div className="flex-1 overflow-y-auto px-6 py-5">
{!detail ? (
<div className="flex h-full flex-col items-center justify-center gap-3 text-center">
<Layers className="h-10 w-10 text-muted-foreground" />
<h2 className="font-display text-xl font-semibold">{collections.length ? 'Select a collection' : 'No collections yet'}</h2>
<p className="max-w-sm text-sm text-muted-foreground">
A collection is a saved workflow over existing bookmarks: per-collection status, priority, dates — independent everywhere the link appears.
</p>
</div>
) : (
<>
<div className="mb-4 flex flex-wrap items-center gap-2">
<Input value={nameDraft} onChange={(e) => setNameDraft(e.target.value)} onBlur={saveName} onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur() }} aria-label="Collection name" className="w-72 bg-transparent font-display text-2xl font-bold tracking-tight" />
<span className="text-xs text-muted-foreground">{detail._count?.items ?? 0} item{(detail._count?.items ?? 0) === 1 ? '' : 's'}</span>
<div className="ml-auto flex items-center gap-1.5">
<Button size="sm" variant="outline" onClick={() => setAddOpen(true)}><Plus className="mr-1 h-4 w-4" />Add bookmarks</Button>
<Button size="sm" variant="outline" onClick={() => setPropOpen(true)}><Plus className="mr-1 h-4 w-4" />Property</Button>
<Button size="sm" variant="ghost" onClick={deleteCollection} aria-label="Delete collection" title="Delete collection"><Trash2 className="h-4 w-4 text-destructive" /></Button>
</div>
</div>
{/* View tabs */}
<div className="mb-3 flex flex-wrap items-center gap-1.5">
{detail.views.map((v) => {
const Icon = VIEW_ICONS[v.type] ?? Table2
return (
<button
key={v.id}
onClick={() => setViewId(v.id)}
className={cn('flex items-center gap-1.5 rounded-md px-2.5 py-1 text-sm transition-colors', v.id === viewId ? 'bg-primary/10 font-medium text-primary' : 'text-muted-foreground hover:bg-muted hover:text-foreground')}
>
<Icon className="h-3.5 w-3.5" /> {v.name}
</button>
)
})}
<Button size="sm" variant="ghost" className="h-7 px-2" onClick={() => setViewOpen(true)} aria-label="Add view"><Plus className="h-4 w-4" /></Button>
{activeView && (
<div className="ml-auto flex items-center gap-1.5">
<Popover open={filterOpen} onOpenChange={(o) => { setFilterOpen(o); if (o) { setFProp(detail.properties[0]?.id ?? ''); setFOp(FILTER_OPS[detail.properties[0]?.type ?? 'TEXT']?.[0] ?? 'eq') } }}>
<PopoverTrigger asChild>
<Button size="sm" variant="ghost" className="h-7 gap-1 px-2 text-muted-foreground"><Filter className="h-3.5 w-3.5" />Filter{filterClauses.length > 0 && ` (${filterClauses.length})`}</Button>
</PopoverTrigger>
<PopoverContent className="w-80 space-y-2" align="end">
<Label className="text-xs uppercase tracking-wider text-muted-foreground">Add a filter clause</Label>
<Select value={fProp || undefined} onValueChange={(id) => { setFProp(id); const p = detail.properties.find((x) => x.id === id); setFOp(FILTER_OPS[p?.type ?? 'TEXT']?.[0] ?? 'eq'); setFValue('') }}>
<SelectTrigger aria-label="Filter property"><SelectValue placeholder="Property" /></SelectTrigger>
<SelectContent>
{detail.properties.filter((p) => FILTER_OPS[p.type]).map((p) => <SelectItem key={p.id} value={p.id}>{p.name}</SelectItem>)}
</SelectContent>
</Select>
<Select value={fOp} onValueChange={setFOp}>
<SelectTrigger aria-label="Filter operator"><SelectValue /></SelectTrigger>
<SelectContent>
{(FILTER_OPS[detail.properties.find((p) => p.id === fProp)?.type ?? 'TEXT'] ?? []).map((op) => <SelectItem key={op} value={op}>{OP_LABELS[op] ?? op}</SelectItem>)}
</SelectContent>
</Select>
{!['empty', 'notEmpty'].includes(fOp) && (() => {
const p = detail.properties.find((x) => x.id === fProp)
if (p?.type === 'SELECT') return (
<Select value={fValue || undefined} onValueChange={setFValue}>
<SelectTrigger aria-label="Filter value"><SelectValue placeholder="Value" /></SelectTrigger>
<SelectContent>{(p.config.options ?? []).map((o) => <SelectItem key={o.id} value={o.id}>{o.label}</SelectItem>)}</SelectContent>
</Select>
)
if (p?.type === 'CHECKBOX') return (
<Select value={fValue || undefined} onValueChange={setFValue}>
<SelectTrigger aria-label="Filter value"><SelectValue placeholder="Value" /></SelectTrigger>
<SelectContent><SelectItem value="true">checked</SelectItem><SelectItem value="false">unchecked</SelectItem></SelectContent>
</Select>
)
return <Input value={fValue} onChange={(e) => setFValue(e.target.value)} placeholder="Value" aria-label="Filter value" className="h-8 text-sm" />
})()}
<Button size="sm" className="w-full" onClick={addClause}>Apply filter</Button>
</PopoverContent>
</Popover>
<Button size="sm" variant="ghost" className="h-7 px-2 text-muted-foreground" onClick={deleteView} aria-label="Delete view" title="Delete view"><Trash2 className="h-3.5 w-3.5" /></Button>
</div>
)}
</div>
{/* Active filter chips */}
{filterClauses.length > 0 && (
<div className="mb-3 flex flex-wrap items-center gap-1.5">
<span className="text-xs text-muted-foreground">{activeView?.filters?.operator ?? 'AND'}:</span>
{filterClauses.map((c, i) => (
<Badge key={i} variant="secondary" className="gap-1">
{clauseLabel(c)}
<button type="button" aria-label="Remove filter" onClick={() => setClause(filterClauses.filter((_, j) => j !== i))}><X className="h-3 w-3" /></button>
</Badge>
))}
</div>
)}
{activeView?.type === 'BOARD' ? renderBoard() : renderTable()}
{activeView && (activeView.type === 'CALENDAR' || activeView.type === 'LIST') && (
<p className="mt-2 text-xs text-muted-foreground">Calendar and list layouts render as a table in this phase.</p>
)}
{cursor && (
<Button size="sm" variant="outline" className="mt-3" onClick={() => loadItems(detail.id, viewId, cursor)}>Load more</Button>
)}
</>
)}
</div>
</div>
{/* Add bookmarks dialog */}
<Dialog open={addOpen} onOpenChange={(o) => { setAddOpen(o); if (!o) setAddQuery('') }}>
<DialogContent className="max-w-lg">
<DialogHeader><DialogTitle>Add existing bookmarks</DialogTitle></DialogHeader>
<p className="text-xs text-muted-foreground">Membership is contextual — adding here never duplicates or re-owns the bookmark.</p>
<Input autoFocus value={addQuery} onChange={(e) => setAddQuery(e.target.value)} placeholder="Search bookmarks…" aria-label="Search bookmarks" />
<div className="max-h-72 space-y-1 overflow-y-auto">
{addResults.map((b) => {
const member = items.some((i) => i.bookmarkId === b.id)
return (
<div key={b.id} className="flex items-center gap-2 rounded-md border border-border/60 px-2 py-1.5">
<div className="min-w-0 flex-1">
<p className="truncate text-sm">{b.title || b.url}</p>
<p className="truncate text-xs text-muted-foreground">{b.url}</p>
</div>
<Button size="sm" variant={member ? 'ghost' : 'outline'} disabled={member} onClick={() => addItem(b.id)}>
{member ? 'Added' : 'Add'}
</Button>
</div>
)
})}
{addResults.length === 0 && <p className="py-6 text-center text-sm text-muted-foreground">No bookmarks found</p>}
</div>
</DialogContent>
</Dialog>
{/* New property dialog */}
<Dialog open={propOpen} onOpenChange={setPropOpen}>
<DialogContent className="max-w-md">
<DialogHeader><DialogTitle>New property</DialogTitle></DialogHeader>
<div className="space-y-3">
<Input value={propName} onChange={(e) => setPropName(e.target.value)} placeholder="Name (e.g. Status)" aria-label="Property name" />
<Select value={propType} onValueChange={(t) => setPropType(t as (typeof PROPERTY_TYPES)[number])}>
<SelectTrigger aria-label="Property type"><SelectValue /></SelectTrigger>
<SelectContent>
{PROPERTY_TYPES.map((t) => <SelectItem key={t} value={t}>{t.replace('_', ' ').toLowerCase().replace(/\b\w/g, (m) => m.toUpperCase())}</SelectItem>)}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">Type is permanent — conversions that could destroy values are refused by design.</p>
{(propType === 'SELECT' || propType === 'MULTI_SELECT') && (
<div className="space-y-2">
<Label className="text-xs uppercase tracking-wider text-muted-foreground">Options</Label>
{propOptions.map((o, i) => (
<div key={i} className="flex items-center gap-2">
<Input type="color" aria-label="Option color" value={o.color || '#6366f1'} onChange={(e) => setPropOptions(propOptions.map((x, j) => (j === i ? { ...x, color: e.target.value } : x)))} className="h-8 w-10 shrink-0 p-1" />
<Input value={o.label} onChange={(e) => setPropOptions(propOptions.map((x, j) => (j === i ? { ...x, label: e.target.value } : x)))} placeholder="Option label" aria-label="Option label" className="h-8 text-sm" />
<Button size="sm" variant="ghost" className="h-8 px-2" aria-label="Remove option" onClick={() => setPropOptions(propOptions.filter((_, j) => j !== i))}><X className="h-4 w-4" /></Button>
</div>
))}
<Button size="sm" variant="outline" onClick={() => setPropOptions([...propOptions, { label: '', color: '#6366f1' }])}><Plus className="mr-1 h-4 w-4" />Option</Button>
</div>
)}
{propType === 'DATE' && (
<Select value={propMode} onValueChange={(m) => setPropMode(m as 'date' | 'datetime')}>
<SelectTrigger aria-label="Date mode"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="date">Date only (never shifts across timezones)</SelectItem>
<SelectItem value="datetime">Date &amp; time (stored UTC)</SelectItem>
</SelectContent>
</Select>
)}
<Button className="w-full" onClick={createProperty}>Create property</Button>
</div>
</DialogContent>
</Dialog>
{/* New view dialog */}
<Dialog open={viewOpen} onOpenChange={setViewOpen}>
<DialogContent className="max-w-sm">
<DialogHeader><DialogTitle>New view</DialogTitle></DialogHeader>
<div className="space-y-3">
<Input autoFocus value={viewName} onChange={(e) => setViewName(e.target.value)} placeholder="View name" aria-label="View name" />
<Select value={viewType} onValueChange={(t) => setViewType(t as typeof viewType)}>
<SelectTrigger aria-label="View type"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="TABLE">Table</SelectItem>
<SelectItem value="BOARD">Board</SelectItem>
<SelectItem value="CALENDAR">Calendar (renders as table for now)</SelectItem>
<SelectItem value="LIST">List (renders as table for now)</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">A view is a saved query — filters and grouping never copy records.</p>
<Button className="w-full" onClick={createView}>Create view</Button>
</div>
</DialogContent>
</Dialog>
</div>
)
}
+5
View File
@@ -0,0 +1,5 @@
import { CollectionsClient } from './client'
export default function CollectionsPage() {
return <CollectionsClient />
}
+121
View File
@@ -0,0 +1,121 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { BookmarkCard } from '@/components/bookmark-card'
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
import { Users, RefreshCw, Mail, Phone } from 'lucide-react'
import { toast } from 'sonner'
import type { Bookmark } from '@/components/app-shell'
import { fetchBookmarks } from '@/lib/bookmarks'
interface Contact {
id: string
uid: string
displayName: string
email: string | null
phone: string | null
_count?: { bookmarks: number }
}
export function ContactsClient() {
const [contacts, setContacts] = useState<Contact[]>([])
const [selectedContact, setSelectedContact] = useState<string | null>(null)
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
const [selectedBookmark, setSelectedBookmark] = useState<Bookmark | null>(null)
const [syncing, setSyncing] = useState(false)
const [loading, setLoading] = useState(true)
const loadContacts = useCallback(async () => {
setLoading(true)
try {
const res = await fetch('/api/contacts')
if (res.ok) setContacts(await res.json())
} catch { toast.error('Could not load contacts') }
finally { setLoading(false) }
}, [])
const loadBookmarks = useCallback(async (contactId: string) => {
try { setBookmarks(await fetchBookmarks(new URLSearchParams({ contactId }))) }
catch { toast.error('Could not load bookmarks') }
}, [])
useEffect(() => { const timer = setTimeout(loadContacts, 0); return () => clearTimeout(timer) }, [loadContacts])
useEffect(() => { const timer = setTimeout(() => { if (selectedContact) loadBookmarks(selectedContact) }, 0); return () => clearTimeout(timer) }, [selectedContact, loadBookmarks])
useEffect(() => { const reload = () => { loadContacts(); if (selectedContact) loadBookmarks(selectedContact) }; window.addEventListener('computer:bookmarks-changed', reload); return () => window.removeEventListener('computer:bookmarks-changed', reload) }, [loadContacts, loadBookmarks, selectedContact])
const syncContacts = async () => {
setSyncing(true)
toast.info('Configure your Nextcloud settings in Settings → Nextcloud to sync contacts')
setSyncing(false)
}
return (
<div className="flex gap-6 h-[calc(100vh-120px)]">
<div className="w-72 shrink-0 space-y-4 overflow-y-auto">
<div className="flex items-center justify-between">
<h1 className="font-display text-2xl font-bold tracking-tight">Contacts</h1>
<Button variant="outline" size="sm" onClick={syncContacts} loading={syncing} className="gap-1.5">
<RefreshCw className="h-3 w-3" /> Sync
</Button>
</div>
{loading ? (
<div className="space-y-2">{Array.from({ length: 5 }).map((_, i) => <div key={i} className="h-14 rounded-lg bg-muted animate-pulse" />)}</div>
) : contacts.length === 0 ? (
<div className="text-center py-8">
<Users className="h-10 w-10 text-muted-foreground/50 mx-auto mb-3" />
<p className="text-sm text-muted-foreground">No contacts yet</p>
<p className="text-xs text-muted-foreground mt-1">Sync from Nextcloud in Settings</p>
</div>
) : (
<div className="space-y-1">
{contacts.map((c: Contact) => (
<div
key={c.id}
role="button"
tabIndex={0}
aria-pressed={selectedContact === c.id}
onClick={() => setSelectedContact(c.id)}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedContact(c.id) } }}
className={`flex items-center gap-3 rounded-lg px-3 py-2.5 cursor-pointer transition-colors focus-visible:outline-2 focus-visible:outline-primary ${
selectedContact === c.id ? 'bg-accent' : 'hover:bg-muted'
}`}
>
<div className="h-9 w-9 rounded-full bg-primary/20 flex items-center justify-center text-sm font-bold text-primary shrink-0">
{(c.displayName ?? '?')[0]?.toUpperCase()}
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium truncate">{c.displayName}</p>
{c.email && <p className="text-xs text-muted-foreground truncate flex items-center gap-1"><Mail className="h-3 w-3" />{c.email}</p>}
</div>
<span className="text-xs text-muted-foreground">{c._count?.bookmarks ?? 0}</span>
</div>
))}
</div>
)}
</div>
<div className="flex-1 overflow-y-auto">
{selectedContact ? (
<div className="space-y-4">
<h2 className="font-medium">Bookmarks for {contacts.find(c => c.id === selectedContact)?.displayName}</h2>
{bookmarks.length === 0 ? (
<p className="text-sm text-muted-foreground py-8 text-center">No bookmarks linked to this contact</p>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{bookmarks.map((b: Bookmark) => <BookmarkCard key={b.id} bookmark={b} compact onClick={() => setSelectedBookmark(b)} />)}
</div>
)}
</div>
) : (
<div className="flex flex-col items-center justify-center h-full text-center">
<Users className="h-12 w-12 text-muted-foreground/50 mb-4" />
<p className="text-muted-foreground">Select a contact to view linked bookmarks</p>
</div>
)}
</div>
<BookmarkDetailSheet bookmark={selectedBookmark} onClose={() => setSelectedBookmark(null)} onUpdate={() => { if (selectedContact) loadBookmarks(selectedContact) }} />
</div>
)
}
+5
View File
@@ -0,0 +1,5 @@
import { ContactsClient } from './client'
export default function ContactsPage() {
return <ContactsClient />
}
+7
View File
@@ -0,0 +1,7 @@
import { redirect } from 'next/navigation'
// The dashboard was folded into the "All Bookmarks" filter view.
export default async function DashboardPage({ searchParams }: { searchParams: Promise<{ search?: string }> }) {
const { search } = await searchParams
redirect(search ? `/bookmarks?search=${encodeURIComponent(search)}` : '/bookmarks')
}
+444
View File
@@ -0,0 +1,444 @@
'use client'
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useSession } from 'next-auth/react'
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { ExternalLink, Calendar, GripVertical, Plus, MoreHorizontal, Pencil, Trash2, ArrowLeft, ArrowRight, Check, X } from 'lucide-react'
import { toast } from 'sonner'
import type { Bookmark } from '@/components/app-shell'
import { fetchBookmarks } from '@/lib/bookmarks'
import { invalidateReference } from '@/lib/reference-data'
import { cn } from '@/lib/utils'
type Column = { id: string; label: string; color: string; position: number; key: string | null }
type CardDrop = { columnId: string; index: number }
const PALETTE = ['#64748b', '#3b82f6', '#f59e0b', '#22c55e', '#8b5cf6', '#ec4899', '#ef4444', '#14b8a6']
function columnFor(b: Bookmark, cols: Column[]) {
const explicit = (b as any).kanbanColumnId as string | null
if (explicit && cols.some(c => c.id === explicit)) return explicit
return cols.find(c => c.key === b.kanbanStatus)?.id ?? cols[0]?.id
}
function sortCards(a: Bookmark, b: Bookmark, currentUserId?: string) {
// Owned cards keep their persisted board order. Shared cards are read-only
// and sort after owned ones so they cannot disturb the owner's positions.
if (currentUserId) {
const aOwned = a.ownerId === currentUserId
const bOwned = b.ownerId === currentUserId
if (aOwned !== bOwned) return aOwned ? -1 : 1
}
const ap = a.kanbanPosition ?? 0
const bp = b.kanbanPosition ?? 0
if (ap !== bp) return ap - bp
return b.updatedAt.localeCompare(a.updatedAt) || b.id.localeCompare(a.id)
}
export function KanbanClient() {
const { data: session } = useSession()
const currentUserId = session?.user?.id
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
const [columns, setColumns] = useState<Column[]>([])
const [loading, setLoading] = useState(true)
const [selectedBookmark, setSelectedBookmark] = useState<Bookmark | null>(null)
const [draggedId, setDraggedId] = useState<string | null>(null)
const [draggedColumnId, setDraggedColumnId] = useState<string | null>(null)
const [cardDrop, setCardDrop] = useState<CardDrop | null>(null)
const [columnDropId, setColumnDropId] = useState<string | null>(null)
const [editingId, setEditingId] = useState<string | null>(null)
const [editLabel, setEditLabel] = useState('')
const [adding, setAdding] = useState(false)
const [newLabel, setNewLabel] = useState('')
const suppressClick = useRef(false)
const load = useCallback(async () => {
setLoading(true)
try {
const [bookmarks, cRes] = await Promise.all([fetchBookmarks(), fetch('/api/kanban/columns')])
setBookmarks(bookmarks)
if (cRes.ok) setColumns(await cRes.json())
} catch (e) { console.error('Kanban load failed', e) }
setLoading(false)
}, [])
useEffect(() => { const timer = setTimeout(load, 0); window.addEventListener('computer:bookmarks-changed', load); return () => { clearTimeout(timer); window.removeEventListener('computer:bookmarks-changed', load) } }, [load])
const isOwned = useCallback((b: Bookmark) => !currentUserId || b.ownerId === currentUserId, [currentUserId])
const cardsByColumn = useMemo(() => {
const groups: Record<string, Bookmark[]> = {}
for (const col of columns) groups[col.id] = []
for (const b of bookmarks) {
const columnId = columnFor(b, columns)
if (columnId && groups[columnId]) groups[columnId].push(b)
}
for (const list of Object.values(groups)) list.sort((a, b) => sortCards(a, b, currentUserId))
return groups
}, [bookmarks, columns, currentUserId])
const clearDrag = useCallback(() => {
setDraggedId(null)
setDraggedColumnId(null)
setCardDrop(null)
setColumnDropId(null)
}, [])
const finishDrag = useCallback(() => {
clearDrag()
// Drag gestures can still emit a click in some browsers; do not open the
// detail sheet when the pointer was dragging a card.
setTimeout(() => { suppressClick.current = false }, 0)
}, [clearDrag])
const saveColumnOrder = useCallback(async (next: Column[]) => {
setColumns(next)
const res = await fetch('/api/kanban/columns', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ order: next.map(c => c.id) }) })
if (res.ok) invalidateReference('columns')
else { toast.error('Could not reorder columns'); load() }
}, [load])
const reorderColumn = useCallback((sourceId: string, targetId: string) => {
if (sourceId === targetId) return
const from = columns.findIndex(c => c.id === sourceId)
const to = columns.findIndex(c => c.id === targetId)
if (from < 0 || to < 0) return
const next = [...columns]
const [moved] = next.splice(from, 1)
// Drop before the target column; this is the least surprising direction
// for both leftward and rightward moves.
next.splice(from < to ? to - 1 : to, 0, moved)
saveColumnOrder(next)
}, [columns, saveColumnOrder])
// Position among the owner's cards, ignoring read-only shared cards and the
// card being dragged. The server normalizes the target column in this order.
const ownedDropIndex = useCallback((columnId: string, rawIndex: number, movedId: string) => {
const list = cardsByColumn[columnId] ?? []
let index = 0
for (let i = 0; i < Math.min(rawIndex, list.length); i++) {
const card = list[i]
if (card.id === movedId || !isOwned(card)) continue
index++
}
return index
}, [cardsByColumn, isOwned])
const moveCardTo = useCallback(async (bookmarkId: string, columnId: string, position: number) => {
const current = bookmarks.find(b => b.id === bookmarkId)
if (!current) return
if (currentUserId && current.ownerId !== currentUserId) {
toast.error('Only the owner can move a shared bookmark')
return
}
const target = (cardsByColumn[columnId] ?? []).filter(b => b.id !== bookmarkId && isOwned(b))
const clamped = Math.max(0, Math.min(position, target.length))
const optimistic = [...target]
optimistic.splice(clamped, 0, { ...current, kanbanColumnId: columnId })
const positions = new Map(optimistic.map((b, i) => [b.id, i]))
setBookmarks(prev => prev.map(b => {
if (b.id === bookmarkId) return { ...b, kanbanColumnId: columnId, kanbanPosition: clamped }
const next = positions.get(b.id)
return next === undefined ? b : { ...b, kanbanPosition: next }
}))
try {
const res = await fetch(`/api/kanban/cards/${bookmarkId}`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
// Optimistic concurrency (review CR-04): the move carries the card's
// version; a card edited or moved elsewhere is a 409, and the board
// reloads the true state instead of silently clobbering it.
body: JSON.stringify({ columnId, position: clamped, version: current.version ?? 0 }),
})
if (res.status === 409) {
toast.error('This bookmark was changed elsewhere — the board reloaded without your move')
load()
return
}
if (!res.ok) throw new Error(await res.text())
const saved = await res.json().catch(() => null)
if (saved) setBookmarks(prev => prev.map(b => b.id === bookmarkId ? saved : b))
} catch (e) { console.error(e); toast.error('Failed to move'); load() }
}, [bookmarks, cardsByColumn, currentUserId, isOwned, load])
const addColumn = async () => {
if (!newLabel.trim()) return
const res = await fetch('/api/kanban/columns', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ label: newLabel, color: PALETTE[columns.length % PALETTE.length] }),
})
if (res.ok) { const col = await res.json(); setColumns(c => [...c, col]); setNewLabel(''); setAdding(false); invalidateReference('columns') }
else toast.error('Could not add column')
}
const saveColumn = async (id: string, data: Partial<Column>) => {
const res = await fetch(`/api/kanban/columns/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) })
if (res.ok) { const col = await res.json(); setColumns(cs => cs.map(c => c.id === id ? col : c)); invalidateReference('columns') }
else toast.error('Could not update column')
setEditingId(null)
}
const deleteColumn = async (col: Column) => {
if (columns.length <= 1) { toast.error('A board needs at least one column'); return }
const dest = columns.find(c => c.id !== col.id)
if (!confirm(`Delete "${col.label}"? Its bookmarks will move to "${dest?.label}".`)) return
const res = await fetch(`/api/kanban/columns/${col.id}`, { method: 'DELETE' })
if (res.ok) { toast.success('Column deleted'); invalidateReference('columns'); load() } else toast.error((await res.json())?.error ?? 'Could not delete')
}
const moveColumn = (index: number, dir: -1 | 1) => {
const next = [...columns]
const j = index + dir
if (j < 0 || j >= next.length) return
;[next[index], next[j]] = [next[j], next[index]]
saveColumnOrder(next)
}
// Keyboard alternative to drag-and-drop: focus a card, Arrow Left/Right
// moves it to the adjacent column.
const moveCard = (b: Bookmark, dir: -1 | 1) => {
if (!isOwned(b)) { toast.error('Only the owner can move a shared bookmark'); return }
const current = columnFor(b, columns)
const idx = columns.findIndex(c => c.id === current)
const j = idx + dir
if (idx < 0 || j < 0 || j >= columns.length) return
moveCardTo(b.id, columns[j].id, cardsByColumn[columns[j].id]?.filter(c => c.id !== b.id && isOwned(c)).length ?? 0)
toast.success(`Moved to ${columns[j].label}`)
}
const handleCardDragOver = (e: React.DragEvent<HTMLElement>, col: Column, index: number) => {
if (!draggedId || draggedColumnId) return
e.preventDefault()
e.stopPropagation()
e.dataTransfer.dropEffect = 'move'
const rect = e.currentTarget.getBoundingClientRect()
const before = e.clientY < rect.top + rect.height / 2
setCardDrop({ columnId: col.id, index: before ? index : index + 1 })
}
const handleColumnDragOver = (e: React.DragEvent<HTMLElement>, col: Column) => {
if (draggedColumnId) {
if (draggedColumnId === col.id) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
setColumnDropId(col.id)
setCardDrop(null)
return
}
if (!draggedId) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
// The pointer is over the column body, not a card: append to the end.
setCardDrop(prev => prev?.columnId === col.id ? prev : { columnId: col.id, index: (cardsByColumn[col.id] ?? []).length })
}
const handleColumnDrop = (e: React.DragEvent<HTMLElement>, col: Column) => {
e.preventDefault()
if (draggedColumnId) {
reorderColumn(draggedColumnId, col.id)
finishDrag()
return
}
if (draggedId) {
const rawIndex = cardDrop?.columnId === col.id ? cardDrop.index : (cardsByColumn[col.id] ?? []).length
moveCardTo(draggedId, col.id, ownedDropIndex(col.id, rawIndex, draggedId))
finishDrag()
}
}
const handleColumnDragLeave = (e: React.DragEvent<HTMLElement>) => {
if (e.currentTarget.contains(e.relatedTarget as Node | null)) return
if (draggedColumnId) setColumnDropId(null)
if (draggedId) setCardDrop(null)
}
return (
<div className="space-y-6">
<div className="flex items-end justify-between gap-4">
<div>
<h1 className="font-display text-2xl font-bold tracking-tight">Kanban Board</h1>
<p className="text-sm text-muted-foreground mt-1">Drag cards within or between columns, drag a column by its grip to reorder it, or focus a card and press Arrow Left/Right. Touch users can use each card’s menu.</p>
</div>
{!adding ? (
<Button size="sm" variant="outline" className="gap-1.5" onClick={() => setAdding(true)}><Plus className="h-4 w-4" /> Add column</Button>
) : (
<div className="flex items-center gap-1.5">
<Input autoFocus value={newLabel} onChange={e => setNewLabel(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') addColumn(); if (e.key === 'Escape') setAdding(false) }} placeholder="Column name" className="h-8 w-40" />
<Button size="icon-sm" onClick={addColumn}><Check className="h-4 w-4" /></Button>
<Button size="icon-sm" variant="ghost" onClick={() => setAdding(false)}><X className="h-4 w-4" /></Button>
</div>
)}
</div>
<div className="flex gap-4 overflow-x-auto pb-2 h-[calc(100vh-180px)]">
{columns.map((col, idx) => {
const colBookmarks = cardsByColumn[col.id] ?? []
const isCardTarget = !!draggedId && cardDrop?.columnId === col.id
const isColumnTarget = !!draggedColumnId && columnDropId === col.id && draggedColumnId !== col.id
return (
<div
key={col.id}
data-column-id={col.id}
className={cn(
'rounded-lg border bg-muted/30 flex flex-col w-72 shrink-0 transition-[box-shadow,background-color,border-color] duration-150',
isCardTarget && 'bg-primary/[0.04] border-primary/30 shadow-sm',
isColumnTarget && 'ring-2 ring-primary/50 border-primary/40',
)}
style={{ borderTopColor: col.color, borderTopWidth: 3 }}
onDragOver={e => handleColumnDragOver(e, col)}
onDragLeave={handleColumnDragLeave}
onDrop={e => handleColumnDrop(e, col)}
>
<div className="px-3 py-2 border-b flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5 min-w-0">
<span
draggable
onDragStart={e => {
setDraggedColumnId(col.id)
setDraggedId(null)
setCardDrop(null)
e.dataTransfer.effectAllowed = 'move'
e.dataTransfer.setData('text/plain', col.id)
}}
onDragEnd={finishDrag}
className="cursor-grab active:cursor-grabbing text-muted-foreground/40 hover:text-muted-foreground transition-colors"
title="Drag to reorder column"
aria-label={`Drag ${col.label} column`}
>
<GripVertical className="h-4 w-4" />
</span>
{editingId === col.id ? (
<Input autoFocus value={editLabel} onChange={e => setEditLabel(e.target.value)} onBlur={() => saveColumn(col.id, { label: editLabel })}
onKeyDown={e => { if (e.key === 'Enter') saveColumn(col.id, { label: editLabel }); if (e.key === 'Escape') setEditingId(null) }} className="h-7 text-sm" />
) : (
<h3 className="text-sm font-medium truncate flex items-center gap-2">
<span className="h-2 w-2 rounded-full shrink-0" style={{ backgroundColor: col.color }} />{col.label}
</h3>
)}
</div>
<div className="flex items-center gap-1 shrink-0">
<span className="text-xs text-muted-foreground bg-muted rounded-full px-2 py-0.5">{colBookmarks.length}</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="icon-sm" variant="ghost" aria-label={`Column ${col.label} options`}><MoreHorizontal className="h-4 w-4" /></Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => { setEditingId(col.id); setEditLabel(col.label) }}><Pencil className="h-3.5 w-3.5 mr-2" />Rename</DropdownMenuItem>
<DropdownMenuItem disabled={idx === 0} onClick={() => moveColumn(idx, -1)}><ArrowLeft className="h-3.5 w-3.5 mr-2" />Move left</DropdownMenuItem>
<DropdownMenuItem disabled={idx === columns.length - 1} onClick={() => moveColumn(idx, 1)}><ArrowRight className="h-3.5 w-3.5 mr-2" />Move right</DropdownMenuItem>
<DropdownMenuSeparator />
<div className="flex gap-1.5 px-2 py-1.5">
{PALETTE.map(c => (
<button key={c} aria-label={`Color ${c}`} onClick={() => saveColumn(col.id, { color: c })} className="h-4 w-4 rounded-full ring-offset-1 hover:ring-2 ring-ring" style={{ backgroundColor: c }} />
))}
</div>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive" onClick={() => deleteColumn(col)}><Trash2 className="h-3.5 w-3.5 mr-2" />Delete column</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div className="flex-1 overflow-y-auto p-2 space-y-2">
{loading ? (
Array.from({ length: 3 }).map((_, i) => <div key={i} className="h-20 rounded-lg bg-muted/50 animate-pulse" />)
) : colBookmarks.length === 0 ? (
<div className={cn('flex h-24 items-center justify-center rounded-lg border border-dashed text-xs text-muted-foreground transition-colors', isCardTarget && 'border-primary/50 bg-primary/[0.03] text-primary')}>
{draggedId ? 'Drop card here' : 'No cards yet'}
</div>
) : colBookmarks.map((b, index) => {
const canMove = isOwned(b)
const showLine = isCardTarget && cardDrop?.index === index
const currentColumn = columnFor(b, columns)
return (
<Fragment key={b.id}>
{showLine && <div className="mx-1 h-1 rounded-full bg-primary/70 shadow-sm" />}
<div
draggable={canMove}
role="button"
tabIndex={0}
data-bookmark-id={b.id}
aria-label={canMove
? `${b.title ?? 'Untitled'}. Enter opens details; Arrow Left or Right moves to the adjacent column.`
: `${b.title ?? 'Untitled'} (shared). Enter opens details.`}
onDragStart={e => {
if (!canMove) { e.preventDefault(); return }
suppressClick.current = true
setDraggedId(b.id)
setDraggedColumnId(null)
setColumnDropId(null)
e.dataTransfer.effectAllowed = 'move'
e.dataTransfer.setData('text/plain', b.id)
}}
onDragEnd={finishDrag}
onDragOver={e => handleCardDragOver(e, col, index)}
onClick={() => { if (!suppressClick.current) setSelectedBookmark(b) }}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedBookmark(b) }
else if (canMove && e.key === 'ArrowLeft') { e.preventDefault(); moveCard(b, -1) }
else if (canMove && e.key === 'ArrowRight') { e.preventDefault(); moveCard(b, 1) }
}}
className={cn(
'rounded-lg border bg-card p-3 shadow-sm transition-[transform,box-shadow,opacity] duration-150 group focus-visible:outline-2 focus-visible:outline-primary',
canMove ? 'cursor-grab active:cursor-grabbing hover:-translate-y-0.5 hover:shadow-md' : 'cursor-default',
draggedId === b.id && 'opacity-40 scale-[0.98]',
)}
>
<div className="flex items-start gap-2">
<GripVertical className={cn('h-4 w-4 text-muted-foreground/50 mt-0.5 shrink-0', !canMove && 'opacity-30')} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
{b.favicon && <img src={b.favicon} alt="" referrerPolicy="no-referrer" className="h-3.5 w-3.5 rounded" onError={(e: any) => { e.target.style.display = 'none' }} />}
<p className="text-sm font-medium truncate">{b.title ?? 'Untitled'}</p>
{!canMove && <Badge variant="outline" className="text-[9px] px-1 py-0 shrink-0">Shared</Badge>}
</div>
<div className="flex flex-wrap gap-1 mt-1.5">
{(b.tags ?? []).slice(0, 2).map((bt: any) => (
<Badge key={bt?.tag?.id} variant="secondary" className="text-[9px] px-1 py-0" style={{ backgroundColor: `${bt?.tag?.color}20`, color: bt?.tag?.color }}>{bt?.tag?.name}</Badge>
))}
</div>
{b.dueDate && (
<p className="text-[10px] text-muted-foreground mt-1 flex items-center gap-1">
<Calendar className="h-3 w-3" />
{new Date(b.dueDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })}
</p>
)}
</div>
<div className="flex items-center gap-0.5 opacity-60 group-hover:opacity-100 focus-within:opacity-100 shrink-0" onDragStart={e => { e.preventDefault(); e.stopPropagation() }}>
<a href={b.url} target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()} className="rounded p-0.5" aria-label="Open link">
<ExternalLink className="h-3.5 w-3.5 text-muted-foreground hover:text-primary" />
</a>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button size="icon-sm" variant="ghost" className="h-6 w-6" onClick={e => e.stopPropagation()} aria-label={`${b.title ?? 'Bookmark'} options`}><MoreHorizontal className="h-3.5 w-3.5" /></Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setSelectedBookmark(b)}><ExternalLink className="h-3.5 w-3.5 mr-2" />Open details</DropdownMenuItem>
{canMove && columns.length > 1 && <DropdownMenuSeparator />}
{canMove && columns.filter(c => c.id !== currentColumn).map(c => (
<DropdownMenuItem key={c.id} onClick={() => moveCardTo(b.id, c.id, cardsByColumn[c.id]?.filter(x => x.id !== b.id && isOwned(x)).length ?? 0)}>
<span className="h-2 w-2 rounded-full mr-2 shrink-0" style={{ backgroundColor: c.color }} />Move to {c.label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
</div>
</Fragment>
)
})}
{!loading && isCardTarget && cardDrop?.index === colBookmarks.length && colBookmarks.length > 0 && (
<div className="mx-1 h-1 rounded-full bg-primary/70 shadow-sm" />
)}
</div>
</div>
)
})}
</div>
<BookmarkDetailSheet bookmark={selectedBookmark} onClose={() => setSelectedBookmark(null)} onUpdate={load} />
</div>
)
}
+5
View File
@@ -0,0 +1,5 @@
import { KanbanClient } from './client'
export default function KanbanPage() {
return <KanbanClient />
}
+11
View File
@@ -0,0 +1,11 @@
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
import { AppShellWrapper } from '@/components/app-shell-wrapper'
export default async function AppLayout({ children }: { children: React.ReactNode }) {
const session = await auth()
if (!session?.user) redirect('/login')
// Pass the server session down so the shell and screens render during SSR
// instead of being discarded and refetched on the client.
return <AppShellWrapper session={session}>{children}</AppShellWrapper>
}
+699
View File
@@ -0,0 +1,699 @@
'use client'
import { useCallback, useEffect, useRef, useState, type ClipboardEvent } from 'react'
import { useRouter } from 'next/navigation'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { toast } from 'sonner'
import {
ChevronLeft, ChevronRight, Code, Download, Eye, FileText, GripVertical, Heading1, Heading2, Heading3,
Link2, List, ListOrdered, ListTodo, Minus, Pencil, Pin, PinOff, Plus, Quote, Search, Trash2, Type, X,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { cn } from '@/lib/utils'
import { PageAutosave, PageConflictError, type PageSaveState } from '@/lib/page-autosave'
import { PAGES_CHANGED, nextUntitledTitle, notifyActivePage, notifyPagesChanged, type PageSummary } from '@/lib/pages'
import { reorderPages } from '@/lib/page-order'
import { fetchLinkPreview } from '@/lib/link-preview'
import { LinkPreviewCard } from '@/components/link-preview-card'
import type { Element, ElementContent } from 'hast'
export { PAGES_CHANGED }
// Notion-style slash menu: typing "/" at the start of a line offers blocks
// that insert their Markdown equivalent. The textarea stays the source of
// truth, so autosave and conflict handling are untouched.
const SLASH_BLOCKS = [
{ key: 'text', label: 'Text', desc: 'Plain paragraph', icon: Type, prefix: '' },
{ key: 'h1', label: 'Heading 1', desc: 'Large section heading', icon: Heading1, prefix: '# ' },
{ key: 'h2', label: 'Heading 2', desc: 'Medium section heading', icon: Heading2, prefix: '## ' },
{ key: 'h3', label: 'Heading 3', desc: 'Small section heading', icon: Heading3, prefix: '### ' },
{ key: 'todo', label: 'To-do list', desc: 'Track tasks with a checkbox', icon: ListTodo, prefix: '- [ ] ' },
{ key: 'bullet', label: 'Bulleted list', desc: 'Simple bulleted list', icon: List, prefix: '- ' },
{ key: 'num', label: 'Numbered list', desc: 'List with numbering', icon: ListOrdered, prefix: '1. ' },
{ key: 'quote', label: 'Quote', desc: 'Capture a quote', icon: Quote, prefix: '> ' },
{ key: 'div', label: 'Divider', desc: 'Visual section break', icon: Minus, prefix: '---\n' },
{ key: 'code', label: 'Code', desc: 'Code snippet block', icon: Code, prefix: '```\n' },
] as const
type LinkedBookmark = { id: string; url: string; title: string | null; favicon: string | null; ogImage: string | null; ogTitle: string | null; ogDescription: string | null; description: string | null }
type PageDetail = PageSummary & { content: string; version: number; bookmarks: { bookmark: LinkedBookmark }[] }
const notify = notifyPagesChanged
const host = (u: string) => { try { return new URL(u).hostname.replace(/^www\./, '') } catch { return u } }
const textOf = (nodes: ElementContent[]): string =>
nodes.map((n) => (n.type === 'text' ? n.value : n.type === 'element' ? textOf(n.children) : '')).join('')
// A paragraph whose only content is a single external link — a bare URL
// autolinked by GFM or a lone [label](url) — renders as a Notion-style
// preview card instead of a plain <p><a>. Links woven into sentences stay
// inline text; the Markdown source remains the source of truth either way.
function standaloneLink(node: Element | undefined): { href: string; label: string } | null {
if (!node) return null
const kids = node.children.filter((c) => !(c.type === 'text' && c.value.trim() === ''))
if (kids.length !== 1) return null
const a = kids[0]
if (a.type !== 'element' || a.tagName !== 'a') return null
const href = a.properties?.href
if (typeof href !== 'string' || !/^https?:\/\//i.test(href)) return null
return { href, label: textOf(a.children) }
}
export function PagesClient({ initialId }: { initialId: string | null }) {
const router = useRouter()
const [pages, setPages] = useState<PageSummary[]>([])
const [activeId, setActiveId] = useState<string | null>(initialId)
const [page, setPage] = useState<PageDetail | null>(null)
const [filter, setFilter] = useState('')
const [mode, setMode] = useState<'edit' | 'preview'>('preview')
const [title, setTitle] = useState('')
const [content, setContent] = useState('')
const [saveStates, setSaveStates] = useState<Record<string, PageSaveState>>({})
const [linkQuery, setLinkQuery] = useState('')
const [results, setResults] = useState<LinkedBookmark[]>([])
const [linkOpen, setLinkOpen] = useState(false)
const [slash, setSlash] = useState<{ query: string; start: number } | null>(null)
const [slashIndex, setSlashIndex] = useState(0)
const [tabDrop, setTabDrop] = useState<{ id: string; after: boolean } | null>(null)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const pendingCaret = useRef<number | null>(null)
const suppressTabClick = useRef(false)
const draggedTabRef = useRef<string | null>(null)
const activePage = useRef(initialId)
const loadSequence = useRef(0)
const selectionSequence = useRef(0)
// Optimistic concurrency (review DATA-01): PageAutosave tracks the server
// revision per page and sends it with content saves, so a newer save from
// another tab or device answers 409 instead of being silently overwritten.
const persistContent = useCallback(async (id: string, content: string, version: number | undefined) => {
const body = JSON.stringify(typeof version === 'number' ? { content, version } : { content })
let res: Response
try {
res = await fetch(`/api/pages/${id}`, {
method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body,
keepalive: new TextEncoder().encode(body).length < 60000,
})
} catch (error) {
toast.error('Could not save page. Your draft is kept in this tab; retry saving.')
throw error
}
if (res.status === 409) {
// Another session saved first. Review DATA-04: the queue enters a
// paused conflict state instead of adopting the remote version, so
// nothing overwrites the newer content until the user explicitly
// chooses to overwrite, discard, or copy the draft.
let serverVersion: number | undefined
try {
const latest = await fetch(`/api/pages/${id}`, { cache: 'no-store' }).then(r => (r.ok ? r.json() : null))
if (latest && typeof latest.version === 'number') serverVersion = latest.version
} catch { /* keep the stale base; the conflict state pauses autosave either way */ }
toast.error('This page was saved in another tab or device. Autosave is paused so nothing is overwritten until you resolve the conflict.')
throw new PageConflictError(serverVersion)
}
if (!res.ok) {
toast.error('Could not save page. Your draft is kept in this tab; retry saving.')
throw new Error('Save failed')
}
const saved = await res.json().catch(() => null)
return saved && typeof saved.version === 'number' ? saved.version : undefined
}, [])
const [autosave] = useState(() => new PageAutosave(persistContent, (id, state) => setSaveStates(previous => ({ ...previous, [id]: state }))))
const saveState = activeId ? saveStates[activeId] ?? 'saved' : 'saved'
useEffect(() => {
const beforeUnload = (event: BeforeUnloadEvent) => {
if (autosave.hasUnsaved()) { event.preventDefault(); event.returnValue = '' }
}
const flush = () => { void autosave.flushAll() }
window.addEventListener('beforeunload', beforeUnload)
window.addEventListener('pagehide', flush)
return () => {
window.removeEventListener('beforeunload', beforeUnload)
window.removeEventListener('pagehide', flush)
flush()
}
}, [autosave])
const loadPages = useCallback(async () => {
const res = await fetch('/api/pages')
if (!res.ok) return [] as PageSummary[]
const data: PageSummary[] = await res.json()
setPages(data)
return data
}, [])
const loadPage = useCallback(async (id: string) => {
const sequence = ++loadSequence.current
const res = await fetch(`/api/pages/${id}`)
if (sequence !== loadSequence.current || activePage.current !== id) return
if (!res.ok) { setPage(null); notifyActivePage(null); return }
const data: PageDetail = await res.json()
if (sequence !== loadSequence.current || activePage.current !== id) return
if (typeof data.version === 'number') autosave.setVersion(data.id, data.version)
// Review DATA-03: recovery compares the draft's original base version
// with the freshly fetched server version; a mismatch pauses autosave in
// the conflict state instead of silently rebasing onto the newer save.
const draft = autosave.restore(id, data.version)
setPage(data)
setTitle(data.title)
setContent(draft ?? data.content)
notifyActivePage(data.title)
if (draft !== undefined || !data.content) setMode('edit')
}, [autosave])
useEffect(() => {
const timer = setTimeout(() => loadPages().then((data) => {
if (!activePage.current && data.length) { activePage.current = data[0].id; setActiveId(data[0].id) }
}).catch((e) => console.error('Failed to load pages', e)), 0)
return () => clearTimeout(timer)
}, [loadPages])
useEffect(() => {
const timer = setTimeout(() => {
if (activeId) loadPage(activeId).catch((e) => console.error('Failed to load page', e))
else setPage(null)
}, 0)
return () => clearTimeout(timer)
}, [activeId, loadPage])
const select = async (id: string) => {
const sequence = ++selectionSequence.current
if (activePage.current && !await autosave.flush(activePage.current)) return
if (sequence !== selectionSequence.current) return
activePage.current = id
setActiveId(id)
router.replace(`/pages?id=${id}`)
}
// The sidebar can create or open pages while this workspace stays mounted.
useEffect(() => {
if (!initialId || initialId === activePage.current) return
void loadPages()
void select(initialId)
}, [initialId])
// Sidebar mutations (rename, pin, delete) announce themselves; keep the
// page list in step and drop the detail view when the open page is gone.
useEffect(() => {
const reload = () => {
void loadPages().then((data) => {
if (activePage.current && !data.some((p) => p.id === activePage.current)) {
activePage.current = null
setActiveId(null)
setPage(null)
notifyActivePage(null)
router.replace('/pages')
}
})
}
window.addEventListener(PAGES_CHANGED, reload)
return () => window.removeEventListener(PAGES_CHANGED, reload)
}, [loadPages, router])
// Leaving the pages workspace clears the breadcrumb title.
useEffect(() => () => { notifyActivePage(null) }, [])
const patch = async (body: Record<string, unknown>) => {
if (!activeId || page?.id !== activeId) return null
const res = await fetch(`/api/pages/${page.id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
if (!res.ok) { toast.error('Could not save page'); return null }
// Review CR-17: metadata responses (rename/pin/link changes) carry the
// CURRENT content revision but never require or acknowledge a content
// base — adopting it here would silently rebase an in-flight stale draft
// onto another editor's save and authorize overwriting it. Only content
// saves (persistContent) and fresh page loads may move the version map.
return res
}
const createPage = async () => {
if (activePage.current && !await autosave.flush(activePage.current)) return
const res = await fetch('/api/pages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: nextUntitledTitle(pages.map((p) => p.title)) }) })
if (!res.ok) { toast.error('Could not create page'); return }
const p = await res.json()
await loadPages()
notify()
setMode('edit')
select(p.id)
}
const onContentChange = (v: string) => {
if (!page || page.id !== activeId) return
setContent(v)
autosave.edit(page.id, v)
}
// Show the block menu only while the caret sits on a bare "/token" line.
const updateSlash = (text: string, caret: number) => {
const lineStart = text.lastIndexOf('\n', caret - 1) + 1
const line = text.slice(lineStart, caret)
const m = /^\/([\w-]*)$/.exec(line)
if (m) { setSlash({ query: m[1].toLowerCase(), start: lineStart }); setSlashIndex(0) }
else setSlash(null)
}
const slashFiltered = SLASH_BLOCKS.filter((b) => !slash?.query || b.key.includes(slash.query) || b.label.toLowerCase().includes(slash.query))
const applyBlock = (block: (typeof SLASH_BLOCKS)[number]) => {
const ta = textareaRef.current
if (!slash || !ta) return
const caret = ta.selectionStart
const next = content.slice(0, slash.start) + block.prefix + content.slice(caret)
pendingCaret.current = slash.start + block.prefix.length
onContentChange(next)
setSlash(null)
}
// Restore the caret after a programmatic content rewrite (slash insert,
// "[] " shortcut). Runs once the new content has reached the textarea.
useEffect(() => {
if (pendingCaret.current === null || mode !== 'edit') return
const ta = textareaRef.current
if (!ta) return
const c = pendingCaret.current
pendingCaret.current = null
ta.focus()
ta.setSelectionRange(c, c)
}, [content, mode])
const saveTitle = async () => {
if (!page) return
const t = title.trim()
// Keep the generated "Untitled N" name until the user gives a real one.
if (!t) { setTitle(page.title); return }
if (t === page.title) return
if (await patch({ title: t })) {
setPage(current => current?.id === page.id ? { ...current, title: t } : current)
notifyActivePage(t)
await loadPages(); notify()
}
}
const togglePin = async () => {
if (!page) return
if (await patch({ pinned: !page.pinned })) {
setPage(current => current?.id === page.id ? { ...current, pinned: !page.pinned } : current)
await loadPages(); notify()
}
}
const move = async (dir: -1 | 1) => {
if (!activeId) return
const idx = pages.findIndex((p) => p.id === activeId)
const target = pages[idx + dir]
if (idx < 0 || !target) return
const next = reorderPages(pages, activeId, target.id, dir > 0)
if (next === 'blocked') { toast.error('Pinned and unpinned pages keep separate groups'); return }
if (next) await savePageOrder(next)
}
const savePageOrder = async (next: PageSummary[]) => {
setPages(next)
const res = await fetch('/api/pages', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ order: next.map((p) => p.id) }) })
if (!res.ok) { toast.error('Could not reorder pages'); await loadPages(); return }
await loadPages()
notify()
}
const dropTab = (target: PageSummary, after: boolean) => {
const source = draggedTabRef.current
draggedTabRef.current = null
setTabDrop(null)
if (!source) return
const next = reorderPages(pages, source, target.id, after)
if (next === 'blocked') { toast.error('Pinned and unpinned pages keep separate groups'); return }
if (next) void savePageOrder(next)
}
const download = async () => {
if (!activeId) return
// A paused conflict can never flush; exporting the server copy is still
// useful, so only ordinary save failures block the download.
if (autosave.conflictVersion(activeId) === null && !await autosave.flush(activeId)) return
const a = document.createElement('a')
a.href = `/api/pages/${activeId}/markdown`
a.download = ''
document.body.appendChild(a); a.click(); a.remove()
}
// Explicit conflict resolutions (review DATA-04). Typing is never consent;
// each path is a deliberate click.
const overwriteRemote = async () => {
if (!activeId) return
if (await autosave.resolveOverwrite(activeId)) toast.success('Your draft replaced the newer version')
else toast.error('Could not save page. Your draft is kept in this tab; retry saving.')
}
const discardDraft = async () => {
if (!activeId) return
autosave.discard(activeId)
await loadPage(activeId)
}
const copyDraft = async () => {
const res = await fetch('/api/pages', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: `${page?.title ?? 'Untitled'} (draft copy)`, content }),
})
if (!res.ok) { toast.error('Could not create the copy'); return }
toast.success('Draft copied to a new page')
await loadPages(); notify()
}
const remove = async () => {
if (!page || !confirm(`Delete page "${page.title}"? Bookmarks are kept.`)) return
if (!await autosave.flush(page.id)) return
const res = await fetch(`/api/pages/${page.id}`, { method: 'DELETE' })
if (!res.ok) { toast.error('Could not delete page'); return }
autosave.forget(page.id)
const data = await loadPages(); notify()
if (data.length) select(data[0].id)
else { activePage.current = null; setActiveId(null); router.replace('/pages') }
}
useEffect(() => {
if (!linkOpen) return
const q = linkQuery.trim()
const t = setTimeout(async () => {
try {
const params = new URLSearchParams({ limit: '8' })
if (q) params.set('search', q)
const res = await fetch(`/api/bookmarks?${params}`)
if (res.ok) setResults((await res.json()).slice(0, 8))
} catch { /* transient; retried on next keystroke */ }
}, 250)
return () => clearTimeout(t)
}, [linkQuery, linkOpen])
const addBookmark = async (bookmarkId: string) => {
if (activeId && !await autosave.flush(activeId)) return
if (await patch({ addBookmarkId: bookmarkId })) {
setLinkOpen(false); setLinkQuery('')
if (activeId) await loadPage(activeId)
await loadPages()
}
}
const addUrl = async () => {
let url = linkQuery.trim()
if (!url) return
if (!/^https?:\/\//i.test(url)) url = `https://${url}`
const res = await fetch('/api/bookmarks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url }) })
if (!res.ok) { toast.error('Could not save URL'); return }
const b = await res.json()
await addBookmark(b.id)
toast.success('Link added')
}
const removeBookmark = async (bookmarkId: string) => {
if (await patch({ removeBookmarkId: bookmarkId })) {
if (page) setPage({ ...page, bookmarks: page.bookmarks.filter((x) => x.bookmark.id !== bookmarkId) })
await loadPages()
}
}
// Notion-style paste: a bare URL lands in the textarea untouched, and once
// its preview resolves we offer to upgrade it to a titled Markdown link.
// Nothing is rewritten without an explicit click, so undo stays intact.
const offerTitleForPastedUrl = (url: string) => {
void fetchLinkPreview(url).then((p) => {
const raw = p?.ogTitle || p?.title
if (!raw) return
const title = raw.replace(/[\[\]\n]/g, ' ').trim()
if (!title || title === url) return
toast.info('Paste as titled link?', {
description: title,
duration: 10000,
action: {
label: 'Use title',
onClick: () => {
const ta = textareaRef.current
if (!ta) return
const idx = ta.value.indexOf(url)
if (idx < 0) return
const markdown = `[${title}](${url})`
pendingCaret.current = idx + markdown.length
onContentChange(ta.value.slice(0, idx) + markdown + ta.value.slice(idx + url.length))
},
},
})
})
}
const onPaste = (e: ClipboardEvent<HTMLTextAreaElement>) => {
const text = e.clipboardData.getData('text/plain').trim()
if (/^https?:\/\/\S+$/i.test(text)) offerTitleForPastedUrl(text)
}
const visible = pages.filter((p) => p.title.toLowerCase().includes(filter.toLowerCase()))
const looksLikeUrl = /^(https?:\/\/)?[\w-]+(\.[\w-]+)+/i.test(linkQuery.trim())
return (
<div className="flex h-full flex-col">
<div className="flex items-center gap-2 border-b border-border/60 px-4 py-2">
<div className="relative w-40 shrink-0">
<Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<Input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Filter pages" className="h-8 pl-7 text-sm" />
</div>
<div className="flex flex-1 items-center gap-1 overflow-x-auto">
{visible.map((p) => (
<div
key={p.id}
data-page-tab={p.id}
onDragOver={(e) => {
if (!draggedTabRef.current || draggedTabRef.current === p.id) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
const rect = e.currentTarget.getBoundingClientRect()
setTabDrop({ id: p.id, after: e.clientX > rect.left + rect.width / 2 })
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setTabDrop(null)
}}
onDrop={(e) => {
e.preventDefault()
const rect = e.currentTarget.getBoundingClientRect()
dropTab(p, e.clientX > rect.left + rect.width / 2)
}}
title={filter.trim() ? 'Clear the filter to reorder pages' : 'Drag the grip to reorder page'}
className={cn(
'group/tab flex shrink-0 items-center gap-1 rounded-md px-2 py-1.5 text-sm transition-colors',
p.id === activeId ? 'bg-primary/10 font-medium text-primary' : 'text-muted-foreground hover:bg-muted hover:text-foreground',
tabDrop?.id === p.id && 'ring-1 ring-primary/50',
)}
>
{!filter.trim() && (
<span
data-page-tab-drag
draggable
onDragStart={(e) => {
suppressTabClick.current = true
draggedTabRef.current = p.id
e.dataTransfer.effectAllowed = 'move'
e.dataTransfer.setData('text/plain', p.id)
}}
onDragEnd={() => {
draggedTabRef.current = null
setTabDrop(null)
setTimeout(() => { suppressTabClick.current = false }, 0)
}}
className="cursor-grab text-muted-foreground/40 opacity-0 transition-opacity hover:text-muted-foreground active:cursor-grabbing group-hover/tab:opacity-100"
aria-label={`Drag page ${p.title}`}
>
<GripVertical className="h-3 w-3" />
</span>
)}
<button
type="button"
onClick={() => { if (!suppressTabClick.current) select(p.id) }}
aria-label={p.title}
className="flex min-w-0 items-center gap-1.5"
>
{p.pinned ? <Pin className="h-3 w-3" /> : <FileText className="h-3 w-3" />}
<span className="max-w-[10rem] truncate">{p.title}</span>
</button>
</div>
))}
</div>
<Button size="sm" onClick={createPage}><Plus className="mr-1 h-4 w-4" />New page</Button>
</div>
{!page || page.id !== activeId ? (
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-10 text-center">
<FileText className="h-10 w-10 text-muted-foreground" />
<h2 className="font-display text-xl font-semibold">{pages.length ? 'Select a page' : 'No pages yet'}</h2>
<p className="max-w-sm text-sm text-muted-foreground">Pages are Markdown notes that collect links into a workspace. A bookmark can live on many pages.</p>
<Button onClick={createPage}><Plus className="mr-1 h-4 w-4" />Create a page</Button>
</div>
) : (
<div className="mx-auto w-full max-w-4xl flex-1 overflow-y-auto px-6 py-8">
<div className="mb-6 flex flex-wrap items-center gap-2">
<input value={title} onChange={(e) => setTitle(e.target.value)} onBlur={saveTitle} onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()} className="min-w-0 flex-1 bg-transparent font-display text-3xl font-bold outline-none" aria-label="Page title" />
<span className="text-xs text-muted-foreground">{saveState === 'saving' ? 'Saving…' : saveState === 'dirty' ? 'Unsaved' : saveState === 'conflict' ? 'Conflict' : 'Saved'}</span>
{saveState === 'dirty' && <Button size="sm" variant="outline" onClick={() => autosave.flush(page.id)}>Save now</Button>}
<Button variant="ghost" size="icon-sm" title={mode === 'edit' ? 'Preview' : 'Edit'} onClick={() => { setMode(mode === 'edit' ? 'preview' : 'edit'); setSlash(null) }}>{mode === 'edit' ? <Eye className="h-4 w-4" /> : <Pencil className="h-4 w-4" />}</Button>
<Button variant="ghost" size="icon-sm" title={page.pinned ? 'Unpin' : 'Pin to sidebar'} onClick={togglePin}>{page.pinned ? <PinOff className="h-4 w-4" /> : <Pin className="h-4 w-4" />}</Button>
<Button variant="ghost" size="icon-sm" title="Move tab left" onClick={() => move(-1)}><ChevronLeft className="h-4 w-4" /></Button>
<Button variant="ghost" size="icon-sm" title="Move tab right" onClick={() => move(1)}><ChevronRight className="h-4 w-4" /></Button>
<Button variant="ghost" size="icon-sm" title="Download .md" onClick={download}><Download className="h-4 w-4" /></Button>
<Button variant="ghost" size="icon-sm" title="Delete page" onClick={remove}><Trash2 className="h-4 w-4 text-destructive" /></Button>
</div>
{saveState === 'conflict' && (
<div role="alert" className="mb-4 rounded-lg border border-destructive/40 bg-destructive/5 p-4 text-sm">
<p className="font-medium text-foreground">This page was changed elsewhere</p>
<p className="mt-1 text-muted-foreground">
Your local draft is based on an older version — or its base version is unknown —
so autosave is paused and nothing is overwritten until you choose. Your draft
stays in the editor below.
</p>
<div className="mt-3 flex flex-wrap gap-2">
<Button size="sm" variant="destructive" onClick={overwriteRemote}>Overwrite with my draft</Button>
<Button size="sm" variant="outline" onClick={copyDraft}>Save my draft as a new page</Button>
<Button size="sm" variant="outline" onClick={discardDraft}>Discard my draft and load latest</Button>
</div>
</div>
)}
{mode === 'edit' ? (
<div className="relative">
<Textarea
ref={textareaRef}
value={content}
onChange={(e) => { onContentChange(e.target.value); updateSlash(e.target.value, e.target.selectionStart) }}
onClick={(e) => updateSlash(e.currentTarget.value, e.currentTarget.selectionStart)}
onPaste={onPaste}
onBlur={() => setSlash(null)}
onKeyDown={(e) => {
// While the slash menu is open, arrows/Enter/Tab/Escape drive it.
if (slash && slashFiltered.length > 0) {
if (e.key === 'ArrowDown') { e.preventDefault(); setSlashIndex((i) => (i + 1) % slashFiltered.length); return }
if (e.key === 'ArrowUp') { e.preventDefault(); setSlashIndex((i) => (i - 1 + slashFiltered.length) % slashFiltered.length); return }
if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); applyBlock(slashFiltered[Math.min(slashIndex, slashFiltered.length - 1)]); return }
if (e.key === 'Escape') { e.preventDefault(); setSlash(null); return }
}
// Notion Markdown shortcut: "[]" + space becomes a to-do item.
if (e.key === ' ') {
const ta = e.currentTarget
const caret = ta.selectionStart
const lineStart = ta.value.lastIndexOf('\n', caret - 1) + 1
if (ta.value.slice(lineStart, caret) === '[]') {
e.preventDefault()
const next = ta.value.slice(0, lineStart) + '- [ ] ' + ta.value.slice(caret)
pendingCaret.current = lineStart + '- [ ] '.length
onContentChange(next)
}
}
}}
placeholder="Write Markdown notes… type / for blocks, paste links, lists, thoughts."
className="min-h-[260px] font-mono text-sm"
/>
{slash && slashFiltered.length > 0 && (
<div
onMouseDown={(e) => e.preventDefault()}
role="listbox"
aria-label="Blocks to insert"
className="absolute left-2 top-full z-20 mt-1 w-72 rounded-lg border bg-popover p-1 shadow-lg"
>
<p className="px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">Basic blocks</p>
<div className="max-h-64 overflow-y-auto">
{slashFiltered.map((b, i) => (
<button
key={b.key}
type="button"
role="option"
aria-selected={i === slashIndex}
onMouseEnter={() => setSlashIndex(i)}
onClick={() => applyBlock(b)}
className={cn('flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-left', i === slashIndex ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50')}
>
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded border bg-card">
<b.icon className="h-3.5 w-3.5 text-muted-foreground" />
</span>
<span className="min-w-0">
<span className="block text-sm font-medium">{b.label}</span>
<span className="block truncate text-xs text-muted-foreground">{b.desc}</span>
</span>
</button>
))}
</div>
</div>
)}
</div>
) : (
<div className="prose prose-sm max-w-none dark:prose-invert min-h-[80px] cursor-text" onDoubleClick={() => setMode('edit')}>
{content ? (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
p: ({ node, ...props }) => {
const link = standaloneLink(node)
return link ? (
<LinkPreviewCard url={link.href} label={link.label !== link.href ? link.label : undefined} />
) : (
<p {...props} />
)
},
a: ({ node, ...props }) => <a {...props} target="_blank" rel="noopener noreferrer" />,
}}
>{content}</ReactMarkdown>
) : (
<p className="text-muted-foreground">No notes yet. Double-click or press the pencil to write.</p>
)}
</div>
)}
<div className="mt-10 mb-3 flex items-center justify-between">
<h3 className="font-display text-lg font-semibold">Links on this page <span className="text-sm font-normal text-muted-foreground">({page.bookmarks.length})</span></h3>
<Popover open={linkOpen} onOpenChange={setLinkOpen}>
<PopoverTrigger asChild><Button size="sm" variant="outline"><Link2 className="mr-1 h-4 w-4" />Add link</Button></PopoverTrigger>
<PopoverContent align="end" className="w-80 p-2">
<Input autoFocus value={linkQuery} onChange={(e) => setLinkQuery(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && looksLikeUrl && addUrl()} placeholder="Search bookmarks or paste a URL" className="h-8 text-sm" />
<div className="mt-2 max-h-64 overflow-y-auto">
{looksLikeUrl && (
<button onClick={addUrl} className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm hover:bg-muted"><Plus className="h-3.5 w-3.5" />Save &amp; add “{linkQuery.trim()}”</button>
)}
{results.filter((r) => !page.bookmarks.some((x) => x.bookmark.id === r.id)).map((r) => (
<button key={r.id} onClick={() => addBookmark(r.id)} className="flex w-full flex-col rounded px-2 py-1.5 text-left hover:bg-muted">
<span className="truncate text-sm">{r.title || r.ogTitle || r.url}</span>
<span className="truncate text-xs text-muted-foreground">{host(r.url)}</span>
</button>
))}
{!looksLikeUrl && results.length === 0 && <p className="px-2 py-3 text-center text-xs text-muted-foreground">No matching bookmarks</p>}
</div>
</PopoverContent>
</Popover>
</div>
{page.bookmarks.length === 0 ? (
<div className="rounded-lg bg-muted/40 p-8 text-center text-sm text-muted-foreground">No links yet. Add existing bookmarks or paste a new URL.</div>
) : (
<div className="grid gap-3 sm:grid-cols-2">
{page.bookmarks.map(({ bookmark: b }) => (
<div key={b.id} className="group relative flex gap-3 rounded-lg bg-card p-3 shadow-sm ring-1 ring-border/50 transition-shadow hover:shadow-md">
{b.ogImage ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={b.ogImage} alt={`Preview of ${b.title || host(b.url)}`} referrerPolicy="no-referrer" className="h-16 w-24 shrink-0 rounded object-cover bg-muted" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }} />
) : null}
<a href={b.url} target="_blank" rel="noopener noreferrer" className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
{b.favicon && (
// eslint-disable-next-line @next/next/no-img-element
<img src={b.favicon} alt="" referrerPolicy="no-referrer" className="h-3.5 w-3.5" onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }} />
)}
<span className="truncate text-sm font-medium">{b.title || b.ogTitle || b.url}</span>
</div>
<p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">{b.description || b.ogDescription || ''}</p>
<p className="mt-1 text-[11px] text-muted-foreground/80">{host(b.url)}</p>
</a>
<button onClick={() => removeBookmark(b.id)} title="Remove from page" className="absolute right-1.5 top-1.5 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-muted group-hover:opacity-100"><X className="h-3.5 w-3.5" /></button>
</div>
))}
</div>
)}
</div>
)}
</div>
)
}
+6
View File
@@ -0,0 +1,6 @@
import { PagesClient } from './client'
export default async function PagesPage({ searchParams }: { searchParams: Promise<{ id?: string }> }) {
const { id } = await searchParams
return <PagesClient initialId={id ?? null} />
}
+205
View File
@@ -0,0 +1,205 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { useSession } from 'next-auth/react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { User, Mail, Server, Cloud, Shield, Check, X, AlertTriangle } from 'lucide-react'
import { toast } from 'sonner'
import { invalidateReference } from '@/lib/reference-data'
import type { OidcStatus } from '@/lib/oidc-config'
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
const { data: session } = useSession()
const [imapConfig, setImapConfig] = useState({ host: '', port: 993, tls: true, username: '', password: '', folder: 'INBOX' })
const [ncConfig, setNcConfig] = useState({ nextcloudUrl: '', cardDavPath: '', username: '', password: '' })
const [savingImap, setSavingImap] = useState(false)
const [testingImap, setTestingImap] = useState(false)
const [syncingContacts, setSyncingContacts] = useState(false)
useEffect(() => {
fetch('/api/settings/imap').then(r => r.json()).then(data => {
if (data) setImapConfig(prev => ({ ...prev, host: data.host ?? '', port: data.port ?? 993, tls: data.tls ?? true, username: data.username ?? '', folder: data.folder ?? 'INBOX' }))
}).catch(() => {})
}, [])
// Every action clears its spinner in finally and tolerates non-JSON or
// failed network responses, so no state can stick after an outage.
const saveImap = async () => {
setSavingImap(true)
try {
const res = await fetch('/api/settings/imap', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
// tls is forced on: legacy stored configs with tls=false migrate to
// verified TLS on the next save (review NET-02).
body: JSON.stringify({ ...imapConfig, tls: true }),
})
if (res.ok) toast.success('IMAP settings saved')
else toast.error((await res.json().catch(() => null))?.error ?? 'Failed to save')
} catch { toast.error('Failed to save') }
finally { setSavingImap(false) }
}
const testImap = async () => {
setTestingImap(true)
try {
const res = await fetch('/api/imap/test', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...imapConfig, tls: true }),
})
const data = await res.json().catch(() => null)
if (res.ok && data?.ok) toast.success('Connection successful!')
else toast.error(data?.error ?? 'Connection failed')
} catch { toast.error('Connection failed') }
finally { setTestingImap(false) }
}
const syncContacts = async () => {
if (!ncConfig.nextcloudUrl || !ncConfig.username || !ncConfig.password) {
toast.error('Fill in Nextcloud URL, username, and password')
return
}
setSyncingContacts(true)
try {
const res = await fetch('/api/contacts/sync', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(ncConfig),
})
const data = await res.json().catch(() => null)
if (res.ok && data?.synced !== undefined) {
// Review CR-07: the sync mirrors the address book — remotely deleted
// contacts are removed too (scoped to this source, never from partial
// responses). Surface both counts so the policy is visible.
const removed = typeof data.removed === 'number' && data.removed > 0 ? `, removed ${data.removed} deleted on the server` : ''
toast.success(`Synced ${data.synced} contacts${removed}`)
invalidateReference('contacts')
}
else toast.error(data?.error ?? 'Sync failed')
} catch { toast.error('Sync failed') }
finally { setSyncingContacts(false) }
}
return (
<div className="max-w-2xl space-y-6">
<div>
<h1 className="font-display text-2xl font-bold tracking-tight">Settings</h1>
<p className="text-sm text-muted-foreground mt-1">Configure your integrations and preferences</p>
</div>
<Tabs defaultValue="profile" className="w-full">
<TabsList className="w-full justify-start">
<TabsTrigger value="profile" className="gap-1.5"><User className="h-3.5 w-3.5" /> Profile</TabsTrigger>
<TabsTrigger value="imap" className="gap-1.5"><Mail className="h-3.5 w-3.5" /> IMAP</TabsTrigger>
<TabsTrigger value="nextcloud" className="gap-1.5"><Cloud className="h-3.5 w-3.5" /> Nextcloud</TabsTrigger>
<TabsTrigger value="oidc" className="gap-1.5"><Shield className="h-3.5 w-3.5" /> OIDC</TabsTrigger>
</TabsList>
<TabsContent value="profile" className="space-y-4 mt-4">
<div className="flex items-center gap-4">
<div className="h-16 w-16 rounded-full bg-primary/20 flex items-center justify-center text-2xl font-bold text-primary">
{(session?.user?.name ?? session?.user?.email ?? '?')[0]?.toUpperCase()}
</div>
<div>
<p className="font-medium">{session?.user?.name ?? 'User'}</p>
<p className="text-sm text-muted-foreground" suppressHydrationWarning>{session?.user?.email}</p>
</div>
</div>
</TabsContent>
<TabsContent value="imap" className="space-y-4 mt-4">
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium flex items-center gap-2"><Server className="h-4 w-4" /> IMAP Configuration</h3>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs font-medium text-muted-foreground">Host</label>
<Input value={imapConfig.host} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, host: e.target.value }))} placeholder="imap.example.com" />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Port</label>
<Input type="number" value={imapConfig.port} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, port: parseInt(e.target.value) || 993 }))} />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Username</label>
<Input value={imapConfig.username} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, username: e.target.value }))} />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Password</label>
<Input type="password" value={imapConfig.password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, password: e.target.value }))} />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Folder</label>
<Input value={imapConfig.folder} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapConfig(p => ({ ...p, folder: e.target.value }))} />
</div>
<div className="flex items-end">
{/* Review NET-02: mailbox logins always run over verified TLS;
the backend rejects insecure settings, so there is no toggle. */}
<p className="text-sm text-muted-foreground">TLS is required (implicit TLS, port 993 by default)</p>
</div>
</div>
<div className="flex gap-2">
<Button onClick={testImap} variant="outline" loading={testingImap}>Test Connection</Button>
<Button onClick={saveImap} loading={savingImap}>Save IMAP Settings</Button>
</div>
</div>
</TabsContent>
<TabsContent value="nextcloud" className="space-y-4 mt-4">
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium flex items-center gap-2"><Cloud className="h-4 w-4" /> Nextcloud / CardDAV</h3>
<div className="grid grid-cols-2 gap-3">
<div className="col-span-2">
<label className="text-xs font-medium text-muted-foreground">Nextcloud URL</label>
<Input value={ncConfig.nextcloudUrl} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, nextcloudUrl: e.target.value }))} placeholder="https://nextcloud.example.com" />
</div>
<div className="col-span-2">
<label className="text-xs font-medium text-muted-foreground">CardDAV Path (optional)</label>
<Input value={ncConfig.cardDavPath} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, cardDavPath: e.target.value }))} placeholder="/remote.php/dav/addressbooks/users/USER/contacts/" />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Username</label>
<Input value={ncConfig.username} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, username: e.target.value }))} />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">App Password</label>
<Input type="password" value={ncConfig.password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNcConfig(p => ({ ...p, password: e.target.value }))} />
</div>
</div>
<Button onClick={syncContacts} loading={syncingContacts}>Sync Contacts Now</Button>
</div>
</TabsContent>
<TabsContent value="oidc" className="space-y-4 mt-4">
<div className="rounded-lg border p-4 space-y-3">
<h3 className="font-medium flex items-center gap-2"><Shield className="h-4 w-4" /> OIDC Configuration</h3>
<p className="text-sm text-muted-foreground">Authelia single sign-on, configured via environment variables (read-only)</p>
<div className={`flex items-start gap-2 rounded-md p-3 text-sm ${oidc.enabled ? 'bg-green-500/10 text-green-700 dark:text-green-400' : 'bg-amber-500/10 text-amber-800 dark:text-amber-300'}`}>
{oidc.enabled ? <Check className="h-4 w-4 mt-0.5 shrink-0" /> : <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />}
<span>
{oidc.enabled
? <>Configured for <span className="font-mono break-all">{oidc.issuer}</span>. Client integration is still pending.</>
: <>Not connected. Authelia sign-in is disabled until all three variables below hold real values. Users can sign in with email and password meanwhile. Setup guide: <span className="font-mono">docs/AUTHELIA.md</span></>}
</span>
</div>
<div className="space-y-2">
{([['OIDC_ISSUER', oidc.issuerSet], ['OIDC_CLIENT_ID', oidc.clientIdSet], ['OIDC_CLIENT_SECRET', oidc.clientSecretSet]] as const).map(([name, set]) => (
<div key={name} className="flex items-center gap-2">
<span className="text-xs font-mono bg-muted px-2 py-1 rounded">{name}</span>
<span className="text-sm text-muted-foreground">{set ? 'Set' : 'Not set'}</span>
{set ? <Check className="h-4 w-4 text-green-500" /> : <X className="h-4 w-4 text-muted-foreground" />}
</div>
))}
</div>
<div className="space-y-1 pt-2 border-t">
<p className="text-xs font-medium text-muted-foreground">Redirect URI to register in Authelia</p>
<p className="text-xs font-mono bg-muted px-2 py-1.5 rounded break-all" suppressHydrationWarning>{callbackUrl}</p>
</div>
</div>
</TabsContent>
</Tabs>
</div>
)
}
+24
View File
@@ -0,0 +1,24 @@
import { SettingsClient } from './client'
import { getOidcStatus } from '@/lib/oidc-config'
import { headers } from 'next/headers'
export const dynamic = 'force-dynamic'
export default async function SettingsPage() {
// The redirect URI shown for Authelia registration derives from the same
// configured origin auth.ts trusts — never from client-controllable request
// headers in production (header poisoning could hand an admin an
// attacker-hosted callback URL to register).
const envUrl = process.env.NEXTAUTH_URL || process.env.AUTH_URL || ''
let callbackUrl = '/api/auth/callback/authelia'
try {
if (envUrl) callbackUrl = `${new URL(envUrl).origin}/api/auth/callback/authelia`
} catch { /* keep the relative fallback */ }
if (!envUrl && process.env.NODE_ENV !== 'production') {
const h = await headers()
const host = h.get('x-forwarded-host') ?? h.get('host') ?? ''
const proto = h.get('x-forwarded-proto') ?? 'http'
if (host) callbackUrl = `${proto}://${host}/api/auth/callback/authelia`
}
return <SettingsClient oidc={getOidcStatus()} callbackUrl={callbackUrl} />
}
+170
View File
@@ -0,0 +1,170 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { BookmarkCard } from '@/components/bookmark-card'
import { BookmarkDetailSheet } from '@/components/bookmark-detail-sheet'
import { Plus, Tags, Trash2, Edit, Check, X } from 'lucide-react'
import { toast } from 'sonner'
import type { Bookmark, TagWithCount } from '@/components/app-shell'
import { fetchBookmarks } from '@/lib/bookmarks'
import { invalidateReference } from '@/lib/reference-data'
export function TagsClient({ initialTag = null }: { initialTag?: string | null }) {
const [tags, setTags] = useState<TagWithCount[]>([])
const [selectedTag, setSelectedTag] = useState<string | null>(null)
const [bookmarks, setBookmarks] = useState<Bookmark[]>([])
const [selectedBookmark, setSelectedBookmark] = useState<Bookmark | null>(null)
const [newName, setNewName] = useState('')
const [newColor, setNewColor] = useState('#6366f1')
const [editingId, setEditingId] = useState<string | null>(null)
const [editName, setEditName] = useState('')
const [editColor, setEditColor] = useState('#6366f1')
const [loading, setLoading] = useState(true)
const [effectiveId, setEffectiveId] = useState('')
const [shareQuery, setShareQuery] = useState('')
const [shareUsers, setShareUsers] = useState<any[]>([])
useEffect(() => { fetch('/api/me').then(r => r.json()).then(me => setEffectiveId(me.effectiveUser?.id || '')).catch(() => {}) }, [])
// Debounced user search; failures keep the previous results silently.
useEffect(() => {
const q = shareQuery.trim()
const t = setTimeout(async () => {
if (q.length < 2) { setShareUsers([]); return }
try {
const res = await fetch(`/api/users/search?q=${encodeURIComponent(q)}`)
if (res.ok) setShareUsers(await res.json())
} catch { /* transient; retried on next keystroke */ }
}, q.length < 2 ? 0 : 250)
return () => clearTimeout(t)
}, [shareQuery])
const loadTags = useCallback(async () => {
// Every tag mutation reloads through here; keep the detail sheet's cache
// in step so new/renamed tags appear in its picker immediately.
invalidateReference('tags')
try {
const res = await fetch('/api/tags')
if (res.ok) setTags(await res.json())
} catch { toast.error('Could not load tags') }
}, [])
const loadBookmarks = useCallback(async (tagId: string) => {
setLoading(true)
try { setBookmarks(await fetchBookmarks(new URLSearchParams({ tagId }))) }
catch { toast.error('Could not load bookmarks') }
finally { setLoading(false) }
}, [])
useEffect(() => { const timer = setTimeout(loadTags, 0); return () => clearTimeout(timer) }, [loadTags])
// Quick Find deep-links to a tag via /tags?tag=<id>.
useEffect(() => {
if (!initialTag) return
const timer = setTimeout(() => setSelectedTag(initialTag), 0)
return () => clearTimeout(timer)
}, [initialTag])
useEffect(() => { const timer = setTimeout(() => { if (selectedTag) loadBookmarks(selectedTag) }, 0); return () => clearTimeout(timer) }, [selectedTag, loadBookmarks])
useEffect(() => { const reload = () => { loadTags(); if (selectedTag) loadBookmarks(selectedTag) }; window.addEventListener('computer:bookmarks-changed', reload); return () => window.removeEventListener('computer:bookmarks-changed', reload) }, [loadTags, loadBookmarks, selectedTag])
const createTag = async () => {
if (!newName) return
const res = await fetch('/api/tags', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: newName, color: newColor }) })
if (res.ok) { toast.success('Tag created'); setNewName(''); loadTags() }
else toast.error('Failed')
}
const updateTag = async (id: string) => {
const response = await fetch(`/api/tags/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: editName, color: editColor }) })
if (!response.ok) { toast.error('Could not update tag'); return }
setEditingId(null)
loadTags()
}
const deleteTag = async (id: string) => {
if (!confirm('Delete this tag?')) return
const response = await fetch(`/api/tags/${id}`, { method: 'DELETE' })
if (!response.ok) { toast.error('Could not delete tag'); return }
toast.success('Tag deleted')
if (selectedTag === id) setSelectedTag(null)
loadTags()
}
return (
<div className="flex gap-6 h-[calc(100vh-120px)]">
<div className="w-64 shrink-0 space-y-4 overflow-y-auto">
<h1 className="font-display text-2xl font-bold tracking-tight">Tags</h1>
<div className="flex gap-1.5">
<Input placeholder="New tag" value={newName} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNewName(e.target.value)} className="flex-1" />
<input type="color" value={newColor} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNewColor(e.target.value)} className="h-9 w-9 rounded border cursor-pointer" />
<Button size="icon-sm" onClick={createTag}><Plus className="h-4 w-4" /></Button>
</div>
<div className="space-y-1">
{tags.map((t: TagWithCount) => (
<div
key={t.id}
role="button"
tabIndex={0}
aria-pressed={selectedTag === t.id}
className={`flex items-center gap-2 rounded-lg px-3 py-2 cursor-pointer transition-colors focus-visible:outline-2 focus-visible:outline-primary ${
selectedTag === t.id ? 'bg-accent' : 'hover:bg-muted'
}`}
onClick={() => setSelectedTag(t.id)}
onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setSelectedTag(t.id) } }}
>
{editingId === t.id ? (
<>
<input type="color" value={editColor} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEditColor(e.target.value)} className="h-5 w-5 rounded cursor-pointer" />
<Input value={editName} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEditName(e.target.value)} className="h-7 text-xs flex-1" />
<button onClick={() => updateTag(t.id)}><Check className="h-3 w-3 text-green-500" /></button>
<button onClick={() => setEditingId(null)}><X className="h-3 w-3" /></button>
</>
) : (
<>
<div className="h-3 w-3 rounded-full shrink-0" style={{ backgroundColor: t.color }} />
<span className="text-sm font-medium flex-1 truncate">{t.name}</span>
<span className="text-xs text-muted-foreground">{t._count?.bookmarks ?? 0}</span>
{t.ownerId === effectiveId ? <><button aria-label="Edit tag" onClick={(e: React.MouseEvent) => { e.stopPropagation(); setEditingId(t.id); setEditName(t.name); setEditColor(t.color) }}><Edit className="h-3 w-3 text-muted-foreground" /></button>
<button aria-label="Delete tag" onClick={(e: React.MouseEvent) => { e.stopPropagation(); deleteTag(t.id) }}><Trash2 className="h-3 w-3 text-muted-foreground hover:text-destructive" /></button></> : <span className="text-xs text-muted-foreground">Shared</span>}
</>
)}
</div>
))}
</div>
</div>
<div className="flex-1 overflow-y-auto">
{selectedTag ? (
<div className="space-y-4">
<h2 className="font-medium">Bookmarks tagged: <Badge style={{ backgroundColor: `${tags.find(t => t.id === selectedTag)?.color ?? '#6366f1'}20`, color: tags.find(t => t.id === selectedTag)?.color }}>{tags.find(t => t.id === selectedTag)?.name}</Badge></h2>
{tags.find(t => t.id === selectedTag)?.ownerId === effectiveId && <div className="space-y-2 rounded border p-3">
<p className="text-xs text-muted-foreground">Sharing is group-wide: every recipient can see all bookmarks under this tag — including ones other recipients add.</p>
<Input placeholder="Share this tag with a user…" value={shareQuery} onChange={e => setShareQuery(e.target.value)} />
{shareUsers.map(u => <Button key={u.id} size="sm" variant="outline" onClick={async () => { const res = await fetch(`/api/tags/${selectedTag}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ shareUserIds: [u.id] }) }); if (!res.ok) { toast.error('Could not share tag'); return } toast.success('Tag shared'); setShareUsers([]); setShareQuery(''); loadTags() }}>Share with {u.name || u.email}</Button>)}
{(tags.find(t => t.id === selectedTag)?.sharedWith || []).map(share => <Button key={share.userId} size="xs" variant="ghost" onClick={async () => { const res = await fetch(`/api/tags/${selectedTag}/share/${share.userId}`, { method: 'DELETE' }); if (!res.ok) { toast.error('Could not stop sharing'); return } loadTags() }}>Stop sharing with {share.user?.name || share.user?.email || `${share.userId.slice(0, 8)}…`}</Button>)}
</div>}
{loading ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => <div key={i} className="h-32 rounded-lg bg-muted animate-pulse" />)}
</div>
) : bookmarks.length === 0 ? (
<p className="text-sm text-muted-foreground py-8 text-center">No bookmarks with this tag</p>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
{bookmarks.map((b: Bookmark) => <BookmarkCard key={b.id} bookmark={b} compact onClick={() => setSelectedBookmark(b)} />)}
</div>
)}
</div>
) : (
<div className="flex flex-col items-center justify-center h-full text-center">
<Tags className="h-12 w-12 text-muted-foreground/50 mb-4" />
<p className="text-muted-foreground">Select a tag to view its bookmarks</p>
</div>
)}
</div>
<BookmarkDetailSheet bookmark={selectedBookmark} onClose={() => setSelectedBookmark(null)} onUpdate={() => { if (selectedTag) loadBookmarks(selectedTag) }} />
</div>
)
}
+7
View File
@@ -0,0 +1,7 @@
import { TagsClient } from './client'
// Quick Find deep-links to a tag via /tags?tag=<id>.
export default async function TagsPage({ searchParams }: { searchParams: Promise<{ tag?: string }> }) {
const { tag } = await searchParams
return <TagsClient initialTag={tag ?? null} />
}
+112
View File
@@ -0,0 +1,112 @@
import { NextRequest } from 'next/server'
import { backendFetch, observedClientIP } from '@/lib/api'
export const dynamic = 'force-dynamic'
// Go's handlers cap JSON bodies at 1 MiB (http.MaxBytesReader). Enforce the
// same cap at the proxy boundary (review: frontend proxy body limits) so
// oversized or chunked payloads are rejected here instead of being buffered
// through the Next server first.
const MAX_BODY_BYTES = 1 << 20
// Review CR-14: the cap is enforced WHILE streaming — a chunked body without
// a usable Content-Length is cancelled as soon as it crosses the limit
// instead of being fully buffered first — and concurrent body readers are
// bounded, so oversized-upload floods cannot pile up in memory.
const MAX_CONCURRENT_BODY_READS = 32
let activeBodyReads = 0
// readBodyLimited returns the buffered body, null when it exceeded the cap
// (the reader is cancelled promptly), or 'busy' when too many bodies are
// already being read.
async function readBodyLimited(request: NextRequest): Promise<ArrayBuffer | null | 'busy'> {
if (activeBodyReads >= MAX_CONCURRENT_BODY_READS) return 'busy'
activeBodyReads++
try {
if (!request.body) return new ArrayBuffer(0)
const reader = request.body.getReader()
const chunks: Uint8Array[] = []
let total = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
if (!value) continue
total += value.byteLength
if (total > MAX_BODY_BYTES) {
await reader.cancel().catch(() => { /* already broken */ })
return null
}
chunks.push(value)
}
const out = new Uint8Array(total)
let offset = 0
for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.byteLength }
return out.buffer
} finally {
activeBodyReads--
}
}
async function proxy(request: NextRequest) {
// NextAuth handles its own explicit /api/auth/* route; this catches all data
// routes and preserves JSON, Markdown downloads, statuses and view-as cookies.
const headers = new Headers()
if (request.headers.has('content-type')) headers.set('Content-Type', request.headers.get('content-type')!)
// Review SEC-2: forward the observed browser IP only when TRUSTED_PROXY=1
// pins the boundary that overwrites X-Real-IP (the shipped nginx template
// does). X-Forwarded-For is deliberately ignored: its leftmost entry is
// client-controlled. backendFetch adds the timestamped HMAC signature.
const clientIP = observedClientIP(request.headers)
if (clientIP) headers.set('x-computer-client-ip', clientIP)
if (!['GET', 'HEAD'].includes(request.method)) {
const declared = Number(request.headers.get('content-length') || 0)
if (declared > MAX_BODY_BYTES) {
return Response.json({ error: 'Request body too large' }, { status: 413 })
}
// Defense in depth: the SameSite session cookie is the primary CSRF
// barrier. Origin is checked when present (parsed env origin, so a
// trailing slash or path in NEXTAUTH_URL cannot break the match);
// Sec-Fetch-Site closes the gap for mutated requests whose Origin was
// stripped by an intermediary. An allowlisted origin is deliberately
// permitted even though the browser labels it cross-site.
const origin = request.headers.get('origin')
if (origin) {
const envUrl = process.env.NEXTAUTH_URL || process.env.AUTH_URL
let envOrigin: string | null = null
try { envOrigin = envUrl ? new URL(envUrl).origin : null } catch { envOrigin = null }
if (origin !== request.nextUrl.origin && origin !== envOrigin) {
return Response.json({ error: 'Invalid request origin' }, { status: 403 })
}
} else if (request.headers.get('sec-fetch-site') === 'cross-site') {
return Response.json({ error: 'Invalid request origin' }, { status: 403 })
}
}
try {
let body: ArrayBuffer | undefined
if (!['GET', 'HEAD'].includes(request.method)) {
// Review CR-14: streamed, counted and cancelled at the limit — an
// oversized chunked body without Content-Length never lands fully in
// memory before its 413.
const limited = await readBodyLimited(request)
if (limited === 'busy') {
return Response.json({ error: 'Too many concurrent request bodies' }, { status: 429 })
}
if (limited === null) {
return Response.json({ error: 'Request body too large' }, { status: 413 })
}
body = limited
}
const response = await backendFetch(request.nextUrl.pathname + request.nextUrl.search, {
method: request.method, headers, body,
})
const outgoing = new Headers()
for (const name of ['content-type', 'content-disposition', 'set-cookie', 'x-next-cursor']) {
const value = response.headers.get(name)
if (value) outgoing.set(name, value)
}
outgoing.set('Cache-Control', 'no-store')
return new Response(response.body, { status: response.status, headers: outgoing })
} catch (error) {
console.error('Go API unavailable', error)
return Response.json({ error: 'API unavailable' }, { status: 502 })
}
}
export { proxy as GET, proxy as HEAD, proxy as POST, proxy as PUT, proxy as PATCH, proxy as DELETE }
+3
View File
@@ -0,0 +1,3 @@
export const dynamic = 'force-dynamic'
import { handlers } from '@/auth'
export const { GET, POST } = handlers
+24
View File
@@ -0,0 +1,24 @@
export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'
import { signIn } from '@/auth'
export async function POST(req: Request) {
const expectedOrigin = new URL(process.env.NEXTAUTH_URL || req.url).origin
if (req.headers.get('origin') !== expectedOrigin) {
return NextResponse.json({ error: 'Invalid request origin' }, { status: 403 })
}
if (req.headers.get('content-type')?.split(';')[0].trim().toLowerCase() !== 'application/json') {
return NextResponse.json({ error: 'Content-Type must be application/json' }, { status: 415 })
}
try {
const body = await req.json()
const result = await signIn('credentials', {
email: body.email,
password: body.password,
redirect: false,
})
return NextResponse.json({ ok: true, url: result })
} catch {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 })
}
}
+53
View File
@@ -0,0 +1,53 @@
export const dynamic = 'force-dynamic'
import { NextResponse } from 'next/server'
import jwt from 'jsonwebtoken'
import { auth } from '@/auth'
import { apiBase } from '@/lib/api'
// Review CR-02: "sign out everywhere" is an explicit, observable action.
// The NextAuth signOut event is a fire-and-forget backstop; this route lets
// the UI establish whether Go's global revocation (tokenVersion bump, which
// kills Go cookie sessions and previously minted assertions) actually
// succeeded BEFORE the local session is discarded — so a backend outage
// degrades to an accurate "signed out here, other sessions may remain"
// outcome instead of a silent partial logout. The request is deadline-bound
// and logs without secrets.
export async function POST(req: Request) {
const expectedOrigin = new URL(process.env.NEXTAUTH_URL || req.url).origin
if (req.headers.get('origin') !== expectedOrigin) {
return NextResponse.json({ error: 'Invalid request origin' }, { status: 403 })
}
const session = await auth()
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
const id = typeof session?.user?.id === 'string' ? session.user.id : ''
const ver = typeof session?.user?.ver === 'number' ? session.user.ver : 0
if (!secret || !id || ver < 1) {
// No backend identity attached to this session — nothing to revoke.
return NextResponse.json({ revoked: false, reason: 'no-backend-session' })
}
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), 5000)
try {
const res = await fetch(`${apiBase()}/api/auth/signout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Same short-lived assertion the data proxy signs (lib/api.ts).
Authorization: `Bearer ${jwt.sign({ uid: id, ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'computer', expiresIn: '60s' })}`,
},
cache: 'no-store',
signal: controller.signal,
})
if (!res.ok) {
console.error(`session revoke: Go signout answered ${res.status} for user ${id}`)
return NextResponse.json({ revoked: false, reason: 'backend-error' })
}
return NextResponse.json({ revoked: true })
} catch (error) {
const kind = error instanceof Error ? error.name : 'Error'
console.error(`session revoke: Go signout unreachable for user ${id} (${kind})`)
return NextResponse.json({ revoked: false, reason: 'unreachable' })
} finally {
clearTimeout(timer)
}
}
+104
View File
@@ -0,0 +1,104 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
:root {
--background: 0 0% 100%;
--foreground: 240 10% 3.9%;
--card: 0 0% 100%;
--card-foreground: 240 10% 3.9%;
--popover: 0 0% 100%;
--popover-foreground: 240 10% 3.9%;
--primary: 245 58% 51%;
--primary-foreground: 0 0% 100%;
--secondary: 240 4.8% 95.9%;
--secondary-foreground: 240 5.9% 10%;
--muted: 240 4.8% 95.9%;
--muted-foreground: 240 3.8% 44.1%;
--accent: 245 58% 95%;
--accent-foreground: 245 58% 51%;
--destructive: 0 84.2% 60.2%;
--destructive-foreground: 0 0% 10%;
--border: 240 5.9% 90%;
--input: 240 5.9% 90%;
--ring: 245 58% 51%;
--radius: 0.625rem;
--radius-sm: calc(0.625rem - 4px);
--radius-lg: calc(0.625rem + 4px);
--radius-full: 9999px;
--spacing-xs: 4px;
--spacing-sm: 8px;
--spacing-md: 16px;
--spacing-lg: 24px;
--spacing-xl: 32px;
--spacing-2xl: 48px;
--spacing-3xl: 64px;
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.03), 0 1px 3px 0 rgb(0 0 0 / 0.06);
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.05), 0 2px 4px -2px rgb(0 0 0 / 0.05);
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.07), 0 4px 6px -4px rgb(0 0 0 / 0.05);
--duration-fast: 150ms;
--duration-normal: 250ms;
--duration-slow: 350ms;
--chart-1: 245 58% 51%;
--chart-2: 173 58% 39%;
--chart-3: 12 76% 61%;
--chart-4: 197 37% 24%;
--chart-5: 43 74% 66%;
--sidebar: 245 30% 97%;
--sidebar-foreground: 240 10% 20%;
}
.dark {
--background: 240 10% 3.9%;
--foreground: 0 0% 98%;
--card: 240 10% 6%;
--card-foreground: 0 0% 98%;
--popover: 240 10% 6%;
--popover-foreground: 0 0% 98%;
--primary: 245 60% 60%;
--primary-foreground: 0 0% 100%;
--secondary: 240 3.7% 15.9%;
--secondary-foreground: 0 0% 98%;
--muted: 240 3.7% 15.9%;
--muted-foreground: 240 5% 64.9%;
--accent: 245 30% 18%;
--accent-foreground: 245 60% 75%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 0 0% 98%;
--border: 240 3.7% 15.9%;
--input: 240 3.7% 15.9%;
--ring: 245 60% 60%;
--shadow-sm: 0 1px 3px 0 rgb(0 0 0 / 0.15), 0 1px 2px -1px rgb(0 0 0 / 0.15);
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.2), 0 2px 4px -2px rgb(0 0 0 / 0.15);
--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.25), 0 4px 6px -4px rgb(0 0 0 / 0.15);
--chart-1: 245 60% 60%;
--chart-2: 160 60% 45%;
--chart-3: 30 80% 55%;
--chart-4: 280 65% 60%;
--chart-5: 340 75% 55%;
--sidebar: 240 10% 5.5%;
--sidebar-foreground: 0 0% 85%;
}
}
@layer base {
html { scroll-behavior: smooth; }
* { border-color: hsl(var(--border)); }
body {
background-color: hsl(var(--background));
color: hsl(var(--foreground));
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
::selection { background-color: hsl(var(--primary) / 0.2); color: hsl(var(--primary)); }
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background-color: transparent; }
::-webkit-scrollbar-thumb { background-color: hsl(var(--border)); border-radius: 9999px; }
::-webkit-scrollbar-thumb:hover { background-color: hsl(var(--muted-foreground) / 0.5); }
}
@layer utilities {
.scrollbar-none::-webkit-scrollbar { display: none; }
.scrollbar-none { -ms-overflow-style: none; scrollbar-width: none; }
}
+36
View File
@@ -0,0 +1,36 @@
import { DM_Sans, Plus_Jakarta_Sans, JetBrains_Mono } from 'next/font/google'
import './globals.css'
import { Providers } from '@/components/providers'
export const dynamic = 'force-dynamic'
const dmSans = DM_Sans({ subsets: ['latin'], variable: '--font-sans' })
const jakartaSans = Plus_Jakarta_Sans({ subsets: ['latin'], variable: '--font-display' })
const jetbrainsMono = JetBrains_Mono({ subsets: ['latin'], variable: '--font-mono' })
export const metadata = {
metadataBase: new URL(process.env.NEXTAUTH_URL ?? 'http://localhost:3000'),
title: 'computer',
description: 'Your personal binder of life on the web',
icons: {
icon: '/favicon.svg',
shortcut: '/favicon.svg',
},
openGraph: {
title: 'computer',
description: 'Your personal binder of life on the web',
images: ['/og-image.png'],
},
}
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<body className={`${dmSans.variable} ${jakartaSans.variable} ${jetbrainsMono.variable} font-sans`}>
<Providers>
{children}
</Providers>
</body>
</html>
)
}
+109
View File
@@ -0,0 +1,109 @@
'use client'
import { useState } from 'react'
import { signIn } from 'next-auth/react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Link2, Shield, Mail, Lock } from 'lucide-react'
import Link from 'next/link'
import { toast } from 'sonner'
import { useRouter } from 'next/navigation'
export function LoginClient({ oidcEnabled }: { oidcEnabled: boolean }) {
// Client-owned integration point. Keep disabled until verified Authelia
// identities are mapped to Go users in auth.ts's sign-in callback.
const oidcReady = false
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
const router = useRouter()
const handleEmailLogin = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true)
try {
// signIn with redirect:false still rejects on network failures.
const result = await signIn('credentials', { email, password, redirect: false })
if (result?.ok) {
router.push('/pages')
} else {
toast.error('Invalid credentials')
}
} catch {
toast.error('Sign-in failed; check your connection')
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-8">
<div className="text-center">
<div className="flex justify-center mb-4">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<Link2 className="h-7 w-7" />
</div>
</div>
<h1 className="font-display text-3xl font-bold tracking-tight">computer</h1>
<p className="text-sm text-muted-foreground mt-2">Your personal binder of life on the web</p>
</div>
<div className="space-y-4">
<Button
onClick={() => oidcEnabled && signIn('authelia', { redirectTo: '/pages' })}
className="w-full gap-2"
size="lg"
variant="default"
disabled={!oidcEnabled || !oidcReady}
>
<Shield className="h-5 w-5" />
Sign in with Authelia
</Button>
{(!oidcEnabled || !oidcReady) && (
<p className="text-center text-xs text-muted-foreground -mt-2">
Authelia single sign-on awaits client integration. Use email below.
</p>
)}
<div className="relative">
<div className="absolute inset-0 flex items-center"><div className="w-full border-t" /></div>
<div className="relative flex justify-center text-xs"><span className="bg-background px-2 text-muted-foreground">or continue with email</span></div>
</div>
<form onSubmit={handleEmailLogin} className="space-y-3">
<div className="relative">
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
type="email"
placeholder="Email"
value={email}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
className="pl-10"
required
/>
</div>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
type="password"
placeholder="Password"
value={password}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}
className="pl-10"
required
/>
</div>
<Button type="submit" variant="outline" className="w-full" loading={loading}>
Sign in with Email
</Button>
</form>
<p className="text-center text-xs text-muted-foreground">
Don't have an account? <Link href="/signup" className="text-primary hover:underline">Sign up</Link>
</p>
</div>
</div>
</div>
)
}
+12
View File
@@ -0,0 +1,12 @@
import { LoginClient } from './client'
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
import { getOidcStatus } from '@/lib/oidc-config'
export const dynamic = 'force-dynamic'
export default async function LoginPage() {
const session = await auth()
if (session?.user) redirect('/pages')
return <LoginClient oidcEnabled={getOidcStatus().enabled} />
}
+8
View File
@@ -0,0 +1,8 @@
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
export default async function Home() {
const session = await auth()
if (session?.user) redirect('/pages')
redirect('/login')
}
+68
View File
@@ -0,0 +1,68 @@
'use client'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { ExternalLink, Link2, Calendar } from 'lucide-react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
export function PublicBookmarkView({ bookmark }: { bookmark: any }) {
const domain = (() => { try { return new URL(bookmark?.url ?? '').hostname } catch { return '' } })()
return (
<div className="min-h-screen bg-background">
<header className="border-b">
<div className="max-w-3xl mx-auto px-4 py-4 flex items-center gap-2">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary text-primary-foreground">
<Link2 className="h-4 w-4" />
</div>
<span className="font-display font-bold">computer</span>
<span className="text-muted-foreground text-sm">— Shared Bookmark</span>
</div>
</header>
<main className="max-w-3xl mx-auto px-4 py-8 space-y-6">
<a
href={bookmark?.url ?? '#'}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-3 rounded-lg bg-primary/10 px-6 py-4 text-lg font-medium text-primary hover:bg-primary/20 transition-colors"
>
<ExternalLink className="h-5 w-5 shrink-0" />
<span className="truncate">{bookmark?.url ?? ''}</span>
</a>
<div>
<h1 className="font-display text-3xl font-bold tracking-tight">{bookmark?.title ?? 'Untitled'}</h1>
{bookmark?.ogDescription && <p className="text-muted-foreground mt-2">{bookmark.ogDescription}</p>}
</div>
{bookmark?.ogImage && (
<div className="rounded-lg border overflow-hidden">
<img src={bookmark.ogImage} alt={bookmark?.title ?? ''} referrerPolicy="no-referrer" className="w-full aspect-video object-cover" />
</div>
)}
<div className="flex flex-wrap gap-2">
{(bookmark?.tags ?? []).map((bt: any) => (
<Badge key={bt?.tag?.id} variant="secondary" style={{ backgroundColor: `${bt?.tag?.color ?? '#6366f1'}20`, color: bt?.tag?.color ?? '#6366f1' }}>
{bt?.tag?.name}
</Badge>
))}
</div>
{bookmark?.notes && (
<div className="prose prose-sm dark:prose-invert max-w-none rounded-lg border p-6">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{bookmark.notes}</ReactMarkdown>
</div>
)}
<div className="flex items-center gap-4 text-sm text-muted-foreground">
{bookmark?.dueDate && (
<span className="flex items-center gap-1"><Calendar className="h-4 w-4" /> {new Date(bookmark.dueDate).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric', timeZone: 'UTC' })}</span>
)}
</div>
</main>
</div>
)
}
+13
View File
@@ -0,0 +1,13 @@
import { apiBase } from '@/lib/api'
import { notFound } from 'next/navigation'
import { PublicBookmarkView } from './client'
export default async function PublicSharePage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const response = await fetch(`${apiBase()}/api/public/bookmarks/${encodeURIComponent(id)}`, { cache: 'no-store' })
if (!response.ok) notFound()
const bookmark = await response.json()
return <PublicBookmarkView bookmark={JSON.parse(JSON.stringify(bookmark))} />
}
+83
View File
@@ -0,0 +1,83 @@
'use client'
import { useState } from 'react'
import { signIn } from 'next-auth/react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Link2, Mail, Lock, User } from 'lucide-react'
import Link from 'next/link'
import { toast } from 'sonner'
import { useRouter } from 'next/navigation'
export function SignupClient() {
const [name, setName] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [loading, setLoading] = useState(false)
const router = useRouter()
const handleSignup = async (e: React.FormEvent) => {
e.preventDefault()
if (password.length < 6) { toast.error('Password must be at least 6 characters'); return }
setLoading(true)
try {
const res = await fetch('/api/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, name }),
})
const data = await res.json()
if (res.ok) {
// Auto sign in
const result = await signIn('credentials', { email, password, redirect: false })
if (result?.ok) {
router.push('/pages')
} else {
toast.success('Account created! Please sign in.')
router.push('/login')
}
} else {
toast.error(data?.error ?? 'Signup failed')
}
} catch {
toast.error('Error creating account')
}
setLoading(false)
}
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-8">
<div className="text-center">
<div className="flex justify-center mb-4">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<Link2 className="h-7 w-7" />
</div>
</div>
<h1 className="font-display text-3xl font-bold tracking-tight">Create Account</h1>
<p className="text-sm text-muted-foreground mt-2">Join computer to start organizing your links</p>
</div>
<form onSubmit={handleSignup} className="space-y-3">
<div className="relative">
<User className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input placeholder="Name" value={name} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value)} className="pl-10" />
</div>
<div className="relative">
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input type="email" placeholder="Email" value={email} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)} className="pl-10" required />
</div>
<div className="relative">
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input type="password" placeholder="Password (min 8 chars)" value={password} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)} className="pl-10" minLength={8} required />
</div>
<Button type="submit" className="w-full" loading={loading}>Create Account</Button>
</form>
<p className="text-center text-xs text-muted-foreground">
Already have an account? <Link href="/login" className="text-primary hover:underline">Sign in</Link>
</p>
</div>
</div>
)
}
+9
View File
@@ -0,0 +1,9 @@
import { SignupClient } from './client'
import { auth } from '@/auth'
import { redirect } from 'next/navigation'
export default async function SignupPage() {
const session = await auth()
if (session?.user) redirect('/pages')
return <SignupClient />
}
+146
View File
@@ -0,0 +1,146 @@
import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import jwt from 'jsonwebtoken'
import { createHmac } from 'node:crypto'
import { getOidcStatus } from '@/lib/oidc-config'
// Review SEC-2: browser IP attestation for Go's rate limiting (see lib/api.ts
// for the identical semantics used by the data proxy). Duplicated here to keep
// auth.ts import-free of lib/api.ts (avoiding a lib/api.ts → @/auth → lib/api.ts
// cycle); both helpers must stay in sync.
const observedClientIP = (headers: Headers): string | null => {
if (process.env.TRUSTED_PROXY !== '1') return null
const ip = headers.get('x-real-ip')
return ip && ip.trim() ? ip.trim() : null
}
const signClientIP = (secret: string, ip: string): { ts: string; sig: string } => {
const ts = String(Math.floor(Date.now() / 1000))
return { ts, sig: createHmac('sha256', secret).update(`${ip}|${ts}`).digest('hex') }
}
// NextAuth owns the browser session and the eventual client-managed OIDC flow.
// Password verification and data ownership live in Go, not Prisma.
export const { handlers, auth, signIn, signOut } = NextAuth({
trustHost: true,
// Same precedence as Go (config.Secret) and lib/api.ts, so a deployment
// with both variables set can never sign and verify with different values.
secret: process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET,
session: { strategy: 'jwt' },
pages: { signIn: '/login' },
providers: [
...(getOidcStatus().enabled ? [{
id: 'authelia', name: 'Authelia', type: 'oidc',
issuer: process.env.OIDC_ISSUER,
clientId: process.env.OIDC_CLIENT_ID,
clientSecret: process.env.OIDC_CLIENT_SECRET,
authorization: { params: { scope: 'openid profile email' } },
profile(profile: any) {
return { id: profile.sub, name: profile.name ?? profile.preferred_username ?? profile.sub,
email: profile.email, image: profile.picture ?? null }
},
} as any] : []),
CredentialsProvider({
credentials: { email: { label: 'Email', type: 'email' }, password: { label: 'Password', type: 'password' } },
async authorize(credentials, request) {
if (!credentials?.email || !credentials?.password) return null
// Review SEC-1: browser logins arrive through this NextAuth path, not
// the data proxy — without attested headers Go buckets every user on
// this server's address (Compose) or exempted them entirely
// (loopback, same-host setups), and one attacker could lock out any
// account. NextAuth v5 passes the credentials Request as the second
// argument; sign the observed browser IP the same way lib/api.ts does.
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
const ip = observedClientIP(request?.headers ?? new Headers())
if (ip && secret) {
const { ts, sig } = signClientIP(secret, ip)
headers['x-computer-client-ip'] = ip
headers['x-computer-client-ts'] = ts
headers['x-computer-client-sig'] = sig
}
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/auth/login`, {
method: 'POST', headers, cache: 'no-store',
body: JSON.stringify({ email: credentials.email, password: credentials.password }),
})
if (!response.ok) {
// Surface Go's 429 so callers can distinguish throttling from bad
// credentials (the custom login route maps everything else to 401).
if (response.status === 429) {
const retry = response.headers.get('retry-after')
const err = new Error(response.status === 429 ? 'Throttled' : 'Unauthorized') as Error & { status?: number; retryAfter?: string }
err.status = 429
if (retry) err.retryAfter = retry
throw err
}
return null
}
const data = await response.json()
// Carry Go's tokenVersion into the NextAuth JWT so every assertion
// this session signs is revocable by a version bump ("sign out
// everywhere") — review SEC-02.
return { ...data.user, tokenVersion: data.tokenVersion }
},
}),
],
callbacks: {
async signIn({ account }) {
// Client integration point: exchange a verified Authelia identity for a
// local Go User/Account before enabling OIDC. No subject is trusted as a
// database user ID; the backend exchange stays an explicit 501 stub.
return account?.provider !== 'authelia'
},
async jwt({ token, user }) { if (user) { token.id = user.id; token.ver = user.tokenVersion } return token },
async session({ session, token }) {
if (session.user) { session.user.id = token.id as string; session.user.ver = token.ver }
return session
},
},
events: {
// Review AUTH-LIFECYCLE: a browser sign-out must reach Go's revocation.
// Without this the tokenVersion never bumps on NextAuth sign-out:
// previously minted assertions stay valid for the rest of their (≤120s)
// lifetime and the user's Go cookie sessions survive the logout. Go's
// /api/auth/signout means "sign out everywhere" — deliberately the same
// semantics here. Fail-open: if Go is unreachable the local sign-out
// still completes, degrading to the previous behavior. Review CR-02:
// this event is the backstop — the UI's explicit /api/session/revoke
// call is what makes revocation failure user-visible; here the outcome
// is inspected, deadline-bound, and logged without secrets.
async signOut(message) {
const token = 'token' in message ? message.token : null
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
const id = typeof token?.id === 'string' ? token.id : ''
const ver = typeof token?.ver === 'number' ? token.ver : 0
if (!secret || !id || ver < 1) return
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), 5000)
try {
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/auth/signout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Same short-lived assertion the data proxy signs (lib/api.ts).
Authorization: `Bearer ${jwt.sign({ uid: id, ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'computer', expiresIn: '60s' })}`,
},
cache: 'no-store',
signal: controller.signal,
})
if (response.status === 401) {
// The assertion was rejected — overwhelmingly because an explicit
// revoke already bumped the tokenVersion (the revocation this call
// exists to guarantee has then already happened). Nothing to retry.
console.warn(`signout event: revocation assertion rejected (401) for user ${id}; session is revoked or expired`)
} else if (!response.ok) {
// Local sign-out still proceeds, but global revocation did NOT
// happen: other sessions/assertions survive. Make it visible.
console.error(`signout event: Go revocation failed with ${response.status} for user ${id}; other sessions may remain active`)
}
} catch (error) {
const kind = error instanceof Error ? error.name : 'Error'
console.error(`signout event: Go revocation unreachable for user ${id} (${kind}); other sessions may remain active`)
} finally {
clearTimeout(timer)
}
},
},
})
+20
View File
@@ -0,0 +1,20 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
}
}
+187
View File
@@ -0,0 +1,187 @@
'use client'
import { useState, useCallback, useEffect } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Link2, Loader2, Plus, X } from 'lucide-react'
import { toast } from 'sonner'
import { invalidateReference } from '@/lib/reference-data'
interface Props {
open: boolean
onClose: () => void
onCreated: () => void
}
export function AddBookmarkDialog({ open, onClose, onCreated }: Props) {
const [url, setUrl] = useState('')
const [title, setTitle] = useState('')
const [description, setDescription] = useState('')
const [notes, setNotes] = useState('')
const [dueDate, setDueDate] = useState('')
const [kanban, setKanban] = useState('INBOX')
const [loading, setLoading] = useState(false)
const [fetching, setFetching] = useState(false)
const [tags, setTags] = useState<{ id: string; name: string; color: string }[]>([])
const [allTags, setAllTags] = useState<any[]>([])
const [newTagName, setNewTagName] = useState('')
useEffect(() => {
if (open) {
fetch('/api/tags').then(r => r.json()).then(setAllTags).catch(() => {})
const timer = setTimeout(() => { setUrl(''); setTitle(''); setDescription(''); setNotes(''); setDueDate(''); setKanban('INBOX'); setTags([]) }, 0)
return () => clearTimeout(timer)
}
}, [open])
const fetchPreview = useCallback(async () => {
if (!url) return
setFetching(true)
try {
const res = await fetch(`/api/preview?url=${encodeURIComponent(url)}`)
if (res.ok) {
const data = await res.json()
if (data?.ogTitle && !title) setTitle(data.ogTitle)
if (data?.ogDescription && !description) setDescription(data.ogDescription)
}
} catch { /* ignore */ }
setFetching(false)
}, [url, title, description])
const handleSubmit = useCallback(async () => {
if (!url) { toast.error('URL is required'); return }
setLoading(true)
try {
const res = await fetch('/api/bookmarks', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
url,
title: title || undefined,
description: description || undefined,
notes: notes || undefined,
dueDate: dueDate || undefined,
kanbanStatus: kanban,
tagIds: tags.map(t => t.id),
}),
})
if (res.ok) {
toast.success('Bookmark created')
onCreated()
} else {
const data = await res.json().catch(() => ({}))
toast.error(data?.error ?? 'Failed')
}
} catch { toast.error('Error creating bookmark') }
setLoading(false)
}, [url, title, description, notes, dueDate, kanban, tags, onCreated])
const createTag = useCallback(async () => {
if (!newTagName) return
try {
const res = await fetch('/api/tags', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: newTagName }),
})
if (res.ok) {
const tag = await res.json()
setTags(prev => [...prev, { id: tag.id, name: tag.name, color: tag.color }])
setAllTags(prev => [...prev, tag])
setNewTagName('')
invalidateReference('tags')
}
} catch { /* ignore */ }
}, [newTagName])
return (
<Dialog open={open} onOpenChange={() => onClose()}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2"><Link2 className="h-5 w-5" /> Add Bookmark</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<label className="text-xs font-medium text-muted-foreground">URL *</label>
<div className="relative">
<Input
placeholder="https://..."
value={url}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUrl(e.target.value)}
onBlur={fetchPreview}
/>
{fetching && <Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground" />}
</div>
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Title</label>
<Input value={title} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTitle(e.target.value)} placeholder="Auto-filled from URL" />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Description</label>
<Input value={description} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setDescription(e.target.value)} />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Notes (Markdown)</label>
<Textarea value={notes} onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setNotes(e.target.value)} rows={3} />
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs font-medium text-muted-foreground">Due Date</label>
<Input type="date" value={dueDate} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setDueDate(e.target.value)} />
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Status</label>
<select
value={kanban}
onChange={(e: React.ChangeEvent<HTMLSelectElement>) => setKanban(e.target.value)}
className="w-full rounded-md border bg-background px-3 py-2 text-sm"
>
<option value="INBOX">Inbox</option>
<option value="TODO">To Do</option>
<option value="IN_PROGRESS">In Progress</option>
<option value="DONE">Done</option>
</select>
</div>
</div>
<div>
<label className="text-xs font-medium text-muted-foreground">Tags</label>
<div className="flex flex-wrap gap-1.5 mb-2">
{tags.map(t => (
<Badge key={t.id} variant="secondary" className="gap-1" style={{ backgroundColor: `${t.color}20`, color: t.color }}>
{t.name}
<button onClick={() => setTags(prev => prev.filter(x => x.id !== t.id))}><X className="h-3 w-3" /></button>
</Badge>
))}
</div>
<div className="flex gap-1.5">
<select
onChange={(e: React.ChangeEvent<HTMLSelectElement>) => {
const tag = allTags.find((t: any) => t.id === e.target.value)
if (tag && !tags.find(t => t.id === tag.id)) setTags(prev => [...prev, { id: tag.id, name: tag.name, color: tag.color }])
e.target.value = ''
}}
className="flex-1 rounded-md border bg-background px-3 py-1.5 text-sm"
defaultValue=""
>
<option value="" disabled>Select tag...</option>
{allTags.map((t: any) => <option key={t.id} value={t.id}>{t.name}</option>)}
</select>
<div className="flex gap-1">
<Input placeholder="New tag" value={newTagName} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setNewTagName(e.target.value)} className="w-24" />
<Button variant="outline" size="icon-sm" onClick={createTag}><Plus className="h-3 w-3" /></Button>
</div>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={onClose}>Cancel</Button>
<Button onClick={handleSubmit} loading={loading}>Save Bookmark</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+15
View File
@@ -0,0 +1,15 @@
'use client'
import { SessionProvider } from 'next-auth/react'
import type { Session } from 'next-auth'
import { AppShell } from '@/components/app-shell'
// Nested provider seeded with the server session: useSession() in AppShell
// has data during SSR, so the signed-in shell is server-rendered.
export function AppShellWrapper({ session, children }: { session: Session; children: React.ReactNode }) {
return (
<SessionProvider session={session}>
<AppShell>{children}</AppShell>
</SessionProvider>
)
}
+164
View File
@@ -0,0 +1,164 @@
'use client'
import { useState, useEffect, useCallback, useRef } from 'react'
import { useSession } from 'next-auth/react'
import { usePathname, useRouter } from 'next/navigation'
import { Sidebar } from '@/components/sidebar'
import { TopBar } from '@/components/top-bar'
import { AddBookmarkDialog } from '@/components/add-bookmark-dialog'
import { QuickFind } from '@/components/quick-find'
export type Bookmark = {
id: string
url: string
title: string | null
description: string | null
favicon: string | null
ogImage: string | null
ogTitle: string | null
ogDescription: string | null
notes: string | null
dueDate: string | null
// Owner-only fields (review PRIV-02): shared readers receive a narrowed
// projection without contacts, recipients, alerts or mailbox watches.
alertAt?: string | null
alertSent?: boolean
kanbanStatus: string
kanbanColumnId?: string | null
// Owner-only board order within a column. Shared-reader projections omit it.
kanbanPosition?: number
imapWatchEnabled?: boolean
imapQuery?: string | null
isPublic: boolean
ownerId: string
contactId?: string | null
// Optimistic concurrency revision (review CR-04): every owner-driven PUT
// must send the version it edited from; 409 means a newer edit exists.
version?: number
contact?: any | null
tags: { tag: { id: string; name: string; color: string; ownerId?: string } }[]
sharedWith?: any[]
owner?: any
createdAt: string
updatedAt: string
}
export type TagWithCount = {
id: string
name: string
color: string
ownerId: string
_count: { bookmarks: number }
sharedWith?: any[]
}
export function AppShell({ children }: { children: React.ReactNode }) {
const { data: session } = useSession()
const router = useRouter()
const pathname = usePathname()
const [sidebarOpen, setSidebarOpen] = useState(true)
const [addDialogOpen, setAddDialogOpen] = useState(false)
const [quickFindOpen, setQuickFindOpen] = useState(false)
const [alerts, setAlerts] = useState<any[]>([])
const [me, setMe] = useState<{ isAdmin: boolean; viewingAs: { name: string | null; email: string } | null } | null>(null)
useEffect(() => {
if (!session?.user) return
fetch('/api/me')
.then((r) => (r.ok ? r.json() : null))
.then(setMe)
.catch((e) => console.error('Failed to load account info', e))
}, [session?.user])
const exitViewAs = useCallback(async () => {
try {
await fetch('/api/admin/view-as', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId: null }) })
} catch { /* navigating to /admin surfaces any persistent failure */ }
window.location.href = '/admin'
}, [])
// Poll alerts. The API returns every un-dismissed alert on each poll, so
// track already-notified IDs per tab to avoid re-firing every 5 minutes.
const notifiedAlerts = useRef<Set<string>>(new Set())
useEffect(() => {
if (!session?.user) return
const check = async () => {
try {
const res = await fetch('/api/alerts/check')
if (res.ok) {
const data = await res.json()
setAlerts(data ?? [])
if (data?.length && typeof Notification !== 'undefined' && Notification.permission === 'granted') {
for (const a of data) {
const id = String(a?.id ?? a?.bookmarkId ?? '')
if (!id || notifiedAlerts.current.has(id)) continue
notifiedAlerts.current.add(id)
new Notification('computer alert', { body: `${a?.title ?? 'Bookmark'} is due!`, icon: '/favicon.svg' })
}
}
}
} catch { /* ignore */ }
}
check()
const interval = setInterval(check, 5 * 60 * 1000)
return () => clearInterval(interval)
}, [session?.user])
// Request notification permission
useEffect(() => {
if (typeof Notification !== 'undefined' && Notification.permission === 'default') {
Notification.requestPermission()
}
}, [])
const refreshPage = useCallback(() => {
window.dispatchEvent(new Event('computer:bookmarks-changed'))
router.refresh()
}, [router])
const dismissAlert = useCallback(async (bookmarkId: string) => {
try {
const res = await fetch(`/api/alerts/${bookmarkId}`, { method: 'DELETE' })
if (!res.ok) return
} catch { return }
setAlerts((prev: any[]) => (prev ?? []).filter((a: any) => a?.id !== bookmarkId))
}, [])
if (!session?.user) return null
return (
<div className="flex h-screen overflow-hidden bg-background">
<Sidebar open={sidebarOpen} onToggle={() => setSidebarOpen(!sidebarOpen)} onQuickFind={() => setQuickFindOpen(true)} pathname={pathname} isAdmin={!!me?.isAdmin} />
<div className="flex flex-1 flex-col overflow-hidden">
{me?.viewingAs && (
<div className="flex items-center justify-center gap-3 bg-amber-500 px-4 py-1.5 text-sm font-medium text-amber-950">
<span>Admin view — viewing as {me.viewingAs.name || me.viewingAs.email}</span>
<button onClick={exitViewAs} className="rounded bg-amber-950/15 px-2 py-0.5 text-xs font-semibold hover:bg-amber-950/25">Exit</button>
</div>
)}
<TopBar
user={session.user as any}
alerts={alerts}
onDismissAlert={dismissAlert}
onAddBookmark={() => setAddDialogOpen(true)}
onToggleSidebar={() => setSidebarOpen(!sidebarOpen)}
onQuickFind={() => setQuickFindOpen(true)}
/>
<main className="flex-1 overflow-auto p-6">
{children}
</main>
</div>
<AddBookmarkDialog
open={addDialogOpen}
onClose={() => setAddDialogOpen(false)}
onCreated={() => { setAddDialogOpen(false); refreshPage() }}
/>
<QuickFind
open={quickFindOpen}
onOpenChange={setQuickFindOpen}
isAdmin={!!me?.isAdmin}
onAddBookmark={() => setAddDialogOpen(true)}
/>
</div>
)
}
+101
View File
@@ -0,0 +1,101 @@
'use client'
import { ExternalLink, Calendar as CalendarIcon, Clock } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { cn } from '@/lib/utils'
import type { Bookmark } from '@/components/app-shell'
interface BookmarkCardProps {
bookmark: Bookmark
onClick?: () => void
compact?: boolean
}
export function BookmarkCard({ bookmark, onClick, compact }: BookmarkCardProps) {
const domain = (() => { try { return new URL(bookmark?.url ?? '').hostname } catch { return '' } })()
const tags = bookmark?.tags ?? []
return (
<div
onClick={onClick}
className={cn(
'group relative flex cursor-pointer flex-col rounded-lg border bg-card transition-all duration-normal hover:shadow-md hover:-translate-y-0.5 hover:border-primary/20 overflow-hidden',
compact ? 'p-3' : 'p-0'
)}
>
{!compact && bookmark?.ogImage && (
<div className="relative w-full aspect-video bg-muted">
<img
src={bookmark.ogImage}
alt={bookmark?.title ?? 'Bookmark'}
referrerPolicy="no-referrer"
className="object-cover w-full h-full"
onError={(e: any) => { e.target.style.display = 'none' }}
/>
</div>
)}
<div className={cn('flex flex-col gap-2', compact ? '' : 'p-4')}>
<div className="flex items-start gap-2">
{bookmark?.favicon && (
<img
src={bookmark.favicon}
alt=""
referrerPolicy="no-referrer"
className="h-4 w-4 mt-0.5 rounded shrink-0"
onError={(e: any) => { e.target.style.display = 'none' }}
/>
)}
<div className="min-w-0 flex-1">
<h3 className="text-sm font-medium leading-tight truncate">
{bookmark?.title ?? bookmark?.url ?? 'Untitled'}
</h3>
<p className="text-xs text-muted-foreground truncate mt-0.5">{domain}</p>
</div>
<a
href={bookmark?.url ?? '#'}
target="_blank"
rel="noopener noreferrer"
onClick={(e: React.MouseEvent) => e.stopPropagation()}
className="shrink-0 opacity-0 group-hover:opacity-100 transition-opacity"
>
<ExternalLink className="h-4 w-4 text-muted-foreground hover:text-primary" />
</a>
</div>
{!compact && bookmark?.ogDescription && (
<p className="text-xs text-muted-foreground line-clamp-2">{bookmark.ogDescription}</p>
)}
<div className="flex flex-wrap items-center gap-1.5">
{tags.slice(0, 3).map((bt: any) => (
<Badge
key={bt?.tag?.id}
variant="secondary"
className="text-[10px] px-1.5 py-0"
style={{ backgroundColor: `${bt?.tag?.color ?? '#6366f1'}20`, color: bt?.tag?.color ?? '#6366f1' }}
>
{bt?.tag?.name ?? ''}
</Badge>
))}
{tags.length > 3 && (
<span className="text-[10px] text-muted-foreground">+{tags.length - 3}</span>
)}
</div>
{(bookmark?.dueDate || bookmark?.alertAt) && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{bookmark?.dueDate && (
<span className="flex items-center gap-1">
<CalendarIcon className="h-3 w-3" />
{new Date(bookmark.dueDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })}
</span>
)}
{bookmark?.alertAt && (
<span className="flex items-center gap-1">
<Clock className="h-3 w-3" />
Alert set
</span>
)}
</div>
)}
</div>
</div>
)
}
+391
View File
@@ -0,0 +1,391 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@/components/ui/sheet'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Textarea } from '@/components/ui/textarea'
import { ExternalLink, Edit, Save, X, Trash2, Share2, Globe, Users, Calendar, Clock, Mail, Tag } from 'lucide-react'
import { toast } from 'sonner'
import type { Bookmark } from '@/components/app-shell'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { BookmarkExtras } from '@/components/bookmark-extras'
import { fetchReference } from '@/lib/reference-data'
import { format } from 'date-fns'
interface Props {
bookmark: Bookmark | null
onClose: () => void
onUpdate: () => void
}
export function BookmarkDetailSheet({ bookmark, onClose, onUpdate }: Props) {
const [editing, setEditing] = useState(false)
const [notes, setNotes] = useState('')
const [kanban, setKanban] = useState('INBOX')
const [dueDate, setDueDate] = useState('')
const [alertAt, setAlertAt] = useState('')
const [isPublic, setIsPublic] = useState(false)
const [imapEnabled, setImapEnabled] = useState(false)
const [imapQuery, setImapQuery] = useState('')
const [shareSearch, setShareSearch] = useState('')
const [shareResults, setShareResults] = useState<any[]>([])
const [saving, setSaving] = useState(false)
const [effectiveId, setEffectiveId] = useState<string | null>(null)
const [columns, setColumns] = useState<any[]>([])
const [contacts, setContacts] = useState<any[]>([])
const [columnId, setColumnId] = useState('')
const [contactId, setContactId] = useState('')
const [title, setTitle] = useState('')
const [url, setUrl] = useState('')
const [description, setDescription] = useState('')
const [tagIds, setTagIds] = useState<string[]>([])
const [allTags, setAllTags] = useState<{ id: string; name: string; color: string; ownerId?: string }[]>([])
// Review CR-04: set when a save hit a 409. The form keeps the unsaved
// draft; the banner is the explicit, persistent resolution path (a toast
// action alone would sit under the sheet's stacking context and vanish).
const [conflict, setConflict] = useState(false)
const canEdit = !!bookmark && effectiveId === bookmark.ownerId
useEffect(() => {
if (!bookmark) return
let cancelled = false
// Cached + deduplicated: opening the sheet repeatedly no longer fires
// four identical requests each time (fetchReference never rejects).
;(async () => {
const [me, cols, people, tags] = await Promise.all([
fetchReference<{ effectiveUser?: { id: string } }>('me'),
fetchReference<any[]>('columns'),
fetchReference<any[]>('contacts'),
fetchReference<{ id: string; name: string; color: string; ownerId?: string }[]>('tags'),
])
if (cancelled) return
if (me?.effectiveUser?.id) setEffectiveId(me.effectiveUser.id)
if (cols) setColumns(cols)
if (people) setContacts(people)
if (tags) setAllTags(tags)
})()
return () => { cancelled = true }
}, [bookmark])
useEffect(() => {
if (bookmark) {
const timer = setTimeout(() => {
setNotes(bookmark?.notes ?? '')
setKanban(bookmark?.kanbanStatus ?? 'INBOX')
setDueDate(bookmark?.dueDate ? new Date(bookmark.dueDate).toISOString().split('T')[0] : '')
setAlertAt(bookmark?.alertAt ? format(new Date(bookmark.alertAt), "yyyy-MM-dd'T'HH:mm") : '')
setIsPublic(bookmark?.isPublic ?? false)
setImapEnabled(bookmark?.imapWatchEnabled ?? false)
setImapQuery(bookmark?.imapQuery ?? '')
setEditing(false)
setColumnId(bookmark.kanbanColumnId || '')
setContactId(bookmark.contactId || '')
setTitle(bookmark.title || '')
setUrl(bookmark.url)
setDescription(bookmark.description || '')
setTagIds(bookmark.tags.map(({ tag }) => tag.id))
// A refreshed bookmark prop (after an explicit reload) clears the
// conflict state along with the form.
setConflict(false)
}, 0)
return () => clearTimeout(timer)
}
}, [bookmark])
const handleSave = useCallback(async () => {
if (!bookmark) return
setSaving(true)
try {
const res = await fetch(`/api/bookmarks/${bookmark.id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
notes,
title,
url,
description: description || null,
tagIds: tagIds.length === bookmark.tags.length && bookmark.tags.every(({ tag }) => tagIds.includes(tag.id)) ? undefined : tagIds,
kanbanColumnId: columnId || null,
contactId: contactId || null,
kanbanStatus: kanban,
dueDate: dueDate || null,
alertAt: alertAt ? new Date(alertAt).toISOString() : null,
isPublic,
imapWatchEnabled: imapEnabled,
imapQuery: imapQuery || null,
// Optimistic concurrency (review CR-04): the save carries the
// version this form was opened from; a newer edit elsewhere is a
// 409 and this draft is NOT lost silently.
version: bookmark.version ?? 0,
}),
})
if (res.ok) {
toast.success('Bookmark updated')
setEditing(false)
setConflict(false)
onUpdate()
} else if (res.status === 409) {
// Review CR-04: keep the unsaved form exactly as it is; the inline
// conflict banner below is the explicit resolution path. Reloading
// is a deliberate user choice so anything worth keeping can be
// copied first.
setConflict(true)
toast.error('This bookmark was changed elsewhere — your edits were NOT saved')
} else {
toast.error('Failed to update')
}
} catch { toast.error('Error saving') }
setSaving(false)
}, [bookmark, notes, title, url, description, tagIds, columnId, contactId, kanban, dueDate, alertAt, isPublic, imapEnabled, imapQuery, onUpdate])
const handleDelete = useCallback(async () => {
if (!bookmark || !confirm('Delete this bookmark?')) return
const response = await fetch(`/api/bookmarks/${bookmark.id}`, { method: 'DELETE' })
if (!response.ok) { toast.error('Could not delete bookmark'); return }
toast.success('Bookmark deleted')
onClose()
onUpdate()
}, [bookmark, onClose, onUpdate])
const searchUsers = useCallback(async (q: string) => {
setShareSearch(q)
if (q.length < 2) { setShareResults([]); return }
try {
const res = await fetch(`/api/users/search?q=${encodeURIComponent(q)}`)
if (res.ok) setShareResults(await res.json())
} catch { /* ignore */ }
}, [])
const shareWith = useCallback(async (userId: string) => {
if (!bookmark) return
const response = await fetch(`/api/bookmarks/${bookmark.id}/share`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userIds: [userId] }),
})
if (!response.ok) { toast.error('Could not share bookmark'); return }
toast.success('Shared!')
setShareSearch('')
setShareResults([])
onUpdate()
}, [bookmark, onUpdate])
const togglePublic = useCallback(async () => {
if (!bookmark) return
const response = await fetch(`/api/bookmarks/${bookmark.id}/share`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ isPublic: !isPublic }),
})
if (!response.ok) { toast.error('Could not change public access'); return }
setIsPublic(!isPublic)
toast.success(isPublic ? 'Made private' : 'Made public')
onUpdate()
}, [bookmark, isPublic, onUpdate])
const domain = (() => { try { return bookmark ? new URL(bookmark.url).hostname : '' } catch { return '' } })()
return (
<Sheet open={!!bookmark} onOpenChange={() => onClose()}>
<SheetContent className="w-full sm:max-w-lg overflow-y-auto">
<SheetHeader>
<SheetTitle className="flex items-center gap-2">
{bookmark?.favicon && (
<img src={bookmark.favicon} alt="" referrerPolicy="no-referrer" className="h-5 w-5 rounded" onError={(e: any) => { e.target.style.display = 'none' }} />
)}
<span className="truncate">{bookmark?.title ?? 'Untitled'}</span>
</SheetTitle>
</SheetHeader>
<div className="mt-4 space-y-6">
{/* URL */}
<a
href={bookmark?.url ?? '#'}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-2 rounded-lg bg-primary/10 px-4 py-3 text-sm font-medium text-primary hover:bg-primary/20 transition-colors"
>
<ExternalLink className="h-4 w-4 shrink-0" />
<span className="truncate">{bookmark?.url ?? ''}</span>
</a>
{canEdit && <div className="space-y-3">
<label className="block text-xs font-medium" htmlFor="bookmark-url">URL<Input id="bookmark-url" value={url} onChange={e => setUrl(e.target.value)} className="mt-1" /></label>
<label className="block text-xs font-medium" htmlFor="bookmark-description">Description<Textarea id="bookmark-description" value={description} onChange={e => setDescription(e.target.value)} rows={2} className="mt-1" /></label>
</div>}
{/* OG Preview */}
{bookmark?.ogImage && (
<div className="rounded-lg border overflow-hidden">
<img src={bookmark.ogImage} alt="" referrerPolicy="no-referrer" className="w-full aspect-video object-cover" onError={(e: any) => { e.target.style.display = 'none' }} />
<div className="p-3">
<p className="text-sm font-medium">{bookmark?.ogTitle ?? bookmark?.title}</p>
<p className="text-xs text-muted-foreground mt-1">{bookmark?.ogDescription}</p>
<p className="text-xs text-muted-foreground mt-1">{domain}</p>
</div>
</div>
)}
{/* Tags */}
<div>
<p className="text-xs font-medium text-muted-foreground mb-1.5 flex items-center gap-1"><Tag className="h-3 w-3" /> Tags</p>
<div className="flex flex-wrap gap-1.5">
{(bookmark?.tags ?? []).map((bt: any) => (
<Badge key={bt?.tag?.id} variant="secondary" style={{ backgroundColor: `${bt?.tag?.color ?? '#6366f1'}20`, color: bt?.tag?.color ?? '#6366f1' }}>
{bt?.tag?.name ?? ''}
</Badge>
))}
{(bookmark?.tags?.length ?? 0) === 0 && <span className="text-xs text-muted-foreground">No tags</span>}
</div>
{canEdit && bookmark && <div className="mt-2 space-y-1">
{[...new Map([...allTags, ...bookmark.tags.map(({ tag }) => tag)].map(tag => [tag.id, tag])).values()].map(tag => <label key={tag.id} className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={tagIds.includes(tag.id)} onChange={e => setTagIds(previous => e.target.checked ? [...previous, tag.id] : previous.filter(id => id !== tag.id))} />{tag.name}
{/* Group-wide tag sharing is a product decision; make the audience
visible before a tag is attached to private material (review). */}
{tag.ownerId && effectiveId && tag.ownerId !== effectiveId && (
<span className="text-xs text-muted-foreground">(shared tag — everyone with this tag can see bookmarks under it)</span>
)}
</label>)}
</div>}
</div>
{/* Notes */}
{canEdit && <div className="space-y-2"><label className="text-xs font-medium">Title</label><Input value={title} onChange={e => setTitle(e.target.value)} /></div>}
<div>
<div className="flex items-center justify-between mb-1.5">
<p className="text-xs font-medium text-muted-foreground">Notes</p>
<Button disabled={!canEdit} variant="ghost" size="xs" onClick={() => setEditing(!editing)}>
{editing ? <X className="h-3 w-3" /> : <Edit className="h-3 w-3" />}
</Button>
</div>
{editing ? (
<Textarea value={notes} onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setNotes(e.target.value)} rows={6} placeholder="Markdown notes..." />
) : (
<div className="prose prose-sm dark:prose-invert max-w-none rounded-lg bg-muted/50 p-3 min-h-[60px]">
{notes ? <ReactMarkdown remarkPlugins={[remarkGfm]}>{notes}</ReactMarkdown> : <span className="text-muted-foreground text-xs">No notes</span>}
</div>
)}
</div>
{/* Kanban Status */}
<fieldset disabled={!canEdit} className="space-y-4">
<div className="grid grid-cols-2 gap-3">
<label className="text-xs font-medium">Column<select className="mt-1 w-full rounded border bg-background p-2" value={columnId} onChange={e => setColumnId(e.target.value)}><option value="">Use legacy status</option>{columns.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}</select></label>
<label className="text-xs font-medium">Contact<select className="mt-1 w-full rounded border bg-background p-2" value={contactId} onChange={e => setContactId(e.target.value)}><option value="">No contact</option>{contacts.map(c => <option key={c.id} value={c.id}>{c.displayName}</option>)}</select></label>
</div>
<div>
<p className="text-xs font-medium text-muted-foreground mb-1.5">Status</p>
<div className="flex gap-1.5">
{['INBOX', 'TODO', 'IN_PROGRESS', 'DONE'].map((s: string) => (
<Button
key={s}
variant={kanban === s ? 'default' : 'outline'}
size="xs"
onClick={() => setKanban(s)}
>
{s.replace('_', ' ')}
</Button>
))}
</div>
</div>
{/* Due Date & Alert */}
<div className="grid grid-cols-2 gap-3">
<div>
<p className="text-xs font-medium text-muted-foreground mb-1.5 flex items-center gap-1"><Calendar className="h-3 w-3" /> Due Date</p>
<Input type="date" value={dueDate} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setDueDate(e.target.value)} />
</div>
<div>
<p className="text-xs font-medium text-muted-foreground mb-1.5 flex items-center gap-1"><Clock className="h-3 w-3" /> Alert</p>
<Input type="datetime-local" value={alertAt} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setAlertAt(e.target.value)} />
</div>
</div>
{/* Contact */}
{bookmark?.contact && (
<div>
<p className="text-xs font-medium text-muted-foreground mb-1.5 flex items-center gap-1"><Users className="h-3 w-3" /> Contact</p>
<div className="flex items-center gap-2 rounded-lg bg-muted/50 px-3 py-2">
<div className="h-8 w-8 rounded-full bg-primary/20 flex items-center justify-center text-xs font-bold text-primary">
{(bookmark.contact?.displayName ?? '?')[0]?.toUpperCase()}
</div>
<div>
<p className="text-sm font-medium">{bookmark.contact?.displayName}</p>
<p className="text-xs text-muted-foreground">{bookmark.contact?.email}</p>
</div>
</div>
</div>
)}
{/* IMAP Watch */}
<div>
<p className="text-xs font-medium text-muted-foreground mb-1.5 flex items-center gap-1"><Mail className="h-3 w-3" /> Mailbox Watch</p>
<div className="flex items-center gap-2">
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" checked={imapEnabled} onChange={() => setImapEnabled(!imapEnabled)} className="rounded" />
Enabled
</label>
{imapEnabled && (
<Input placeholder="Search query (subject/from)" value={imapQuery} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setImapQuery(e.target.value)} className="flex-1" />
)}
</div>
</div>
{/* Sharing */}
<div>
<p className="text-xs font-medium text-muted-foreground mb-1.5 flex items-center gap-1"><Share2 className="h-3 w-3" /> Sharing</p>
<div className="space-y-2">
<Button variant={isPublic ? 'default' : 'outline'} size="sm" onClick={togglePublic} className="gap-1.5">
<Globe className="h-3 w-3" />
{isPublic ? 'Public' : 'Private'}
</Button>
{isPublic && (
<div className="space-y-1 text-xs text-muted-foreground">
<p>
Public link: <code className="bg-muted px-1 rounded">/share/bookmark/{bookmark?.id}</code>
</p>
<p>Anyone with the link sees the title, description, <span className="font-medium text-foreground">notes</span>, due date, tags and preview. Contacts, alerts, mailbox watches and your identity stay private.</p>
</div>
)}
<Input placeholder="Search users to share with..." value={shareSearch} onChange={(e: React.ChangeEvent<HTMLInputElement>) => searchUsers(e.target.value)} />
{shareResults.map((u: any) => (
<button key={u?.id} onClick={() => shareWith(u?.id)} className="flex items-center gap-2 w-full rounded-md px-2 py-1.5 hover:bg-muted text-sm">
<span className="h-6 w-6 rounded-full bg-primary/20 flex items-center justify-center text-xs font-bold text-primary">
{(u?.name ?? u?.email ?? '?')[0]?.toUpperCase()}
</span>
{u?.name ?? u?.email}
</button>
))}
</div>
</div>
{/* Actions */}
</fieldset>
{conflict && canEdit && (
<div role="alert" className="rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm space-y-2">
<p className="font-medium text-destructive">This bookmark was changed elsewhere</p>
<p className="text-muted-foreground">
Your edits are kept in this form but were NOT saved — saving again would overwrite the
newer version. Copy anything you want to keep, then load the latest version.
</p>
<Button size="sm" variant="outline" onClick={() => onUpdate()}>Load latest version</Button>
</div>
)}
{bookmark && <BookmarkExtras bookmark={bookmark} canEdit={canEdit} onUpdate={onUpdate} />}
{!canEdit && <p className="text-xs text-muted-foreground">Shared bookmark — read only</p>}
{canEdit &&
<div className="flex items-center gap-2 pt-2 border-t">
<Button onClick={handleSave} loading={saving} className="flex-1 gap-1.5">
<Save className="h-4 w-4" /> Save Changes
</Button>
<Button variant="destructive" size="icon" onClick={handleDelete}>
<Trash2 className="h-4 w-4" />
</Button>
</div>}
</div>
</SheetContent>
</Sheet>
)
}
+53
View File
@@ -0,0 +1,53 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { toast } from 'sonner'
import type { Bookmark } from '@/components/app-shell'
export function BookmarkExtras({ bookmark, canEdit, onUpdate }: { bookmark: Bookmark; canEdit: boolean; onUpdate: () => void }) {
const [sources, setSources] = useState<any[]>([])
const [signals, setSignals] = useState<any[]>([])
const [pages, setPages] = useState<any[]>([])
const [from, setFrom] = useState('')
const [subject, setSubject] = useState('')
const [busy, setBusy] = useState(false)
const [shares, setShares] = useState<any[]>([])
const load = useCallback(async () => {
const [signalResponse, bookmarkResponse] = await Promise.all([
fetch(`/api/bookmarks/${bookmark.id}/signals`), fetch(`/api/bookmarks/${bookmark.id}`),
])
if (signalResponse.ok) { const data = await signalResponse.json(); setSources(data.sources); setSignals(data.signals) }
if (bookmarkResponse.ok) { const data = await bookmarkResponse.json(); setPages(data.pageLinks ?? []); setShares(data.sharedWith ?? []) }
}, [bookmark.id])
useEffect(() => { const timer = setTimeout(() => load().catch(() => toast.error('Could not load bookmark details')), 0); return () => clearTimeout(timer) }, [load])
const change = async (url: string, method: string, body?: any) => {
setBusy(true)
try {
const response = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined })
if (!response.ok) { toast.error((await response.json()).error || 'Request failed'); return }
await load(); onUpdate()
} catch { toast.error('Request failed') } finally { setBusy(false) }
}
return <div className="space-y-4 border-t pt-4">
<a className="text-sm text-primary underline" href={`/api/bookmarks/${bookmark.id}/markdown`}>Download Markdown</a>
{canEdit && shares.length > 0 && <div><h3 className="text-sm font-medium">Shared with</h3>{shares.map(share => <div key={share.userId} className="flex items-center justify-between text-xs"><span>{share.user?.name || share.user?.email}</span><Button size="xs" variant="ghost" onClick={() => change(`/api/bookmarks/${bookmark.id}/share/${share.userId}`, 'DELETE')}>Stop sharing</Button></div>)}</div>}
<div><h3 className="text-sm font-medium">On pages</h3>
{pages.length ? pages.map(link => <a key={link.pageId} className="block text-sm text-primary" href={`/pages?id=${link.pageId}`}>{link.page.title}</a>) : <p className="text-xs text-muted-foreground">Not linked to a page yet</p>}
</div>
<div className="space-y-2"><h3 className="text-sm font-medium">Signals</h3>
{canEdit && <>
<div className="flex gap-2"><Input placeholder="From address (optional)" value={from} onChange={e => setFrom(e.target.value)} /><Input placeholder="Subject contains" value={subject} onChange={e => setSubject(e.target.value)} /></div>
<div className="flex gap-2"><Button size="sm" disabled={busy} onClick={() => change(`/api/bookmarks/${bookmark.id}/signals`, 'POST', { type: 'email', config: { from, subject } })}>Add email watcher</Button>
<Button size="sm" variant="outline" disabled={busy} onClick={() => change(`/api/bookmarks/${bookmark.id}/signals`, 'POST', { action: 'check' })}>Check now</Button></div>
</>}
{sources.map(source => <div key={source.id} className="rounded border p-2 text-xs">
<p>{source.type}: {source.config.from || 'any sender'} / {source.config.subject || 'any subject'}</p><p className="text-muted-foreground">{source.lastStatus || 'Not checked yet'}</p>
{canEdit && <div className="flex gap-2"><Button size="xs" variant="ghost" onClick={() => change(`/api/signal-sources/${source.id}`, 'PATCH', { enabled: !source.enabled })}>{source.enabled ? 'Pause' : 'Enable'}</Button><Button size="xs" variant="ghost" onClick={() => change(`/api/signal-sources/${source.id}`, 'DELETE')}>Remove</Button></div>}
</div>)}
{signals.map(signal => <div key={signal.id} className="rounded bg-muted p-2 text-sm"><p>{signal.title}</p><p className="text-xs text-muted-foreground">{signal.summary}</p></div>)}
{!signals.length && <p className="text-xs text-muted-foreground">No matching events yet. Configure a mailbox in Settings to check email watchers.</p>}
</div>
</div>
}
@@ -0,0 +1,50 @@
'use client'
// IMPORTANT: Do not remove this component.
// It handles a known Next.js dev server race condition where dynamic chunks
// imported by next/dynamic haven't been compiled yet and cause webpack to throw
// a ChunkLoadError
import { useEffect } from 'react'
// A dev server that keeps serving stale chunk URLs raises a ChunkLoadError on every
// render pass, so an unthrottled reload turns one bad chunk into a continuous reload
// loop that wipes whatever the user was typing.
const RELOAD_THROTTLE_MS = 60000
const RELOAD_KEY = 'chunkReloadAt'
function shouldReload(): boolean {
const now = Date.now()
try {
const last = Number(window.sessionStorage.getItem(RELOAD_KEY)) || 0
if (now - last < RELOAD_THROTTLE_MS) {
return false
}
window.sessionStorage.setItem(RELOAD_KEY, String(now))
} catch {
// Without a durable timestamp the throttle cannot latch across reloads, so stay put
// rather than risk the loop; the user can still reload by hand.
return false
}
return true
}
export function ChunkLoadErrorHandler() {
useEffect(() => {
const handler = (event: ErrorEvent) => {
if (
event.error?.name === 'ChunkLoadError' ||
event.error?.message?.includes('Loading chunk')
) {
event.preventDefault()
if (shouldReload()) {
window.location.reload()
}
}
}
window.addEventListener('error', handler)
return () => window.removeEventListener('error', handler)
}, [])
return null
}
+20
View File
@@ -0,0 +1,20 @@
'use client'
import { ReactNode, useSyncExternalStore } from 'react'
const subscribe = () => () => {}
/** True only after the component has mounted on the client. Use to gate browser-only values. */
export function useMounted(): boolean {
return useSyncExternalStore(subscribe, () => true, () => false)
}
/**
* Renders children only after client mount, so SSR output stays deterministic.
* Use for anything that differs between server and client (window/localStorage reads,
* user timezone/locale values, random ids, live clocks, third-party widgets).
* Pass a `fallback` matching the final size to avoid layout shift.
*/
export function ClientOnly({ children, fallback = null }: { children: ReactNode; fallback?: ReactNode }) {
const mounted = useMounted()
return <>{mounted ? children : fallback}</>
}
+54
View File
@@ -0,0 +1,54 @@
'use client'
import { useLinkPreview } from '@/lib/link-preview'
const hostOf = (u: string) => {
try { return new URL(u).hostname.replace(/^www\./, '') } catch { return u }
}
// Notion-style inline preview for a link that sits alone on its own line in
// page Markdown. While the preview loads (or if nothing resolves) the card
// still shows the link text/host, so content never disappears or shifts.
export function LinkPreviewCard({ url, label }: { url: string; label?: string }) {
const preview = useLinkPreview(url)
const title = preview?.ogTitle || preview?.title || label || url
const description = preview?.ogDescription || preview?.description || null
return (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
className="my-2 flex gap-3 rounded-lg bg-card p-3 no-underline shadow-sm ring-1 ring-border/50 transition-shadow hover:shadow-md"
>
{preview?.ogImage ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={preview.ogImage}
alt=""
referrerPolicy="no-referrer"
className="h-16 w-24 shrink-0 rounded bg-muted object-cover"
onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }}
/>
) : null}
<span className="min-w-0 flex-1">
<span className="flex items-center gap-1.5">
{preview?.favicon ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={preview.favicon}
alt=""
referrerPolicy="no-referrer"
className="h-3.5 w-3.5 shrink-0"
onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }}
/>
) : null}
<span className="truncate text-sm font-medium text-foreground">{title}</span>
</span>
{description ? (
<span className="mt-0.5 line-clamp-2 block text-xs text-muted-foreground">{description}</span>
) : null}
<span className="mt-1 block text-[11px] text-muted-foreground/80">{hostOf(url)}</span>
</span>
</a>
)
}
+18
View File
@@ -0,0 +1,18 @@
'use client'
import { SessionProvider } from 'next-auth/react'
import { ThemeProvider } from '@/components/theme-provider'
import { Toaster } from '@/components/ui/sonner'
import { ChunkLoadErrorHandler } from '@/components/chunk-load-error-handler'
export function Providers({ children }: { children: React.ReactNode }) {
return (
<SessionProvider>
<ThemeProvider attribute="class" defaultTheme="dark" enableSystem disableTransitionOnChange>
{children}
<Toaster />
<ChunkLoadErrorHandler />
</ThemeProvider>
</SessionProvider>
)
}
+226
View File
@@ -0,0 +1,226 @@
'use client'
// Notion-style "Quick Find": a Cmd/Ctrl+K palette to jump to any page,
// bookmark, tag, or view, and to run the few workspace commands
// (new page, add bookmark, toggle theme). Search is read-only; mutations
// stay on their owning screens.
import { useCallback, useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useTheme } from 'next-themes'
import { toast } from 'sonner'
import {
Calendar,
ExternalLink,
FilePlus2,
FileText,
Kanban,
Link2,
Moon,
Plus,
Search,
Settings,
Shield,
Sun,
Tags,
Users,
} from 'lucide-react'
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from '@/components/ui/command'
import { nextUntitledTitle, notifyPagesChanged, type PageSummary } from '@/lib/pages'
import type { TagWithCount } from '@/components/app-shell'
type BookmarkHit = { id: string; url: string; title: string | null; favicon: string | null; ogTitle: string | null }
const views = [
{ href: '/bookmarks', label: 'All Bookmarks', icon: Link2 },
{ href: '/calendar', label: 'Calendar', icon: Calendar },
{ href: '/tags', label: 'Tags', icon: Tags },
{ href: '/kanban', label: 'Kanban', icon: Kanban },
{ href: '/contacts', label: 'Contacts', icon: Users },
{ href: '/settings', label: 'Settings', icon: Settings },
]
const host = (u: string) => { try { return new URL(u).hostname.replace(/^www\./, '') } catch { return u } }
interface QuickFindProps {
open: boolean
onOpenChange: (open: boolean) => void
isAdmin?: boolean
onAddBookmark?: () => void
}
export function QuickFind({ open, onOpenChange, isAdmin = false, onAddBookmark }: QuickFindProps) {
const router = useRouter()
const { theme, setTheme } = useTheme()
const [query, setQuery] = useState('')
const [pages, setPages] = useState<PageSummary[]>([])
const [tags, setTags] = useState<TagWithCount[]>([])
const [bookmarks, setBookmarks] = useState<BookmarkHit[]>([])
// Notion binds both Cmd/Ctrl+K and Cmd/Ctrl+P to Quick Find.
useEffect(() => {
const down = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {
e.preventDefault()
onOpenChange(!open)
}
}
document.addEventListener('keydown', down)
return () => document.removeEventListener('keydown', down)
}, [open, onOpenChange])
// Load the workspace index each time the palette opens; results stay fresh
// without polling while it is closed.
useEffect(() => {
if (!open) return
fetch('/api/pages').then((r) => (r.ok ? r.json() : [])).then((d: PageSummary[]) => setPages(d ?? [])).catch(() => {})
fetch('/api/tags').then((r) => (r.ok ? r.json() : [])).then((d: TagWithCount[]) => setTags(d ?? [])).catch(() => {})
}, [open])
// Bookmark search hits the API (debounced) because the server matches
// notes and URLs too, not just titles.
useEffect(() => {
if (!open) return
const q = query.trim()
const t = setTimeout(async () => {
if (q.length < 2) { setBookmarks([]); return }
try {
const params = new URLSearchParams({ search: q, limit: '6' })
const res = await fetch(`/api/bookmarks?${params}`)
if (res.ok) setBookmarks(((await res.json()) as BookmarkHit[]).slice(0, 6))
} catch { /* transient; retried on next keystroke */ }
}, q.length < 2 ? 0 : 200)
return () => clearTimeout(t)
}, [query, open])
const go = useCallback((href: string) => {
onOpenChange(false)
setQuery('')
router.push(href)
}, [onOpenChange, router])
const createPage = useCallback(async () => {
onOpenChange(false)
setQuery('')
const title = nextUntitledTitle(pages.map((p) => p.title))
try {
const res = await fetch('/api/pages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title }) })
if (!res.ok) { toast.error('Could not create page'); return }
const p = await res.json()
notifyPagesChanged()
router.push(`/pages?id=${p.id}`)
} catch { toast.error('Could not create page') }
}, [onOpenChange, pages, router])
return (
<CommandDialog open={open} onOpenChange={(next) => { onOpenChange(next); if (!next) setQuery('') }}>
<CommandInput
placeholder="Search pages, bookmarks, tags, and commands…"
value={query}
onValueChange={(v) => { setQuery(v); }}
/>
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup heading="Commands">
<CommandItem value="new page create" onSelect={createPage}>
<FilePlus2 className="mr-2 h-4 w-4 text-muted-foreground" />
New page
</CommandItem>
{onAddBookmark && (
<CommandItem value="add bookmark new link url" onSelect={() => { onOpenChange(false); setQuery(''); onAddBookmark() }}>
<Plus className="mr-2 h-4 w-4 text-muted-foreground" />
Add bookmark
</CommandItem>
)}
<CommandItem value="toggle theme dark light mode appearance" onSelect={() => { onOpenChange(false); setTheme(theme === 'dark' ? 'light' : 'dark') }}>
{theme === 'dark' ? <Sun className="mr-2 h-4 w-4 text-muted-foreground" /> : <Moon className="mr-2 h-4 w-4 text-muted-foreground" />}
Toggle dark mode
</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="Views">
{views.map((v) => (
<CommandItem key={v.href} value={`view go to ${v.label}`} onSelect={() => go(v.href)}>
<v.icon className="mr-2 h-4 w-4 text-muted-foreground" />
{v.label}
</CommandItem>
))}
{isAdmin && (
<CommandItem value="view go to admin administration" onSelect={() => go('/admin')}>
<Shield className="mr-2 h-4 w-4 text-muted-foreground" />
Admin
</CommandItem>
)}
</CommandGroup>
{pages.length > 0 && (
<>
<CommandSeparator />
<CommandGroup heading="Pages">
{pages.map((p) => (
<CommandItem key={p.id} value={`page ${p.title}`} onSelect={() => go(`/pages?id=${p.id}`)}>
<FileText className="mr-2 h-4 w-4 text-muted-foreground" />
<span className="truncate">{p.title}</span>
</CommandItem>
))}
</CommandGroup>
</>
)}
{tags.length > 0 && (
<>
<CommandSeparator />
<CommandGroup heading="Tags">
{tags.map((t) => (
<CommandItem key={t.id} value={`tag ${t.name}`} onSelect={() => go(`/tags?tag=${t.id}`)}>
<Tags className="mr-2 h-4 w-4" style={{ color: t.color }} />
<span className="truncate">{t.name}</span>
<span className="ml-auto text-xs text-muted-foreground">{t._count?.bookmarks ?? 0}</span>
</CommandItem>
))}
</CommandGroup>
</>
)}
{query.trim().length >= 2 && (
<>
<CommandSeparator />
<CommandGroup heading="Search">
<CommandItem value={`zz-search-bookmarks-for-${query}`} onSelect={() => go(`/bookmarks?search=${encodeURIComponent(query.trim())}`)}>
<Search className="mr-2 h-4 w-4 text-muted-foreground" />
Search bookmarks for “{query.trim()}”
</CommandItem>
</CommandGroup>
</>
)}
{bookmarks.length > 0 && (
<>
<CommandSeparator />
<CommandGroup heading="Bookmarks">
{bookmarks.map((b) => (
<CommandItem key={b.id} value={`bookmark ${b.title ?? ''} ${b.ogTitle ?? ''} ${b.url}`} onSelect={() => go(`/bookmarks?open=${b.id}`)}>
{b.favicon ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={b.favicon} alt="" referrerPolicy="no-referrer" className="mr-2 h-4 w-4 rounded" onError={(e) => { (e.target as HTMLImageElement).style.visibility = 'hidden' }} />
) : (
<Link2 className="mr-2 h-4 w-4 text-muted-foreground" />
)}
<span className="min-w-0 flex-1">
<span className="block truncate">{b.title || b.ogTitle || b.url}</span>
<span className="block truncate text-xs text-muted-foreground">{host(b.url)}</span>
</span>
<ExternalLink className="ml-2 h-3.5 w-3.5 shrink-0 text-muted-foreground" />
</CommandItem>
))}
</CommandGroup>
</>
)}
</CommandList>
</CommandDialog>
)
}
+80
View File
@@ -0,0 +1,80 @@
'use client'
import { useMounted } from '@/components/client-only'
/**
* Hydration-safe date/number formatting.
*
* Locale APIs (`toLocaleDateString`, `Intl.*`) default to the runtime's locale and
* timezone, which differ between server (UTC) and browser — a classic hydration
* mismatch. These components format with an explicit locale + timeZone so SSR and
* client render identical text. Set `localize` to re-render in the visitor's own
* locale/timezone after mount (safe: wrapped in suppressHydrationWarning).
*/
const DEFAULT_LOCALE = 'en-US'
const DEFAULT_TIME_ZONE = 'UTC'
type SafeDateProps = {
date: Date | string | number
options?: Intl.DateTimeFormatOptions
locale?: string
localize?: boolean
className?: string
}
export function SafeDate({ date, options, locale = DEFAULT_LOCALE, localize = false, className }: SafeDateProps) {
const mounted = useMounted()
const d = date instanceof Date ? date : new Date(date)
const useLocal = localize && mounted
// toLocaleDateString throws on timeStyle (and toLocaleTimeString on dateStyle),
// so date+time option mixes render via toLocaleString.
const text = (options?.timeStyle ? d.toLocaleString : d.toLocaleDateString).call(d, useLocal ? undefined : locale, {
timeZone: useLocal ? undefined : DEFAULT_TIME_ZONE,
...options,
})
return (
<span suppressHydrationWarning className={className}>
{text}
</span>
)
}
export function SafeTime({ date, options, locale = DEFAULT_LOCALE, localize = false, className }: SafeDateProps) {
const mounted = useMounted()
const d = date instanceof Date ? date : new Date(date)
const useLocal = localize && mounted
const text = (options?.dateStyle ? d.toLocaleString : d.toLocaleTimeString).call(d, useLocal ? undefined : locale, {
timeZone: useLocal ? undefined : DEFAULT_TIME_ZONE,
...options,
})
return (
<span suppressHydrationWarning className={className}>
{text}
</span>
)
}
type SafeNumberProps = {
value: number
options?: Intl.NumberFormatOptions
locale?: string
/** ISO 4217 code, e.g. 'USD' — shorthand for style: 'currency'. */
currency?: string
localize?: boolean
className?: string
}
export function SafeNumber({ value, options, locale = DEFAULT_LOCALE, currency, localize = false, className }: SafeNumberProps) {
const mounted = useMounted()
const useLocal = localize && mounted
const text = value.toLocaleString(useLocal ? undefined : locale, {
...(currency ? { style: 'currency' as const, currency } : {}),
...options,
})
return (
<span suppressHydrationWarning className={className}>
{text}
</span>
)
}
+370
View File
@@ -0,0 +1,370 @@
'use client'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { Suspense, useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'
import { cn } from '@/lib/utils'
import {
Calendar, Tags, Users, Kanban, Link2, Settings, ChevronLeft, ChevronRight, ChevronDown,
FileText, Pin, PinOff, Plus, Shield, Search, MoreHorizontal, Trash2, Pencil, Layers, GripVertical,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { toast } from 'sonner'
import { PAGES_CHANGED, nextUntitledTitle, notifyPagesChanged, type PageSummary } from '@/lib/pages'
import { reorderPages } from '@/lib/page-order'
// Screens below are filters/views over the same bookmark collection, not
// separate data types. Pages are the primary interface objects.
const viewItems = [
{ href: '/bookmarks', label: 'All Bookmarks', icon: Link2 },
{ href: '/calendar', label: 'Calendar', icon: Calendar },
{ href: '/tags', label: 'Tags', icon: Tags },
{ href: '/kanban', label: 'Kanban', icon: Kanban },
{ href: '/collections', label: 'Collections', icon: Layers },
{ href: '/contacts', label: 'Contacts', icon: Users },
]
// Section collapse state persists per browser. useSyncExternalStore keeps it
// hydration-safe (server snapshot uses the default; the client snapshot reads
// localStorage after mount) without setState inside an effect.
const SECTION_STORE_EVENT = 'computer:sidebar-sections'
function readSection(key: string, fallback: boolean): boolean {
try {
const stored = window.localStorage.getItem(key)
return stored === '0' || stored === '1' ? stored === '1' : fallback
} catch { return fallback }
}
function usePersistentState(key: string, initial: boolean) {
const subscribe = useCallback((onChange: () => void) => {
window.addEventListener('storage', onChange)
window.addEventListener(SECTION_STORE_EVENT, onChange)
return () => {
window.removeEventListener('storage', onChange)
window.removeEventListener(SECTION_STORE_EVENT, onChange)
}
}, [])
const getSnapshot = useCallback(() => readSection(key, initial), [key, initial])
const getServerSnapshot = useCallback(() => initial, [initial])
const value = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
const update = useCallback((next: boolean) => {
try { window.localStorage.setItem(key, next ? '1' : '0') } catch { /* non-fatal */ }
window.dispatchEvent(new Event(SECTION_STORE_EVENT))
}, [key])
return [value, update] as const
}
interface SidebarProps {
open: boolean
onToggle: () => void
onQuickFind: () => void
pathname: string
isAdmin?: boolean
}
export function Sidebar({ open, onToggle, onQuickFind, pathname, isAdmin = false }: SidebarProps) {
return (
<aside
className={cn(
'flex flex-col border-r bg-[hsl(var(--sidebar))] text-[hsl(var(--sidebar-foreground))] transition-all duration-300 ease-in-out',
open ? 'w-60' : 'w-16'
)}
>
<div className="flex items-center gap-2 px-3 py-3">
<Link href="/pages" className="flex min-w-0 items-center gap-2">
<div className="flex h-6 w-6 shrink-0 items-center justify-center rounded bg-primary text-primary-foreground">
<Link2 className="h-3.5 w-3.5" />
</div>
{open && <span className="truncate font-display text-sm font-bold tracking-tight">computer</span>}
</Link>
</div>
<Suspense fallback={<div className="flex-1" />}>
<SidebarNav open={open} pathname={pathname} isAdmin={isAdmin} />
</Suspense>
<div className="space-y-0.5 border-t p-2">
<button
onClick={onQuickFind}
title="Quick find (Ctrl/⌘ K)"
className="flex w-full items-center gap-2 rounded-lg px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
>
<Search className="h-4 w-4 shrink-0" />
{open && <span className="flex-1 text-left">Quick find</span>}
{open && <kbd className="rounded border bg-background px-1 text-[10px] font-medium text-muted-foreground">⌘K</kbd>}
</button>
<Link
href="/settings"
className={cn(
'flex w-full items-center gap-2 rounded-lg px-3 py-1.5 text-sm transition-colors',
pathname === '/settings' ? 'bg-accent font-medium text-accent-foreground' : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
)}
>
<Settings className="h-4 w-4 shrink-0" />
{open && <span>Settings</span>}
</Link>
<Button variant="ghost" size="icon-sm" onClick={onToggle} className="w-full" aria-label={open ? 'Collapse sidebar' : 'Expand sidebar'}>
{open ? <ChevronLeft className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</Button>
</div>
</aside>
)
}
function SectionHeader({ label, open, expanded, onToggle, action }: {
label: string
open: boolean
expanded: boolean
onToggle: () => void
action?: { label: string; onClick: () => void }
}) {
if (!open) return null
return (
<div className="group/header flex items-center gap-0.5 rounded-md pr-1 hover:bg-accent/40">
<button onClick={onToggle} className="flex flex-1 items-center gap-1 px-2 py-1 text-left" aria-expanded={expanded}>
<ChevronDown className={cn('h-3 w-3 shrink-0 text-muted-foreground transition-transform', !expanded && '-rotate-90')} />
<span className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">{label}</span>
</button>
{action && (
<button
onClick={action.onClick}
title={action.label}
aria-label={action.label}
className="shrink-0 rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-accent hover:text-foreground group-hover/header:opacity-100 focus-visible:opacity-100"
>
<Plus className="h-3.5 w-3.5" />
</button>
)}
</div>
)
}
function SidebarNav({ open, pathname, isAdmin = false }: { open: boolean; pathname: string; isAdmin?: boolean }) {
const router = useRouter()
const searchParams = useSearchParams()
const [pages, setPages] = useState<PageSummary[]>([])
const [pagesExpanded, setPagesExpanded] = usePersistentState('computer:sidebar:pages', true)
const [viewsExpanded, setViewsExpanded] = usePersistentState('computer:sidebar:views', true)
const [renamingId, setRenamingId] = useState<string | null>(null)
const [renameValue, setRenameValue] = useState('')
const [pageDrop, setPageDrop] = useState<{ id: string; after: boolean } | null>(null)
const draggedPageRef = useRef<string | null>(null)
const activePageId = pathname === '/pages' ? searchParams.get('id') : null
const load = useCallback(() => {
fetch('/api/pages')
.then((r) => (r.ok ? r.json() : []))
.then((d: PageSummary[]) => setPages(d ?? []))
.catch((e) => console.error('Failed to load pages', e))
}, [])
useEffect(() => {
load()
window.addEventListener(PAGES_CHANGED, load)
return () => window.removeEventListener(PAGES_CHANGED, load)
}, [load])
const createPage = async () => {
const title = nextUntitledTitle(pages.map((p) => p.title))
try {
const res = await fetch('/api/pages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title }) })
if (!res.ok) { toast.error('Could not create page'); return }
const p = await res.json()
notifyPagesChanged()
router.push(`/pages?id=${p.id}`)
} catch { toast.error('Could not create page') }
}
const patchPage = async (id: string, body: Record<string, unknown>) => {
try {
const res = await fetch(`/api/pages/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
if (!res.ok) { toast.error('Could not update page'); return }
load()
notifyPagesChanged()
} catch { toast.error('Could not update page') }
}
const startRename = (p: PageSummary) => {
setRenamingId(p.id)
setRenameValue(p.title)
}
const commitRename = async (p: PageSummary) => {
const t = renameValue.trim()
setRenamingId(null)
if (!t || t === p.title) return
await patchPage(p.id, { title: t })
}
const removePage = async (p: PageSummary) => {
if (!confirm(`Delete page "${p.title}"? Bookmarks are kept.`)) return
try {
const res = await fetch(`/api/pages/${p.id}`, { method: 'DELETE' })
if (!res.ok) { toast.error('Could not delete page'); return }
load()
notifyPagesChanged()
} catch { toast.error('Could not delete page') }
}
const savePageOrder = async (next: PageSummary[]) => {
setPages(next)
try {
const res = await fetch('/api/pages', {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ order: next.map((p) => p.id) }),
})
if (!res.ok) { toast.error('Could not reorder pages'); load(); return }
notifyPagesChanged()
} catch {
toast.error('Could not reorder pages')
load()
}
}
const dropPage = (target: PageSummary, after: boolean) => {
const source = draggedPageRef.current
draggedPageRef.current = null
setPageDrop(null)
if (!source) return
const next = reorderPages(pages, source, target.id, after)
if (next === 'blocked') { toast.error('Pinned and unpinned pages keep separate groups'); return }
if (next) void savePageOrder(next)
}
const viewEntries = isAdmin ? [...viewItems, { href: '/admin', label: 'Admin', icon: Shield }] : viewItems
return (
<nav className="flex-1 space-y-0.5 overflow-y-auto p-2">
<SectionHeader label="Pages" open={open} expanded={pagesExpanded} onToggle={() => setPagesExpanded(!pagesExpanded)} action={{ label: 'New page', onClick: createPage }} />
{(pagesExpanded || !open) && pages.map((p) => {
const isActive = pathname === '/pages' && activePageId === p.id
if (renamingId === p.id) {
return (
<div key={p.id} className="px-1 py-0.5">
<Input
autoFocus
value={renameValue}
onChange={(e) => setRenameValue(e.target.value)}
onBlur={() => commitRename(p)}
onKeyDown={(e) => {
if (e.key === 'Enter') { e.preventDefault(); (e.target as HTMLInputElement).blur() }
if (e.key === 'Escape') setRenamingId(null)
}}
className="h-7 text-sm"
aria-label={`Rename page ${p.title}`}
/>
</div>
)
}
return (
<div
key={p.id}
data-page-id={p.id}
onDragOver={(e) => {
if (!draggedPageRef.current || draggedPageRef.current === p.id) return
e.preventDefault()
e.dataTransfer.dropEffect = 'move'
const rect = e.currentTarget.getBoundingClientRect()
setPageDrop({ id: p.id, after: e.clientY > rect.top + rect.height / 2 })
}}
onDragLeave={(e) => {
if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setPageDrop(null)
}}
onDrop={(e) => {
e.preventDefault()
const rect = e.currentTarget.getBoundingClientRect()
dropPage(p, e.clientY > rect.top + rect.height / 2)
}}
className={cn(
'group/row flex items-center rounded-lg pr-1 transition-colors',
isActive ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50',
pageDrop?.id === p.id && 'ring-1 ring-primary/50'
)}
>
{open && (
<span
data-page-drag-handle
draggable
onDragStart={(e) => {
draggedPageRef.current = p.id
e.dataTransfer.effectAllowed = 'move'
e.dataTransfer.setData('text/plain', p.id)
}}
onDragEnd={() => { draggedPageRef.current = null; setPageDrop(null) }}
className="ml-1 shrink-0 cursor-grab text-muted-foreground/40 opacity-0 transition-opacity hover:text-muted-foreground active:cursor-grabbing group-hover/row:opacity-100 focus-visible:opacity-100"
title="Drag to reorder page"
aria-label={`Drag page ${p.title}`}
>
<GripVertical className="h-3.5 w-3.5" />
</span>
)}
<Link href={`/pages?id=${p.id}`} className="flex min-w-0 flex-1 items-center gap-2 px-2 py-1.5 text-sm">
{p.pinned ? <Pin className="h-3.5 w-3.5 shrink-0 text-muted-foreground" /> : <FileText className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
{(open || isActive) && <span className={cn('truncate', isActive ? 'font-medium' : 'text-muted-foreground')}>{p.title}</span>}
</Link>
{open && (
<div className="flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover/row:opacity-100">
<button
onClick={createPage}
title="New page"
aria-label="New page"
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
>
<Plus className="h-3.5 w-3.5" />
</button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button title="Page actions" aria-label={`Actions for ${p.title}`} className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground">
<MoreHorizontal className="h-3.5 w-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-44">
<DropdownMenuItem onClick={() => patchPage(p.id, { pinned: !p.pinned })}>
{p.pinned ? <PinOff className="mr-2 h-3.5 w-3.5" /> : <Pin className="mr-2 h-3.5 w-3.5" />}
{p.pinned ? 'Unpin' : 'Pin to sidebar'}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => startRename(p)}>
<Pencil className="mr-2 h-3.5 w-3.5" />
Rename
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem className="text-destructive focus:text-destructive" onClick={() => removePage(p)}>
<Trash2 className="mr-2 h-3.5 w-3.5" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div>
)
})}
{open && pagesExpanded && pages.length === 0 && (
<p className="px-3 py-1 text-xs text-muted-foreground/70">No pages yet</p>
)}
<div className="pt-2">
<SectionHeader label="Views" open={open} expanded={viewsExpanded} onToggle={() => setViewsExpanded(!viewsExpanded)} />
{(viewsExpanded || !open) && viewEntries.map((item) => {
const isActive = pathname === item.href || pathname?.startsWith(item.href + '/')
return (
<Link
key={item.href}
href={item.href}
className={cn(
'flex items-center gap-2 rounded-lg px-2 py-1.5 text-sm transition-colors',
isActive ? 'bg-accent font-medium text-accent-foreground' : 'text-muted-foreground hover:bg-accent/50 hover:text-foreground'
)}
>
<item.icon className="h-4 w-4 shrink-0" />
{open && <span className="truncate">{item.label}</span>}
</Link>
)
})}
</div>
</nav>
)
}
+10
View File
@@ -0,0 +1,10 @@
"use client"
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
type ThemeProviderProps = React.ComponentProps<typeof NextThemesProvider>
export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}
+21
View File
@@ -0,0 +1,21 @@
'use client'
import { Moon, Sun } from 'lucide-react'
import { useTheme } from 'next-themes'
import { Button } from '@/components/ui/button'
export function ThemeToggle() {
const { theme, setTheme } = useTheme()
return (
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
>
<Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
)
}
+183
View File
@@ -0,0 +1,183 @@
'use client'
import { useEffect, useState } from 'react'
import { signOut } from 'next-auth/react'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
import { Search, Bell, Plus, Menu, LogOut, Sun, Moon } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from '@/components/ui/breadcrumb'
import { useTheme } from 'next-themes'
import { useMounted } from '@/components/client-only'
import { ACTIVE_PAGE_CHANGED } from '@/lib/pages'
// Notion keeps the top bar minimal: a breadcrumb path on the left, a subtle
// Quick Find pill, and ghost icon buttons on the right.
const SECTION_LABELS: Record<string, string> = {
'/bookmarks': 'All Bookmarks',
'/calendar': 'Calendar',
'/tags': 'Tags',
'/kanban': 'Kanban',
'/contacts': 'Contacts',
'/settings': 'Settings',
'/admin': 'Admin',
'/pages': 'Pages',
}
interface TopBarProps {
user: { id: string; name?: string | null; email?: string | null; image?: string | null }
alerts: any[]
onDismissAlert: (id: string) => void
onAddBookmark: () => void
onToggleSidebar: () => void
onQuickFind: () => void
}
export function TopBar({ user, alerts, onDismissAlert, onAddBookmark, onToggleSidebar, onQuickFind }: TopBarProps) {
const [showAlerts, setShowAlerts] = useState(false)
const pathname = usePathname()
const mounted = useMounted()
const { theme, setTheme } = useTheme()
const [activePageTitle, setActivePageTitle] = useState<string | null>(null)
// The pages workspace announces the open page so breadcrumbs can show it.
// The title only renders on /pages, so route changes need no reset effect.
useEffect(() => {
const handler = (e: Event) => setActivePageTitle((e as CustomEvent<string | null>).detail)
window.addEventListener(ACTIVE_PAGE_CHANGED, handler)
return () => window.removeEventListener(ACTIVE_PAGE_CHANGED, handler)
}, [])
const pageTitle = pathname === '/pages' ? activePageTitle : null
useEffect(() => {
const handler = (e: MouseEvent) => {
const el = document.getElementById('topbar-alerts')
if (el && !el.contains(e.target as Node)) setShowAlerts(false)
}
document.addEventListener('mousedown', handler)
return () => document.removeEventListener('mousedown', handler)
}, [])
const section = SECTION_LABELS[pathname] ?? 'computer'
const isMac = mounted && typeof navigator !== 'undefined' && /mac|iphone|ipad/i.test(navigator.userAgent)
const quickFindHint = !mounted ? '⌘K' : isMac ? '⌘K' : 'Ctrl K'
// Review CR-02: local sign-out is always available, but it is NOT the same
// claim as confirmed global revocation. Ask the trusted server to revoke
// (Go tokenVersion bump) first and report honestly when that fails — other
// devices and already-issued assertions then survive until the backend
// recovers, and the user is told so instead of being silently logged out.
const [signingOut, setSigningOut] = useState(false)
const doSignOut = async () => {
if (signingOut) return
setSigningOut(true)
let revoked = false
try {
const res = await fetch('/api/session/revoke', { method: 'POST' })
const data = await res.json().catch(() => null)
revoked = res.ok && data?.revoked === true
} catch { /* unreachable Next route — treated as a revocation failure below */ }
if (!revoked) {
toast.error('Signed out on this device, but global revocation failed — other sessions may remain signed in until the backend recovers.')
}
void signOut({ redirectTo: '/login' })
}
return (
<header className="flex items-center gap-2 border-b bg-card px-3 py-2">
<Button variant="ghost" size="icon-sm" onClick={onToggleSidebar} className="lg:hidden">
<Menu className="h-4 w-4" />
</Button>
<Breadcrumb className="min-w-0 flex-1">
<BreadcrumbList className="flex-nowrap">
<BreadcrumbItem>
<BreadcrumbLink asChild className="font-medium">
<Link href="/pages">computer</Link>
</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator />
<BreadcrumbItem className="min-w-0">
{pageTitle ? (
<>
<BreadcrumbLink asChild>
<Link href="/pages">Pages</Link>
</BreadcrumbLink>
<BreadcrumbSeparator />
<BreadcrumbPage className="truncate font-normal text-foreground">{pageTitle}</BreadcrumbPage>
</>
) : (
<BreadcrumbPage className="truncate font-normal text-foreground">{section}</BreadcrumbPage>
)}
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
<button
onClick={onQuickFind}
aria-label="Quick find"
className="flex shrink-0 items-center gap-2 rounded-md border border-border/60 bg-muted/40 px-2.5 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<Search className="h-3.5 w-3.5" />
<span className="hidden md:inline">Quick find</span>
<kbd className="pointer-events-none hidden select-none rounded border bg-background px-1.5 text-[10px] font-medium md:inline-flex">{quickFindHint}</kbd>
</button>
<Button variant="ghost" size="sm" onClick={onAddBookmark} className="shrink-0 gap-1.5">
<Plus className="h-4 w-4" />
<span className="hidden sm:inline">New</span>
</Button>
<Button variant="ghost" size="icon-sm" className="shrink-0" onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>
<Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
</Button>
<div className="relative shrink-0" id="topbar-alerts">
<Button variant="ghost" size="icon-sm" onClick={() => setShowAlerts(!showAlerts)}>
<Bell className="h-4 w-4" />
{(alerts?.length ?? 0) > 0 && (
<span className="absolute -top-0.5 -right-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-destructive text-[10px] text-destructive-foreground">
{alerts?.length ?? 0}
</span>
)}
</Button>
{showAlerts && (
<div className="absolute right-0 top-full mt-2 w-80 rounded-lg border bg-card p-2 shadow-lg z-50">
<p className="px-2 py-1 text-xs font-medium text-muted-foreground">Alerts</p>
{(alerts?.length ?? 0) === 0 && (
<p className="px-2 py-4 text-sm text-center text-muted-foreground">No pending alerts</p>
)}
{(alerts ?? []).map((a: any) => (
<div key={a?.id} className="flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted">
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{a?.title ?? 'Untitled'}</p>
<p className="text-xs text-muted-foreground">Alert due</p>
</div>
<Button variant="ghost" size="xs" onClick={() => onDismissAlert(a?.id)}>Dismiss</Button>
</div>
))}
</div>
)}
</div>
<div className="flex shrink-0 items-center gap-2 pl-1">
<div className="flex h-7 w-7 items-center justify-center rounded-full bg-primary text-primary-foreground text-xs font-bold">
{(user?.name ?? user?.email ?? '?')[0]?.toUpperCase()}
</div>
<span className="hidden sm:inline text-sm font-medium">{user?.name ?? user?.email ?? 'User'}</span>
<Button variant="ghost" size="icon-sm" onClick={doSignOut} disabled={signingOut} aria-label="Sign out">
<LogOut className="h-4 w-4" />
</Button>
</div>
</header>
)
}
+58
View File
@@ -0,0 +1,58 @@
'use client';
import * as React from 'react';
import * as AccordionPrimitive from '@radix-ui/react-accordion';
import { ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn('border-b', className)}
{...props}
/>
));
AccordionItem.displayName = 'AccordionItem';
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
'flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180',
className
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
));
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn('pb-4 pt-0', className)}>{children}</div>
</AccordionPrimitive.Content>
));
AccordionContent.displayName = AccordionPrimitive.Content.displayName;
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
+141
View File
@@ -0,0 +1,141 @@
'use client';
import * as React from 'react';
import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';
import { cn } from '@/lib/utils';
import { buttonVariants } from '@/components/ui/button';
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-2 text-center sm:text-left',
className
)}
{...props}
/>
);
AlertDialogHeader.displayName = 'AlertDialogHeader';
const AlertDialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
className
)}
{...props}
/>
);
AlertDialogFooter.displayName = 'AlertDialogFooter';
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn('text-lg font-semibold', className)}
{...props}
/>
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
AlertDialogDescription.displayName =
AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action
ref={ref}
className={cn(buttonVariants(), className)}
{...props}
/>
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(
buttonVariants({ variant: 'outline' }),
'mt-2 sm:mt-0',
className
)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};
+59
View File
@@ -0,0 +1,59 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const alertVariants = cva(
'relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground',
{
variants: {
variant: {
default: 'bg-background text-foreground',
destructive:
'border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive',
},
},
defaultVariants: {
variant: 'default',
},
}
);
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
));
Alert.displayName = 'Alert';
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn('mb-1 font-medium leading-none tracking-tight', className)}
{...props}
/>
));
AlertTitle.displayName = 'AlertTitle';
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn('text-sm [&_p]:leading-relaxed', className)}
{...props}
/>
));
AlertDescription.displayName = 'AlertDescription';
export { Alert, AlertTitle, AlertDescription };
+144
View File
@@ -0,0 +1,144 @@
'use client'
import { motion } from 'framer-motion'
const viewportConfig = { once: true, margin: '-60px' as `${number}px` }
export function FadeIn({
children, delay = 0, duration = 0.4, className,
}: {
children: React.ReactNode; delay?: number; duration?: number; className?: string
}) {
return (
<motion.div
initial={{ opacity: 0, y: 8 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={viewportConfig}
transition={{ duration, delay, ease: 'easeOut' }}
className={className}
>
{children}
</motion.div>
)
}
export function ScaleIn({
children, delay = 0, className,
}: {
children: React.ReactNode; delay?: number; className?: string
}) {
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
whileInView={{ opacity: 1, scale: 1 }}
viewport={viewportConfig}
transition={{ duration: 0.3, delay, ease: 'easeOut' }}
className={className}
>
{children}
</motion.div>
)
}
const slideDirections = {
bottom: { y: 20, x: 0 },
top: { y: -20, x: 0 },
left: { x: -20, y: 0 },
right: { x: 20, y: 0 },
}
export function SlideIn({
children, from = 'bottom', delay = 0, className,
}: {
children: React.ReactNode; from?: keyof typeof slideDirections; delay?: number; className?: string
}) {
return (
<motion.div
initial={{ opacity: 0, ...slideDirections[from] }}
whileInView={{ opacity: 1, x: 0, y: 0 }}
viewport={viewportConfig}
transition={{ duration: 0.4, delay, ease: 'easeOut' }}
className={className}
>
{children}
</motion.div>
)
}
export function Stagger({
children, staggerDelay = 0.08, className,
}: {
children: React.ReactNode; staggerDelay?: number; className?: string
}) {
return (
<motion.div
variants={{ show: { transition: { staggerChildren: staggerDelay } } }}
initial="hidden"
whileInView="show"
viewport={viewportConfig}
className={className}
>
{children}
</motion.div>
)
}
export function StaggerItem({
children, className,
}: {
children: React.ReactNode; className?: string
}) {
return (
<motion.div
variants={{
hidden: { opacity: 0, y: 16 },
show: { opacity: 1, y: 0, transition: { duration: 0.4, ease: 'easeOut' } },
}}
className={className}
>
{children}
</motion.div>
)
}
export function HoverLift({
children, className,
}: {
children: React.ReactNode; className?: string
}) {
return (
<motion.div
whileHover={{ y: -2, boxShadow: 'var(--shadow-lg)' }}
transition={{ duration: 0.15, ease: 'easeOut' }}
className={className}
>
{children}
</motion.div>
)
}
export function PressScale({
children, className,
}: {
children: React.ReactNode; className?: string
}) {
return (
<motion.div
whileTap={{ scale: 0.98 }}
transition={{ duration: 0.1, ease: 'easeOut' }}
className={className}
>
{children}
</motion.div>
)
}
export function SkeletonPulse({ className }: { className?: string }) {
return (
<motion.div
animate={{ opacity: [0.4, 1, 0.4] }}
transition={{ duration: 1.5, repeat: Infinity, ease: 'easeInOut' }}
className={`rounded-md bg-muted ${className ?? ''}`}
/>
)
}
+7
View File
@@ -0,0 +1,7 @@
'use client';
import * as AspectRatioPrimitive from '@radix-ui/react-aspect-ratio';
const AspectRatio = AspectRatioPrimitive.Root;
export { AspectRatio };
+50
View File
@@ -0,0 +1,50 @@
'use client';
import * as React from 'react';
import * as AvatarPrimitive from '@radix-ui/react-avatar';
import { cn } from '@/lib/utils';
const Avatar = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Root>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Root
ref={ref}
className={cn(
'relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full',
className
)}
{...props}
/>
));
Avatar.displayName = AvatarPrimitive.Root.displayName;
const AvatarImage = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Image>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Image>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Image
ref={ref}
className={cn('aspect-square h-full w-full', className)}
{...props}
/>
));
AvatarImage.displayName = AvatarPrimitive.Image.displayName;
const AvatarFallback = React.forwardRef<
React.ElementRef<typeof AvatarPrimitive.Fallback>,
React.ComponentPropsWithoutRef<typeof AvatarPrimitive.Fallback>
>(({ className, ...props }, ref) => (
<AvatarPrimitive.Fallback
ref={ref}
className={cn(
'flex h-full w-full items-center justify-center rounded-full bg-muted',
className
)}
{...props}
/>
));
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName;
export { Avatar, AvatarImage, AvatarFallback };
+36
View File
@@ -0,0 +1,36 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const badgeVariants = cva(
'inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2',
{
variants: {
variant: {
default:
'border-transparent bg-primary text-primary-foreground hover:bg-primary/80',
secondary:
'border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80',
destructive:
'border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80',
outline: 'text-foreground',
},
},
defaultVariants: {
variant: 'default',
},
}
);
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
);
}
export { Badge, badgeVariants };
+115
View File
@@ -0,0 +1,115 @@
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { ChevronRight, MoreHorizontal } from 'lucide-react';
import { cn } from '@/lib/utils';
const Breadcrumb = React.forwardRef<
HTMLElement,
React.ComponentPropsWithoutRef<'nav'> & {
separator?: React.ReactNode;
}
>(({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />);
Breadcrumb.displayName = 'Breadcrumb';
const BreadcrumbList = React.forwardRef<
HTMLOListElement,
React.ComponentPropsWithoutRef<'ol'>
>(({ className, ...props }, ref) => (
<ol
ref={ref}
className={cn(
'flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5',
className
)}
{...props}
/>
));
BreadcrumbList.displayName = 'BreadcrumbList';
const BreadcrumbItem = React.forwardRef<
HTMLLIElement,
React.ComponentPropsWithoutRef<'li'>
>(({ className, ...props }, ref) => (
<li
ref={ref}
className={cn('inline-flex items-center gap-1.5', className)}
{...props}
/>
));
BreadcrumbItem.displayName = 'BreadcrumbItem';
const BreadcrumbLink = React.forwardRef<
HTMLAnchorElement,
React.ComponentPropsWithoutRef<'a'> & {
asChild?: boolean;
}
>(({ asChild, className, ...props }, ref) => {
const Comp = asChild ? Slot : 'a';
return (
<Comp
ref={ref}
className={cn('transition-colors hover:text-foreground', className)}
{...props}
/>
);
});
BreadcrumbLink.displayName = 'BreadcrumbLink';
const BreadcrumbPage = React.forwardRef<
HTMLSpanElement,
React.ComponentPropsWithoutRef<'span'>
>(({ className, ...props }, ref) => (
<span
ref={ref}
role="link"
aria-disabled="true"
aria-current="page"
className={cn('font-normal text-foreground', className)}
{...props}
/>
));
BreadcrumbPage.displayName = 'BreadcrumbPage';
const BreadcrumbSeparator = ({
children,
className,
...props
}: React.ComponentProps<'li'>) => (
<li
role="presentation"
aria-hidden="true"
className={cn('[&>svg]:size-3.5', className)}
{...props}
>
{children ?? <ChevronRight />}
</li>
);
BreadcrumbSeparator.displayName = 'BreadcrumbSeparator';
const BreadcrumbEllipsis = ({
className,
...props
}: React.ComponentProps<'span'>) => (
<span
role="presentation"
aria-hidden="true"
className={cn('flex h-9 w-9 items-center justify-center', className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More</span>
</span>
);
BreadcrumbEllipsis.displayName = 'BreadcrumbElipssis';
export {
Breadcrumb,
BreadcrumbList,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
};
+72
View File
@@ -0,0 +1,72 @@
import * as React from "react"
import { Slot, Slottable } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { Loader2 } from "lucide-react"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium transition-all duration-fast focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background active:scale-[0.98] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:w-4 [&_svg]:h-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 hover:shadow-md",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90 hover:shadow-md",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground hover:border-accent hover:shadow-sm",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground",
"glass-dark":
"bg-white/10 backdrop-blur-md border border-white/20 [box-shadow:inset_0_0_0_1px_rgba(255,255,255,0.1)] text-foreground shadow-sm hover:bg-white/25 hover:border-white/40 hover:shadow-lg focus-visible:ring-white/50 focus-visible:ring-ring/0",
"glass-light":
"bg-black/[0.06] backdrop-blur-md border border-black/10 [box-shadow:inset_0_0_0_1px_rgba(255,255,255,0.5)] text-gray-900 shadow-sm hover:bg-black/[0.12] hover:border-black/20 hover:shadow-lg focus-visible:ring-black/30 focus-visible:ring-ring/0",
link:
"text-primary underline-offset-4 hover:underline focus-visible:underline focus-visible:ring-0 focus-visible:ring-offset-0",
},
size: {
default: "h-10 px-4 py-2",
xs: "h-7 rounded-md px-2 text-xs",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-lg px-6 text-base",
icon: "h-10 w-10",
"icon-sm": "h-8 w-8 rounded-md",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
loading?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, loading = false, disabled, children, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
disabled={disabled || loading}
aria-busy={loading || undefined}
{...props}
>
{loading && <Loader2 className="h-4 w-4 animate-spin" />}
<Slottable>{loading && asChild ? null : children}</Slottable>
</Comp>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
+66
View File
@@ -0,0 +1,66 @@
'use client';
import * as React from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { DayPicker } from 'react-day-picker';
import { cn } from '@/lib/utils';
import { buttonVariants } from '@/components/ui/button';
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
function Calendar({
className,
classNames,
showOutsideDays = true,
...props
}: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn('p-3', className)}
classNames={{
months: 'flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0',
month: 'space-y-4',
caption: 'flex justify-center pt-1 relative items-center',
caption_label: 'text-sm font-medium',
nav: 'space-x-1 flex items-center',
nav_button: cn(
buttonVariants({ variant: 'outline' }),
'h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100'
),
nav_button_previous: 'absolute left-1',
nav_button_next: 'absolute right-1',
table: 'w-full border-collapse space-y-1',
head_row: 'flex',
head_cell:
'text-muted-foreground rounded-md w-9 font-normal text-[0.8rem]',
row: 'flex w-full mt-2',
cell: 'h-9 w-9 text-center text-sm p-0 relative [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected])]:bg-accent first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md focus-within:relative focus-within:z-20',
day: cn(
buttonVariants({ variant: 'ghost' }),
'h-9 w-9 p-0 font-normal aria-selected:opacity-100'
),
day_range_end: 'day-range-end',
day_selected:
'bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground',
day_today: 'bg-accent text-accent-foreground',
day_outside:
'day-outside text-muted-foreground opacity-50 aria-selected:bg-accent/50 aria-selected:text-muted-foreground aria-selected:opacity-30',
day_disabled: 'text-muted-foreground opacity-50',
day_range_middle:
'aria-selected:bg-accent aria-selected:text-accent-foreground',
day_hidden: 'invisible',
...classNames,
}}
components={{
IconLeft: ({ ...props }) => <ChevronLeft className="h-4 w-4" />,
IconRight: ({ ...props }) => <ChevronRight className="h-4 w-4" />,
}}
{...props}
/>
);
}
Calendar.displayName = 'Calendar';
export { Calendar };
+106
View File
@@ -0,0 +1,106 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const cardVariants = cva(
"rounded-lg border bg-card text-card-foreground shadow-sm",
{
variants: {
variant: {
default: "",
interactive:
"transition-all duration-normal hover:shadow-md hover:-translate-y-0.5 hover:border-primary/20",
"glass-dark":
"bg-white/10 backdrop-blur-xl border border-white/20 shadow-md [box-shadow:inset_0_0_0_1px_rgba(255,255,255,0.15)]",
"glass-dark-interactive":
"bg-white/10 backdrop-blur-xl border border-white/20 shadow-md [box-shadow:inset_0_0_0_1px_rgba(255,255,255,0.15)] transition-all duration-normal hover:bg-white/15 hover:border-white/30 hover:shadow-lg hover:-translate-y-0.5",
"glass-light":
"bg-black/[0.04] backdrop-blur-xl border border-black/[0.08] shadow-md [box-shadow:inset_0_0_0_1px_rgba(255,255,255,0.5)] text-gray-900",
"glass-light-interactive":
"bg-black/[0.04] backdrop-blur-xl border border-black/[0.08] shadow-md [box-shadow:inset_0_0_0_1px_rgba(255,255,255,0.5)] text-gray-900 transition-all duration-normal hover:bg-black/[0.08] hover:border-black/[0.15] hover:shadow-lg hover:-translate-y-0.5",
ghost:
"border-transparent shadow-none bg-transparent",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface CardProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof cardVariants> {}
const Card = React.forwardRef<HTMLDivElement, CardProps>(
({ className, variant, ...props }, ref) => (
<div
ref={ref}
className={cn(cardVariants({ variant, className }))}
{...props}
/>
)
)
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h3
ref={ref}
className={cn(
"text-2xl font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, cardVariants, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
+263
View File
@@ -0,0 +1,263 @@
'use client';
import * as React from 'react';
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from 'embla-carousel-react';
import { ArrowLeft, ArrowRight } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
type CarouselApi = UseEmblaCarouselType[1];
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>;
type CarouselOptions = UseCarouselParameters[0];
type CarouselPlugin = UseCarouselParameters[1];
type CarouselProps = {
opts?: CarouselOptions;
plugins?: CarouselPlugin;
orientation?: 'horizontal' | 'vertical';
setApi?: (api: CarouselApi) => void;
};
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0];
api: ReturnType<typeof useEmblaCarousel>[1];
scrollPrev: () => void;
scrollNext: () => void;
canScrollPrev: boolean;
canScrollNext: boolean;
} & CarouselProps;
const CarouselContext = React.createContext<CarouselContextProps | null>(null);
function useCarousel() {
const context = React.useContext(CarouselContext);
if (!context) {
throw new Error('useCarousel must be used within a <Carousel />');
}
return context;
}
const Carousel = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & CarouselProps
>(
(
{
orientation = 'horizontal',
opts,
setApi,
plugins,
className,
children,
...props
},
ref
) => {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === 'horizontal' ? 'x' : 'y',
},
plugins
);
const [canScrollPrev, setCanScrollPrev] = React.useState(false);
const [canScrollNext, setCanScrollNext] = React.useState(false);
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) {
return;
}
setCanScrollPrev(api.canScrollPrev());
setCanScrollNext(api.canScrollNext());
}, []);
const scrollPrev = React.useCallback(() => {
api?.scrollPrev();
}, [api]);
const scrollNext = React.useCallback(() => {
api?.scrollNext();
}, [api]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'ArrowLeft') {
event.preventDefault();
scrollPrev();
} else if (event.key === 'ArrowRight') {
event.preventDefault();
scrollNext();
}
},
[scrollPrev, scrollNext]
);
React.useEffect(() => {
if (!api || !setApi) {
return;
}
setApi(api);
}, [api, setApi]);
React.useEffect(() => {
if (!api) {
return;
}
const timer = setTimeout(() => onSelect(api), 0);
api.on('reInit', onSelect);
api.on('select', onSelect);
return () => {
clearTimeout(timer);
api?.off('select', onSelect);
};
}, [api, onSelect]);
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === 'y' ? 'vertical' : 'horizontal'),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
ref={ref}
onKeyDownCapture={handleKeyDown}
className={cn('relative', className)}
role="region"
aria-roledescription="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
);
}
);
Carousel.displayName = 'Carousel';
const CarouselContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { carouselRef, orientation } = useCarousel();
return (
<div ref={carouselRef} className="overflow-hidden">
<div
ref={ref}
className={cn(
'flex',
orientation === 'horizontal' ? '-ml-4' : '-mt-4 flex-col',
className
)}
{...props}
/>
</div>
);
});
CarouselContent.displayName = 'CarouselContent';
const CarouselItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const { orientation } = useCarousel();
return (
<div
ref={ref}
role="group"
aria-roledescription="slide"
className={cn(
'min-w-0 shrink-0 grow-0 basis-full',
orientation === 'horizontal' ? 'pl-4' : 'pt-4',
className
)}
{...props}
/>
);
});
CarouselItem.displayName = 'CarouselItem';
const CarouselPrevious = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = 'outline', size = 'icon', ...props }, ref) => {
const { orientation, scrollPrev, canScrollPrev } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
'absolute h-8 w-8 rounded-full',
orientation === 'horizontal'
? '-left-12 top-1/2 -translate-y-1/2'
: '-top-12 left-1/2 -translate-x-1/2 rotate-90',
className
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft className="h-4 w-4" />
<span className="sr-only">Previous slide</span>
</Button>
);
});
CarouselPrevious.displayName = 'CarouselPrevious';
const CarouselNext = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<typeof Button>
>(({ className, variant = 'outline', size = 'icon', ...props }, ref) => {
const { orientation, scrollNext, canScrollNext } = useCarousel();
return (
<Button
ref={ref}
variant={variant}
size={size}
className={cn(
'absolute h-8 w-8 rounded-full',
orientation === 'horizontal'
? '-right-12 top-1/2 -translate-y-1/2'
: '-bottom-12 left-1/2 -translate-x-1/2 rotate-90',
className
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight className="h-4 w-4" />
<span className="sr-only">Next slide</span>
</Button>
);
});
CarouselNext.displayName = 'CarouselNext';
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
};
+30
View File
@@ -0,0 +1,30 @@
'use client';
import * as React from 'react';
import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
import { Check } from 'lucide-react';
import { cn } from '@/lib/utils';
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
'peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground',
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
className={cn('flex items-center justify-center text-current')}
>
<Check className="h-4 w-4" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };
+11
View File
@@ -0,0 +1,11 @@
'use client';
import * as CollapsiblePrimitive from '@radix-ui/react-collapsible';
const Collapsible = CollapsiblePrimitive.Root;
const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger;
const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent;
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
+155
View File
@@ -0,0 +1,155 @@
'use client';
import * as React from 'react';
import { type DialogProps } from '@radix-ui/react-dialog';
import { Command as CommandPrimitive } from 'cmdk';
import { Search } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Dialog, DialogContent } from '@/components/ui/dialog';
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive>
>(({ className, ...props }, ref) => (
<CommandPrimitive
ref={ref}
className={cn(
'flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground',
className
)}
{...props}
/>
));
Command.displayName = CommandPrimitive.displayName;
type CommandDialogProps = DialogProps
const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0 shadow-lg">
<Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
</Dialog>
);
};
const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
<div className="flex items-center border-b px-3" cmdk-input-wrapper="">
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
'flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50',
className
)}
{...props}
/>
</div>
));
CommandInput.displayName = CommandPrimitive.Input.displayName;
const CommandList = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.List>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
>(({ className, ...props }, ref) => (
<CommandPrimitive.List
ref={ref}
className={cn('max-h-[300px] overflow-y-auto overflow-x-hidden', className)}
{...props}
/>
));
CommandList.displayName = CommandPrimitive.List.displayName;
const CommandEmpty = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Empty>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
>((props, ref) => (
<CommandPrimitive.Empty
ref={ref}
className="py-6 text-center text-sm"
{...props}
/>
));
CommandEmpty.displayName = CommandPrimitive.Empty.displayName;
const CommandGroup = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Group>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Group
ref={ref}
className={cn(
'overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground',
className
)}
{...props}
/>
));
CommandGroup.displayName = CommandPrimitive.Group.displayName;
const CommandSeparator = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
className={cn('-mx-1 h-px bg-border', className)}
{...props}
/>
));
CommandSeparator.displayName = CommandPrimitive.Separator.displayName;
const CommandItem = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
>(({ className, ...props }, ref) => (
<CommandPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected='true']:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50",
className
)}
{...props}
/>
));
CommandItem.displayName = CommandPrimitive.Item.displayName;
const CommandShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
'ml-auto text-xs tracking-widest text-muted-foreground',
className
)}
{...props}
/>
);
};
CommandShortcut.displayName = 'CommandShortcut';
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
};
+200
View File
@@ -0,0 +1,200 @@
'use client';
import * as React from 'react';
import * as ContextMenuPrimitive from '@radix-ui/react-context-menu';
import { Check, ChevronRight, Circle } from 'lucide-react';
import { cn } from '@/lib/utils';
const ContextMenu = ContextMenuPrimitive.Root;
const ContextMenuTrigger = ContextMenuPrimitive.Trigger;
const ContextMenuGroup = ContextMenuPrimitive.Group;
const ContextMenuPortal = ContextMenuPrimitive.Portal;
const ContextMenuSub = ContextMenuPrimitive.Sub;
const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup;
const ContextMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<ContextMenuPrimitive.SubTrigger
ref={ref}
className={cn(
'flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground',
inset && 'pl-8',
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</ContextMenuPrimitive.SubTrigger>
));
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName;
const ContextMenuSubContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.SubContent
ref={ref}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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',
className
)}
{...props}
/>
));
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName;
const ContextMenuContent = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Content
ref={ref}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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',
className
)}
{...props}
/>
</ContextMenuPrimitive.Portal>
));
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName;
const ContextMenuItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Item
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
inset && 'pl-8',
className
)}
{...props}
/>
));
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName;
const ContextMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<ContextMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.CheckboxItem>
));
ContextMenuCheckboxItem.displayName =
ContextMenuPrimitive.CheckboxItem.displayName;
const ContextMenuRadioItem = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<ContextMenuPrimitive.RadioItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<ContextMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</ContextMenuPrimitive.ItemIndicator>
</span>
{children}
</ContextMenuPrimitive.RadioItem>
));
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName;
const ContextMenuLabel = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<ContextMenuPrimitive.Label
ref={ref}
className={cn(
'px-2 py-1.5 text-sm font-semibold text-foreground',
inset && 'pl-8',
className
)}
{...props}
/>
));
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName;
const ContextMenuSeparator = React.forwardRef<
React.ElementRef<typeof ContextMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<ContextMenuPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-border', className)}
{...props}
/>
));
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName;
const ContextMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
'ml-auto text-xs tracking-widest text-muted-foreground',
className
)}
{...props}
/>
);
};
ContextMenuShortcut.displayName = 'ContextMenuShortcut';
export {
ContextMenu,
ContextMenuTrigger,
ContextMenuContent,
ContextMenuItem,
ContextMenuCheckboxItem,
ContextMenuRadioItem,
ContextMenuLabel,
ContextMenuSeparator,
ContextMenuShortcut,
ContextMenuGroup,
ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuRadioGroup,
};
+65
View File
@@ -0,0 +1,65 @@
import * as React from "react";
import { format } from "date-fns";
import { Calendar as CalendarIcon } from "lucide-react";
import { DateRange } from "react-day-picker";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
interface DateRangePickerProps {
value: DateRange;
onChange: (value: DateRange) => void;
className?: string;
}
export function DateRangePicker({
value,
onChange,
className,
}: DateRangePickerProps) {
return (
<div className={cn("grid gap-2", className)}>
<Popover>
<PopoverTrigger asChild>
<Button
id="date"
variant={"outline"}
className={cn(
"w-[300px] justify-start text-left font-normal",
!value && "text-muted-foreground"
)}
>
<CalendarIcon className="mr-2 h-4 w-4" />
{value?.from ? (
value.to ? (
<>
{format(value.from, "LLL dd, y")} -{" "}
{format(value.to, "LLL dd, y")}
</>
) : (
format(value.from, "LLL dd, y")
)
) : (
<span>Pick a date range</span>
)}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
initialFocus
mode="range"
defaultMonth={value?.from}
selected={value}
onSelect={(value) => onChange(value as DateRange)}
numberOfMonths={2}
/>
</PopoverContent>
</Popover>
</div>
);
}
+122
View File
@@ -0,0 +1,122 @@
'use client';
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg',
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-1.5 text-center sm:text-left',
className
)}
{...props}
/>
);
DialogHeader.displayName = 'DialogHeader';
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
className
)}
{...props}
/>
);
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
'text-lg font-semibold leading-none tracking-tight',
className
)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
+118
View File
@@ -0,0 +1,118 @@
'use client';
import * as React from 'react';
import { Drawer as DrawerPrimitive } from 'vaul';
import { cn } from '@/lib/utils';
const Drawer = ({
shouldScaleBackground = true,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
<DrawerPrimitive.Root
shouldScaleBackground={shouldScaleBackground}
{...props}
/>
);
Drawer.displayName = 'Drawer';
const DrawerTrigger = DrawerPrimitive.Trigger;
const DrawerPortal = DrawerPrimitive.Portal;
const DrawerClose = DrawerPrimitive.Close;
const DrawerOverlay = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Overlay
ref={ref}
className={cn('fixed inset-0 z-50 bg-black/80', className)}
{...props}
/>
));
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName;
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
'fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background',
className
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
));
DrawerContent.displayName = 'DrawerContent';
const DrawerHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn('grid gap-1.5 p-4 text-center sm:text-left', className)}
{...props}
/>
);
DrawerHeader.displayName = 'DrawerHeader';
const DrawerFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn('mt-auto flex flex-col gap-2 p-4', className)}
{...props}
/>
);
DrawerFooter.displayName = 'DrawerFooter';
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Title
ref={ref}
className={cn(
'text-lg font-semibold leading-none tracking-tight',
className
)}
{...props}
/>
));
DrawerTitle.displayName = DrawerPrimitive.Title.displayName;
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
DrawerDescription.displayName = DrawerPrimitive.Description.displayName;
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
};
+200
View File
@@ -0,0 +1,200 @@
'use client';
import * as React from 'react';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
import { Check, ChevronRight, Circle } from 'lucide-react';
import { cn } from '@/lib/utils';
const DropdownMenu = DropdownMenuPrimitive.Root;
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
const DropdownMenuGroup = DropdownMenuPrimitive.Group;
const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
const DropdownMenuSub = DropdownMenuPrimitive.Sub;
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
'flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent',
inset && 'pl-8',
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</DropdownMenuPrimitive.SubTrigger>
));
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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',
className
)}
{...props}
/>
));
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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',
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
));
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
inset && 'pl-8',
className
)}
{...props}
/>
));
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
));
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
));
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
'px-2 py-1.5 text-sm font-semibold',
inset && 'pl-8',
className
)}
{...props}
/>
));
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn('ml-auto text-xs tracking-widest opacity-60', className)}
{...props}
/>
);
};
DropdownMenuShortcut.displayName = 'DropdownMenuShortcut';
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
};
+179
View File
@@ -0,0 +1,179 @@
'use client';
import * as React from 'react';
import * as LabelPrimitive from '@radix-ui/react-label';
import { Slot } from '@radix-ui/react-slot';
import {
Controller,
ControllerProps,
FieldPath,
FieldValues,
FormProvider,
useFormContext,
} from 'react-hook-form';
import { cn } from '@/lib/utils';
import { Label } from '@/components/ui/label';
const Form = FormProvider;
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName;
};
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
);
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
);
};
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext);
const itemContext = React.useContext(FormItemContext);
const { getFieldState, formState } = useFormContext();
const fieldState = getFieldState(fieldContext.name, formState);
if (!fieldContext) {
throw new Error('useFormField should be used within <FormField>');
}
const { id } = itemContext;
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
};
};
type FormItemContextValue = {
id: string;
};
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
);
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId();
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn('space-y-2', className)} {...props} />
</FormItemContext.Provider>
);
});
FormItem.displayName = 'FormItem';
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField();
return (
<Label
ref={ref}
className={cn(error && 'text-destructive', className)}
htmlFor={formItemId}
{...props}
/>
);
});
FormLabel.displayName = 'FormLabel';
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } =
useFormField();
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
);
});
FormControl.displayName = 'FormControl';
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField();
return (
<p
ref={ref}
id={formDescriptionId}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
);
});
FormDescription.displayName = 'FormDescription';
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField();
const body = error ? String(error?.message) : children;
if (!body) {
return null;
}
return (
<p
ref={ref}
id={formMessageId}
className={cn('text-sm font-medium text-destructive', className)}
{...props}
>
{body}
</p>
);
});
FormMessage.displayName = 'FormMessage';
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
};
+29
View File
@@ -0,0 +1,29 @@
'use client';
import * as React from 'react';
import * as HoverCardPrimitive from '@radix-ui/react-hover-card';
import { cn } from '@/lib/utils';
const HoverCard = HoverCardPrimitive.Root;
const HoverCardTrigger = HoverCardPrimitive.Trigger;
const HoverCardContent = React.forwardRef<
React.ElementRef<typeof HoverCardPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof HoverCardPrimitive.Content>
>(({ className, align = 'center', sideOffset = 4, ...props }, ref) => (
<HoverCardPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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',
className
)}
{...props}
/>
));
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName;
export { HoverCard, HoverCardTrigger, HoverCardContent };
+71
View File
@@ -0,0 +1,71 @@
'use client';
import * as React from 'react';
import { OTPInput, OTPInputContext } from 'input-otp';
import { Dot } from 'lucide-react';
import { cn } from '@/lib/utils';
const InputOTP = React.forwardRef<
React.ElementRef<typeof OTPInput>,
React.ComponentPropsWithoutRef<typeof OTPInput>
>(({ className, containerClassName, ...props }, ref) => (
<OTPInput
ref={ref}
containerClassName={cn(
'flex items-center gap-2 has-[:disabled]:opacity-50',
containerClassName
)}
className={cn('disabled:cursor-not-allowed', className)}
{...props}
/>
));
InputOTP.displayName = 'InputOTP';
const InputOTPGroup = React.forwardRef<
React.ElementRef<'div'>,
React.ComponentPropsWithoutRef<'div'>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn('flex items-center', className)} {...props} />
));
InputOTPGroup.displayName = 'InputOTPGroup';
const InputOTPSlot = React.forwardRef<
React.ElementRef<'div'>,
React.ComponentPropsWithoutRef<'div'> & { index: number }
>(({ index, className, ...props }, ref) => {
const inputOTPContext = React.useContext(OTPInputContext);
const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index];
return (
<div
ref={ref}
className={cn(
'relative flex h-10 w-10 items-center justify-center border-y border-r border-input text-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md',
isActive && 'z-10 ring-2 ring-ring ring-offset-background',
className
)}
{...props}
>
{char}
{hasFakeCaret && (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
</div>
)}
</div>
);
});
InputOTPSlot.displayName = 'InputOTPSlot';
const InputOTPSeparator = React.forwardRef<
React.ElementRef<'div'>,
React.ComponentPropsWithoutRef<'div'>
>(({ ...props }, ref) => (
<div ref={ref} role="separator" {...props}>
<Dot />
</div>
));
InputOTPSeparator.displayName = 'InputOTPSeparator';
export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };
+47
View File
@@ -0,0 +1,47 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const inputVariants = cva(
"flex w-full rounded-lg border bg-background text-sm transition-all duration-fast file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",
{
variants: {
variant: {
default: "border-input hover:border-ring/50 focus-visible:border-input focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
error: "border-destructive hover:border-destructive focus-visible:border-destructive focus-visible:ring-2 focus-visible:ring-destructive focus-visible:ring-offset-2 focus-visible:ring-offset-background",
success: "border-emerald-500 hover:border-emerald-500 focus-visible:border-emerald-500 focus-visible:ring-2 focus-visible:ring-emerald-500/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background",
ghost: "border-transparent bg-muted/50 hover:bg-muted focus-visible:bg-background focus-visible:border-input focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
},
size: {
default: "h-10 px-3 py-2",
sm: "h-8 px-2.5 py-1 text-xs rounded-md",
lg: "h-12 px-4 py-3 text-base rounded-lg",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface InputProps
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "size">,
VariantProps<typeof inputVariants> {}
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, variant, size, ...props }, ref) => {
return (
<input
type={type}
className={cn(inputVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input, inputVariants }
+26
View File
@@ -0,0 +1,26 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }
+236
View File
@@ -0,0 +1,236 @@
'use client';
import * as React from 'react';
import * as MenubarPrimitive from '@radix-ui/react-menubar';
import { Check, ChevronRight, Circle } from 'lucide-react';
import { cn } from '@/lib/utils';
const MenubarMenu = MenubarPrimitive.Menu;
const MenubarGroup = MenubarPrimitive.Group;
const MenubarPortal = MenubarPrimitive.Portal;
const MenubarSub = MenubarPrimitive.Sub;
const MenubarRadioGroup = MenubarPrimitive.RadioGroup;
const Menubar = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Root>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Root
ref={ref}
className={cn(
'flex h-10 items-center space-x-1 rounded-md border bg-background p-1',
className
)}
{...props}
/>
));
Menubar.displayName = MenubarPrimitive.Root.displayName;
const MenubarTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Trigger
ref={ref}
className={cn(
'flex cursor-default select-none items-center rounded-sm px-3 py-1.5 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground',
className
)}
{...props}
/>
));
MenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName;
const MenubarSubTrigger = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubTrigger> & {
inset?: boolean;
}
>(({ className, inset, children, ...props }, ref) => (
<MenubarPrimitive.SubTrigger
ref={ref}
className={cn(
'flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground',
inset && 'pl-8',
className
)}
{...props}
>
{children}
<ChevronRight className="ml-auto h-4 w-4" />
</MenubarPrimitive.SubTrigger>
));
MenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName;
const MenubarSubContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.SubContent
ref={ref}
className={cn(
'z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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',
className
)}
{...props}
/>
));
MenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName;
const MenubarContent = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Content>
>(
(
{ className, align = 'start', alignOffset = -4, sideOffset = 8, ...props },
ref
) => (
<MenubarPrimitive.Portal>
<MenubarPrimitive.Content
ref={ref}
align={align}
alignOffset={alignOffset}
sideOffset={sideOffset}
className={cn(
'z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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',
className
)}
{...props}
/>
</MenubarPrimitive.Portal>
)
);
MenubarContent.displayName = MenubarPrimitive.Content.displayName;
const MenubarItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Item> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Item
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
inset && 'pl-8',
className
)}
{...props}
/>
));
MenubarItem.displayName = MenubarPrimitive.Item.displayName;
const MenubarCheckboxItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<MenubarPrimitive.CheckboxItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.CheckboxItem>
));
MenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName;
const MenubarRadioItem = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<MenubarPrimitive.RadioItem
ref={ref}
className={cn(
'relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<MenubarPrimitive.ItemIndicator>
<Circle className="h-2 w-2 fill-current" />
</MenubarPrimitive.ItemIndicator>
</span>
{children}
</MenubarPrimitive.RadioItem>
));
MenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName;
const MenubarLabel = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Label> & {
inset?: boolean;
}
>(({ className, inset, ...props }, ref) => (
<MenubarPrimitive.Label
ref={ref}
className={cn(
'px-2 py-1.5 text-sm font-semibold',
inset && 'pl-8',
className
)}
{...props}
/>
));
MenubarLabel.displayName = MenubarPrimitive.Label.displayName;
const MenubarSeparator = React.forwardRef<
React.ElementRef<typeof MenubarPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof MenubarPrimitive.Separator>
>(({ className, ...props }, ref) => (
<MenubarPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
MenubarSeparator.displayName = MenubarPrimitive.Separator.displayName;
const MenubarShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn(
'ml-auto text-xs tracking-widest text-muted-foreground',
className
)}
{...props}
/>
);
};
MenubarShortcut.displayname = 'MenubarShortcut';
export {
Menubar,
MenubarMenu,
MenubarTrigger,
MenubarContent,
MenubarItem,
MenubarSeparator,
MenubarLabel,
MenubarCheckboxItem,
MenubarRadioGroup,
MenubarRadioItem,
MenubarPortal,
MenubarSubContent,
MenubarSubTrigger,
MenubarGroup,
MenubarSub,
MenubarShortcut,
};
+128
View File
@@ -0,0 +1,128 @@
import * as React from 'react';
import * as NavigationMenuPrimitive from '@radix-ui/react-navigation-menu';
import { cva } from 'class-variance-authority';
import { ChevronDown } from 'lucide-react';
import { cn } from '@/lib/utils';
const NavigationMenu = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Root
ref={ref}
className={cn(
'relative z-10 flex max-w-max flex-1 items-center justify-center',
className
)}
{...props}
>
{children}
<NavigationMenuViewport />
</NavigationMenuPrimitive.Root>
));
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName;
const NavigationMenuList = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.List>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.List>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.List
ref={ref}
className={cn(
'group flex flex-1 list-none items-center justify-center space-x-1',
className
)}
{...props}
/>
));
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName;
const NavigationMenuItem = NavigationMenuPrimitive.Item;
const navigationMenuTriggerStyle = cva(
'group inline-flex h-10 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50'
);
const NavigationMenuTrigger = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<NavigationMenuPrimitive.Trigger
ref={ref}
className={cn(navigationMenuTriggerStyle(), 'group', className)}
{...props}
>
{children}{' '}
<ChevronDown
className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180"
aria-hidden="true"
/>
</NavigationMenuPrimitive.Trigger>
));
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName;
const NavigationMenuContent = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Content>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Content
ref={ref}
className={cn(
'left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ',
className
)}
{...props}
/>
));
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName;
const NavigationMenuLink = NavigationMenuPrimitive.Link;
const NavigationMenuViewport = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Viewport>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Viewport>
>(({ className, ...props }, ref) => (
<div className={cn('absolute left-0 top-full flex justify-center')}>
<NavigationMenuPrimitive.Viewport
className={cn(
'origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]',
className
)}
ref={ref}
{...props}
/>
</div>
));
NavigationMenuViewport.displayName =
NavigationMenuPrimitive.Viewport.displayName;
const NavigationMenuIndicator = React.forwardRef<
React.ElementRef<typeof NavigationMenuPrimitive.Indicator>,
React.ComponentPropsWithoutRef<typeof NavigationMenuPrimitive.Indicator>
>(({ className, ...props }, ref) => (
<NavigationMenuPrimitive.Indicator
ref={ref}
className={cn(
'top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in',
className
)}
{...props}
>
<div className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
</NavigationMenuPrimitive.Indicator>
));
NavigationMenuIndicator.displayName =
NavigationMenuPrimitive.Indicator.displayName;
export {
navigationMenuTriggerStyle,
NavigationMenu,
NavigationMenuList,
NavigationMenuItem,
NavigationMenuContent,
NavigationMenuTrigger,
NavigationMenuLink,
NavigationMenuIndicator,
NavigationMenuViewport,
};
+117
View File
@@ -0,0 +1,117 @@
import * as React from 'react';
import { ChevronLeft, ChevronRight, MoreHorizontal } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ButtonProps, buttonVariants } from '@/components/ui/button';
const Pagination = ({ className, ...props }: React.ComponentProps<'nav'>) => (
<nav
role="navigation"
aria-label="pagination"
className={cn('mx-auto flex w-full justify-center', className)}
{...props}
/>
);
Pagination.displayName = 'Pagination';
const PaginationContent = React.forwardRef<
HTMLUListElement,
React.ComponentProps<'ul'>
>(({ className, ...props }, ref) => (
<ul
ref={ref}
className={cn('flex flex-row items-center gap-1', className)}
{...props}
/>
));
PaginationContent.displayName = 'PaginationContent';
const PaginationItem = React.forwardRef<
HTMLLIElement,
React.ComponentProps<'li'>
>(({ className, ...props }, ref) => (
<li ref={ref} className={cn('', className)} {...props} />
));
PaginationItem.displayName = 'PaginationItem';
type PaginationLinkProps = {
isActive?: boolean;
} & Pick<ButtonProps, 'size'> &
React.ComponentProps<'a'>;
const PaginationLink = ({
className,
isActive,
size = 'icon',
...props
}: PaginationLinkProps) => (
<a
aria-current={isActive ? 'page' : undefined}
className={cn(
buttonVariants({
variant: isActive ? 'outline' : 'ghost',
size,
}),
className
)}
{...props}
/>
);
PaginationLink.displayName = 'PaginationLink';
const PaginationPrevious = ({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink
aria-label="Go to previous page"
size="default"
className={cn('gap-1 pl-2.5', className)}
{...props}
>
<ChevronLeft className="h-4 w-4" />
<span>Previous</span>
</PaginationLink>
);
PaginationPrevious.displayName = 'PaginationPrevious';
const PaginationNext = ({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) => (
<PaginationLink
aria-label="Go to next page"
size="default"
className={cn('gap-1 pr-2.5', className)}
{...props}
>
<span>Next</span>
<ChevronRight className="h-4 w-4" />
</PaginationLink>
);
PaginationNext.displayName = 'PaginationNext';
const PaginationEllipsis = ({
className,
...props
}: React.ComponentProps<'span'>) => (
<span
aria-hidden
className={cn('flex h-9 w-9 items-center justify-center', className)}
{...props}
>
<MoreHorizontal className="h-4 w-4" />
<span className="sr-only">More pages</span>
</span>
);
PaginationEllipsis.displayName = 'PaginationEllipsis';
export {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
};
+31
View File
@@ -0,0 +1,31 @@
'use client';
import * as React from 'react';
import * as PopoverPrimitive from '@radix-ui/react-popover';
import { cn } from '@/lib/utils';
const Popover = PopoverPrimitive.Root;
const PopoverTrigger = PopoverPrimitive.Trigger;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = 'center', sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
'z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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',
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
));
PopoverContent.displayName = PopoverPrimitive.Content.displayName;
export { Popover, PopoverTrigger, PopoverContent };
+28
View File
@@ -0,0 +1,28 @@
'use client';
import * as React from 'react';
import * as ProgressPrimitive from '@radix-ui/react-progress';
import { cn } from '@/lib/utils';
const Progress = React.forwardRef<
React.ElementRef<typeof ProgressPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root>
>(({ className, value, ...props }, ref) => (
<ProgressPrimitive.Root
ref={ref}
className={cn(
'relative h-4 w-full overflow-hidden rounded-full bg-secondary',
className
)}
{...props}
>
<ProgressPrimitive.Indicator
className="h-full w-full flex-1 bg-primary transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
));
Progress.displayName = ProgressPrimitive.Root.displayName;
export { Progress };
+44
View File
@@ -0,0 +1,44 @@
'use client';
import * as React from 'react';
import * as RadioGroupPrimitive from '@radix-ui/react-radio-group';
import { Circle } from 'lucide-react';
import { cn } from '@/lib/utils';
const RadioGroup = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Root
className={cn('grid gap-2', className)}
{...props}
ref={ref}
/>
);
});
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName;
const RadioGroupItem = React.forwardRef<
React.ElementRef<typeof RadioGroupPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item
ref={ref}
className={cn(
'aspect-square h-4 w-4 rounded-full border border-primary text-primary ring-offset-background focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator className="flex items-center justify-center">
<Circle className="h-2.5 w-2.5 fill-current text-current" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
});
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;
export { RadioGroup, RadioGroupItem };
+45
View File
@@ -0,0 +1,45 @@
'use client';
import { GripVertical } from 'lucide-react';
import * as ResizablePrimitive from 'react-resizable-panels';
import { cn } from '@/lib/utils';
const ResizablePanelGroup = ({
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelGroup>) => (
<ResizablePrimitive.PanelGroup
className={cn(
'flex h-full w-full data-[panel-group-direction=vertical]:flex-col',
className
)}
{...props}
/>
);
const ResizablePanel = ResizablePrimitive.Panel;
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
withHandle?: boolean;
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
'relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90',
className
)}
{...props}
>
{withHandle && (
<div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
<GripVertical className="h-2.5 w-2.5" />
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
);
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };
+48
View File
@@ -0,0 +1,48 @@
'use client';
import * as React from 'react';
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
import { cn } from '@/lib/utils';
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn('relative overflow-hidden', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
));
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName;
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = 'vertical', ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
'flex touch-none select-none transition-colors',
orientation === 'vertical' &&
'h-full w-2.5 border-l border-l-transparent p-[1px]',
orientation === 'horizontal' &&
'h-2.5 flex-col border-t border-t-transparent p-[1px]',
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
));
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;
export { ScrollArea, ScrollBar };
+160
View File
@@ -0,0 +1,160 @@
'use client';
import * as React from 'react';
import * as SelectPrimitive from '@radix-ui/react-select';
import { Check, ChevronDown, ChevronUp } from 'lucide-react';
import { cn } from '@/lib/utils';
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
'flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
'flex cursor-default items-center justify-center py-1',
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
'flex cursor-default items-center justify-center py-1',
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = 'popper', ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 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',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
'p-1',
position === 'popper' &&
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]'
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn('py-1.5 pl-8 pr-2 text-sm font-semibold', className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};
+31
View File
@@ -0,0 +1,31 @@
'use client';
import * as React from 'react';
import * as SeparatorPrimitive from '@radix-ui/react-separator';
import { cn } from '@/lib/utils';
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = 'horizontal', decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
'shrink-0 bg-border',
orientation === 'horizontal' ? 'h-[1px] w-full' : 'h-full w-[1px]',
className
)}
{...props}
/>
)
);
Separator.displayName = SeparatorPrimitive.Root.displayName;
export { Separator };
+140
View File
@@ -0,0 +1,140 @@
'use client';
import * as React from 'react';
import * as SheetPrimitive from '@radix-ui/react-dialog';
import { cva, type VariantProps } from 'class-variance-authority';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
const Sheet = SheetPrimitive.Root;
const SheetTrigger = SheetPrimitive.Trigger;
const SheetClose = SheetPrimitive.Close;
const SheetPortal = SheetPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Overlay
className={cn(
'fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className
)}
{...props}
ref={ref}
/>
));
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName;
const sheetVariants = cva(
'fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500',
{
variants: {
side: {
top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top',
bottom:
'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom',
left: 'inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm',
right:
'inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm',
},
},
defaultVariants: {
side: 'right',
},
}
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof SheetPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Content>,
SheetContentProps
>(({ side = 'right', className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
ref={ref}
className={cn(sheetVariants({ side }), className)}
{...props}
>
{children}
<SheetPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
));
SheetContent.displayName = SheetPrimitive.Content.displayName;
const SheetHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col space-y-2 text-center sm:text-left',
className
)}
{...props}
/>
);
SheetHeader.displayName = 'SheetHeader';
const SheetFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
'flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2',
className
)}
{...props}
/>
);
SheetFooter.displayName = 'SheetFooter';
const SheetTitle = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Title
ref={ref}
className={cn('text-lg font-semibold text-foreground', className)}
{...props}
/>
));
SheetTitle.displayName = SheetPrimitive.Title.displayName;
const SheetDescription = React.forwardRef<
React.ElementRef<typeof SheetPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof SheetPrimitive.Description>
>(({ className, ...props }, ref) => (
<SheetPrimitive.Description
ref={ref}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
));
SheetDescription.displayName = SheetPrimitive.Description.displayName;
export {
Sheet,
SheetPortal,
SheetOverlay,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
};
+15
View File
@@ -0,0 +1,15 @@
import { cn } from '@/lib/utils';
function Skeleton({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) {
return (
<div
className={cn('animate-pulse rounded-md bg-muted', className)}
{...props}
/>
);
}
export { Skeleton };
+28
View File
@@ -0,0 +1,28 @@
'use client';
import * as React from 'react';
import * as SliderPrimitive from '@radix-ui/react-slider';
import { cn } from '@/lib/utils';
const Slider = React.forwardRef<
React.ElementRef<typeof SliderPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
<SliderPrimitive.Root
ref={ref}
className={cn(
'relative flex w-full touch-none select-none items-center',
className
)}
{...props}
>
<SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-secondary">
<SliderPrimitive.Range className="absolute h-full bg-primary" />
</SliderPrimitive.Track>
<SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-primary bg-background ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50" />
</SliderPrimitive.Root>
));
Slider.displayName = SliderPrimitive.Root.displayName;
export { Slider };
+31
View File
@@ -0,0 +1,31 @@
'use client';
import { useTheme } from 'next-themes';
import { Toaster as Sonner } from 'sonner';
type ToasterProps = React.ComponentProps<typeof Sonner>;
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = 'system' } = useTheme();
return (
<Sonner
theme={theme as ToasterProps['theme']}
className="toaster group"
toastOptions={{
classNames: {
toast:
'group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg',
description: 'group-[.toast]:text-muted-foreground',
actionButton:
'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',
cancelButton:
'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',
},
}}
{...props}
/>
);
};
export { Toaster };
+29
View File
@@ -0,0 +1,29 @@
'use client';
import * as React from 'react';
import * as SwitchPrimitives from '@radix-ui/react-switch';
import { cn } from '@/lib/utils';
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
'peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input',
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
'pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0'
)}
/>
</SwitchPrimitives.Root>
));
Switch.displayName = SwitchPrimitives.Root.displayName;
export { Switch };
+117
View File
@@ -0,0 +1,117 @@
import * as React from 'react';
import { cn } from '@/lib/utils';
const Table = React.forwardRef<
HTMLTableElement,
React.HTMLAttributes<HTMLTableElement>
>(({ className, ...props }, ref) => (
<div className="relative w-full overflow-auto">
<table
ref={ref}
className={cn('w-full caption-bottom text-sm', className)}
{...props}
/>
</div>
));
Table.displayName = 'Table';
const TableHeader = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<thead ref={ref} className={cn('[&_tr]:border-b', className)} {...props} />
));
TableHeader.displayName = 'TableHeader';
const TableBody = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tbody
ref={ref}
className={cn('[&_tr:last-child]:border-0', className)}
{...props}
/>
));
TableBody.displayName = 'TableBody';
const TableFooter = React.forwardRef<
HTMLTableSectionElement,
React.HTMLAttributes<HTMLTableSectionElement>
>(({ className, ...props }, ref) => (
<tfoot
ref={ref}
className={cn(
'border-t bg-muted/50 font-medium [&>tr]:last:border-b-0',
className
)}
{...props}
/>
));
TableFooter.displayName = 'TableFooter';
const TableRow = React.forwardRef<
HTMLTableRowElement,
React.HTMLAttributes<HTMLTableRowElement>
>(({ className, ...props }, ref) => (
<tr
ref={ref}
className={cn(
'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted',
className
)}
{...props}
/>
));
TableRow.displayName = 'TableRow';
const TableHead = React.forwardRef<
HTMLTableCellElement,
React.ThHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<th
ref={ref}
className={cn(
'h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0',
className
)}
{...props}
/>
));
TableHead.displayName = 'TableHead';
const TableCell = React.forwardRef<
HTMLTableCellElement,
React.TdHTMLAttributes<HTMLTableCellElement>
>(({ className, ...props }, ref) => (
<td
ref={ref}
className={cn('p-4 align-middle [&:has([role=checkbox])]:pr-0', className)}
{...props}
/>
));
TableCell.displayName = 'TableCell';
const TableCaption = React.forwardRef<
HTMLTableCaptionElement,
React.HTMLAttributes<HTMLTableCaptionElement>
>(({ className, ...props }, ref) => (
<caption
ref={ref}
className={cn('mt-4 text-sm text-muted-foreground', className)}
{...props}
/>
));
TableCaption.displayName = 'TableCaption';
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
};
+55
View File
@@ -0,0 +1,55 @@
'use client';
import * as React from 'react';
import * as TabsPrimitive from '@radix-ui/react-tabs';
import { cn } from '@/lib/utils';
const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
'inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground',
className
)}
{...props}
/>
));
TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
'inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm',
className
)}
{...props}
/>
));
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
'mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',
className
)}
{...props}
/>
));
TabsContent.displayName = TabsPrimitive.Content.displayName;
export { Tabs, TabsList, TabsTrigger, TabsContent };
+66
View File
@@ -0,0 +1,66 @@
import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from './card'
import { Badge } from './badge'
import { Checkbox } from './checkbox'
import { Button } from './button'
import { Pencil, Trash2 } from 'lucide-react'
import { motion } from 'framer-motion'
interface TaskCardProps {
id: string
title: string
description?: string
category: string
completed: boolean
onComplete: (id: string, completed: boolean) => void
onDelete: (id: string) => void
onEdit: (id: string) => void
}
export function TaskCard({
id,
title,
description,
category,
completed,
onComplete,
onDelete,
onEdit,
}: TaskCardProps) {
return (
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.2 }}
>
<Card className={`w-full ${completed ? 'opacity-60' : ''}`}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<div className="flex items-center space-x-2">
<Checkbox
checked={completed}
onCheckedChange={(checked) => onComplete(id, checked as boolean)}
/>
<CardTitle className={`text-lg ${completed ? 'line-through' : ''}`}>
{title}
</CardTitle>
</div>
<div className="flex space-x-2">
<Button variant="ghost" size="icon" onClick={() => onEdit(id)}>
<Pencil className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" onClick={() => onDelete(id)}>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</CardHeader>
<CardContent>
{description && <p className="text-sm text-muted-foreground">{description}</p>}
<Badge variant="secondary" className="mt-2">
{category}
</Badge>
</CardContent>
</Card>
</motion.div>
)
}
+40
View File
@@ -0,0 +1,40 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const textareaVariants = cva(
'flex min-h-[80px] w-full rounded-lg border bg-background px-3 py-2 text-sm transition-all duration-fast placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50',
{
variants: {
variant: {
default: 'border-input hover:border-ring/50 focus-visible:border-input focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
error: 'border-destructive hover:border-destructive focus-visible:border-destructive focus-visible:ring-2 focus-visible:ring-destructive focus-visible:ring-offset-2 focus-visible:ring-offset-background',
success: 'border-emerald-500 hover:border-emerald-500 focus-visible:border-emerald-500 focus-visible:ring-2 focus-visible:ring-emerald-500/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background',
ghost: 'border-transparent bg-muted/50 hover:bg-muted focus-visible:bg-background focus-visible:border-input focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
},
},
defaultVariants: {
variant: 'default',
},
}
);
export interface TextareaProps
extends React.TextareaHTMLAttributes<HTMLTextAreaElement>,
VariantProps<typeof textareaVariants> {}
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, variant, ...props }, ref) => {
return (
<textarea
className={cn(textareaVariants({ variant, className }))}
ref={ref}
{...props}
/>
);
}
);
Textarea.displayName = 'Textarea';
export { Textarea, textareaVariants };

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