feat(interests): EOI/contract/reservation tabs + contact log + berth interest milestone + interest list overhaul

Major interest workflow expansion driven by the rapid-fire UX session.

EOI / Contract / Reservation tabs replace the generic Documents tab when
the deal is at the relevant stage — workspace pattern with active-doc
hero, signing progress, paper-signed upload, and history strip. Stage-
conditional visibility wired through interest-tabs.tsx so the tab set
shrinks/expands as the deal moves through the pipeline.

Contact log: per-interaction structured log (channel/direction/summary/
optional follow-up reminder). New `interest_contact_log` table + service
+ tab UI (timeline with channel-coded icons + compose dialog).
auto-creates a reminder when followUpAt is set.

Berth Interest milestone: first milestone in the OverviewTab's pipeline
strip, completes the moment any berth is linked via the junction. Drives
the "have we captured what they want?" sanity check for general_interest
leads before they move to EOI.

Stage-conditional milestones: past phases collapse into a one-liner
strip, current phase expands, future phases hide behind a "Show
upcoming" toggle. Inline stage picker now defers reason capture to an
override-confirm view (only required for illegal transitions, not the
default flow).

Notes blob → threaded: dropped `interests.notes` column entirely; the
threaded `interest_notes` table is the single source of truth. Latest-
note teaser on Overview links into the dedicated Notes tab. Polymorphic
notes service gains aggregated client view (unions client + interest +
yacht notes with source chips and group-by-source toggle).

Berth interest list overhaul:
  - Configurable columns via ColumnPicker (18 toggleable, 5 default-on)
  - Natural-sort SQL ORDER BY on mooring number (A1, A2, A10 not A10, A2)
  - Per-letter row tinting via colored left-border accent + dot in cell
  - Documents tab merged Files (single attachments section)

Topbar improvements:
  - Always-visible back arrow on detail pages (path depth > 2)
  - Breadcrumb-hint store + useBreadcrumbHint hook so detail pages can
    push their entity hierarchy (Clients › Mary Smith › Interest › B17)
  - Tighter spacing, softer separators, 160px crumb truncation

DataTable upgrades:
  - Page-size selector with All option (validator cap raised to 1000)
  - getRowClassName slot for per-row styling (used by berth tinting)
  - Fixed Radix SelectItem crash on empty-string values via __any__
    sentinel (was crashing every list page that opened a select filter)

Interest list:
  - Configurable columns picker
  - Stage cell clickable into detail
  - TagPicker + SavedViewsDropdown sized h-8 to match adjacent buttons
  - Save view moved into ColumnPicker menu; Views button hidden when
    no views are saved
  - Pipeline kanban board endpoint at /api/v1/interests/board with
    minimal projection, 5000-row cap + truncated banner, filter
    pass-through

Mobile chrome + sidebar collapse removed (always-expanded design choice).

User management lists super-admins (was inner-joined on user_port_roles
which excluded global super-admins).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-07 20:59:28 +02:00
parent 267c2b6d1f
commit 3e4d9d6310
87 changed files with 5593 additions and 902 deletions

View File

@@ -0,0 +1,133 @@
'use client';
import { Columns3, Check, Bookmark } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
export interface ColumnPickerOption {
/** Stable ID matching the column's `id` field in the table. */
id: string;
/** Human-readable label shown in the dropdown menu. */
label: string;
/**
* When true, the column can't be toggled off (e.g. Name + actions).
* It still appears in the menu but with a disabled checkmark.
*/
alwaysVisible?: boolean;
}
/**
* Dropdown menu for toggling table column visibility. Lives next to the
* filter bar — single source of truth for which columns the current
* user wants to see in this table. Persistence is handled by the
* parent (typically via `useTablePreferences`).
*/
export function ColumnPicker({
columns,
hidden,
onChange,
onSaveView,
}: {
columns: ColumnPickerOption[];
hidden: string[];
onChange: (hidden: string[]) => void;
/**
* Optional callback. When provided, a "Save current view" item is
* appended to the menu — folds the save-view affordance into the
* column picker instead of a separate top-level button.
*/
onSaveView?: () => void;
}) {
const hiddenSet = new Set(hidden);
function toggle(id: string) {
const next = new Set(hiddenSet);
if (next.has(id)) next.delete(id);
else next.add(id);
onChange(Array.from(next));
}
function showAll() {
onChange([]);
}
// The "All visible" affordance is only useful when something is
// hidden — a no-op button is noise.
const canShowAll = hidden.some((id) =>
columns.some((col) => col.id === id && !col.alwaysVisible),
);
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="gap-1.5 h-8">
<Columns3 className="h-3.5 w-3.5" />
<span className="hidden sm:inline">Columns</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
<DropdownMenuLabel className="text-xs text-muted-foreground">
Show / hide columns
</DropdownMenuLabel>
<DropdownMenuSeparator />
{columns.map((col) => {
const isVisible = !hiddenSet.has(col.id);
return (
<DropdownMenuItem
key={col.id}
disabled={col.alwaysVisible}
onSelect={(e) => {
// Keep the menu open while toggling so the user can
// flip multiple columns in one pass.
e.preventDefault();
if (col.alwaysVisible) return;
toggle(col.id);
}}
className="flex items-center gap-2"
>
<span
aria-hidden
className={`flex h-4 w-4 items-center justify-center rounded-sm border ${
isVisible ? 'bg-primary border-primary text-primary-foreground' : 'border-border'
}`}
>
{isVisible && <Check className="h-3 w-3" />}
</span>
<span className="flex-1">{col.label}</span>
{col.alwaysVisible && (
<span className="text-[10px] uppercase tracking-wide text-muted-foreground">
always
</span>
)}
</DropdownMenuItem>
);
})}
{canShowAll && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={showAll} className="text-xs text-muted-foreground">
Show all columns
</DropdownMenuItem>
</>
)}
{onSaveView && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={onSaveView}>
<Bookmark className="mr-2 h-3.5 w-3.5" />
Save current view
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -8,6 +8,7 @@ import {
type ColumnDef,
type Row,
type RowSelectionState,
type VisibilityState,
} from '@tanstack/react-table';
import { ArrowDown, ArrowUp, ArrowUpDown, Loader2 } from 'lucide-react';
@@ -51,6 +52,12 @@ interface DataTableProps<TData> {
isLoading?: boolean;
getRowId?: (row: TData) => string;
onRowClick?: (row: TData) => void;
/**
* Optional row class hook — return a string of Tailwind utilities
* applied to the `<TableRow>`. Use for visual grouping (e.g. tinting
* berths by mooring letter so the kanban-like grid reads at a glance).
*/
getRowClassName?: (row: TData) => string | undefined;
/**
* Mobile card renderer. When provided, the table is hidden below `lg:`
* and replaced with a vertical list of cards built from this callback.
@@ -58,6 +65,13 @@ interface DataTableProps<TData> {
* sort, and selection stay in sync across the breakpoint.
*/
cardRender?: (row: Row<TData>) => React.ReactNode;
/**
* Per-column visibility map. Keys are column IDs, values mean
* "currently visible". Columns absent from the map are visible by
* default — newly-added columns surface for existing users without
* needing a preferences migration.
*/
columnVisibility?: VisibilityState;
}
export function DataTable<TData>({
@@ -74,7 +88,9 @@ export function DataTable<TData>({
isLoading,
getRowId,
onRowClick,
getRowClassName,
cardRender,
columnVisibility,
}: DataTableProps<TData>) {
const [internalSelection, setInternalSelection] = useState<RowSelectionState>({});
const rowSelectionState = externalSelection ?? internalSelection;
@@ -122,6 +138,7 @@ export function DataTable<TData>({
pagination: pagination
? { pageIndex: pagination.page - 1, pageSize: pagination.pageSize }
: undefined,
columnVisibility,
},
onRowSelectionChange: (updater) => {
const newSelection = typeof updater === 'function' ? updater(rowSelectionState) : updater;
@@ -215,7 +232,7 @@ export function DataTable<TData>({
<TableRow
key={row.id}
data-state={row.getIsSelected() && 'selected'}
className={cn(onRowClick && 'cursor-pointer')}
className={cn(onRowClick && 'cursor-pointer', getRowClassName?.(row.original))}
onClick={() => onRowClick?.(row.original)}
>
{row.getVisibleCells().map((cell) => (
@@ -247,34 +264,61 @@ export function DataTable<TData>({
</ul>
)}
{/* Pagination */}
{pagination && pagination.totalPages > 1 && (
<div className="flex items-center justify-between px-2">
{/* Pagination — render whenever pagination is defined so the
page-size selector is reachable even on single-page tables.
Prev/Next group only renders when there's actually more than
one page. */}
{pagination && (
<div className="flex items-center justify-between px-2 gap-3 flex-wrap">
<div className="text-sm text-muted-foreground">
{selectedIds.length > 0
? `${selectedIds.length} of ${pagination.total} row(s) selected`
: `${pagination.total} row(s) total`}
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={pagination.page <= 1}
onClick={() => onPaginationChange?.(pagination.page - 1, pagination.pageSize)}
>
Previous
</Button>
<span className="text-sm text-muted-foreground">
Page {pagination.page} of {pagination.totalPages}
</span>
<Button
variant="outline"
size="sm"
disabled={pagination.page >= pagination.totalPages}
onClick={() => onPaginationChange?.(pagination.page + 1, pagination.pageSize)}
>
Next
</Button>
<div className="flex items-center gap-3">
{/* Page-size selector — "All" maps to the validator's
max(1000) cap. If a port has more than 1000 active rows
the user paginates; we don't quietly drop rows. */}
<label className="text-sm text-muted-foreground inline-flex items-center gap-1.5">
Show
<select
value={String(pagination.pageSize)}
onChange={(e) => {
const next = e.target.value === 'all' ? 1000 : Number(e.target.value);
onPaginationChange?.(1, next);
}}
className="h-8 rounded-md border border-input bg-background px-2 text-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="250">250</option>
<option value="all">All</option>
</select>
</label>
{pagination.totalPages > 1 && (
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={pagination.page <= 1}
onClick={() => onPaginationChange?.(pagination.page - 1, pagination.pageSize)}
>
Previous
</Button>
<span className="text-sm text-muted-foreground">
Page {pagination.page} of {pagination.totalPages}
</span>
<Button
variant="outline"
size="sm"
disabled={pagination.page >= pagination.totalPages}
onClick={() => onPaginationChange?.(pagination.page + 1, pagination.pageSize)}
>
Next
</Button>
</div>
)}
</div>
</div>
)}

View File

@@ -184,16 +184,22 @@ function FilterField({
</div>
);
case 'select':
case 'select': {
// Radix Select forbids empty-string item values (throws at render
// time, crashes the page). Use a sentinel and translate.
const ANY = '__any__';
return (
<div className="space-y-1">
<Label className="text-xs">{definition.label}</Label>
<Select value={(value as string) ?? ''} onValueChange={(v) => onChange(v || undefined)}>
<Select
value={(value as string) || ANY}
onValueChange={(v) => onChange(v === ANY ? undefined : v)}
>
<SelectTrigger className="h-8">
<SelectValue placeholder={definition.placeholder ?? 'Any'} />
</SelectTrigger>
<SelectContent>
<SelectItem value="">Any</SelectItem>
<SelectItem value={ANY}>Any</SelectItem>
{definition.options?.map((opt) => (
<SelectItem key={opt.value} value={opt.value}>
{opt.label}
@@ -203,6 +209,7 @@ function FilterField({
</Select>
</div>
);
}
case 'multi-select':
return (

View File

@@ -1,7 +1,7 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { Loader2, Pencil } from 'lucide-react';
import { ChevronDown, Loader2, Pencil } from 'lucide-react';
import { toastError } from '@/lib/api/toast-error';
import { Input } from '@/components/ui/input';
@@ -98,33 +98,25 @@ export function InlineEditableField(props: InlineEditableFieldProps) {
}
if (props.variant === 'select') {
// Picker fields don't need a read/edit mode toggle — a Select is
// already a click-to-open control. Rendering one consistent
// SelectTrigger eliminates the width jump that happened when we
// swapped from a content-sized ReadButton to a w-full SelectTrigger
// on click (and back again on selection). The trigger now stays at
// a single width whether the popover is open or closed, so the
// dropdown menu visually aligns to the same control across states.
const labelFor = (v: string | null | undefined) =>
v ? (props.options.find((o) => o.value === v)?.label ?? v) : null;
if (!editing) {
return (
<ReadButton
value={labelFor(value)}
emptyText={emptyText}
disabled={disabled}
onClick={() => setEditing(true)}
className={className}
/>
);
}
return (
<div className={cn('flex items-center gap-1', className)}>
<Select
value={draft}
value={value ?? ''}
onValueChange={(v) => void commit(v)}
open
onOpenChange={(open) => {
if (!open && !saving) setEditing(false);
}}
disabled={disabled || saving}
>
<SelectTrigger className="h-7 text-sm w-full">
<SelectValue placeholder={placeholder} />
<SelectTrigger className="h-8 text-sm w-full">
<SelectValue placeholder={emptyText}>{labelFor(value) ?? emptyText}</SelectValue>
</SelectTrigger>
<SelectContent>
{props.options.map((o) => (
@@ -228,6 +220,7 @@ function ReadButton({
disabled,
onClick,
multiline,
kind = 'text',
className,
}: {
value: string | null;
@@ -235,8 +228,13 @@ function ReadButton({
disabled?: boolean;
onClick: () => void;
multiline?: boolean;
/** Icon affordance: 'text' shows a pencil (free-text edit), 'select'
* shows a chevron-down (fixed-list picker). The chevron clarifies
* that clicking opens a dropdown, not a text input. */
kind?: 'text' | 'select';
className?: string;
}) {
const Icon = kind === 'select' ? ChevronDown : Pencil;
return (
<button
type="button"
@@ -246,6 +244,9 @@ function ReadButton({
'group rounded px-1 -mx-1 py-0.5 text-left text-sm',
multiline ? 'flex w-full items-start gap-1.5' : 'inline-flex items-center gap-1.5',
'hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring',
// Select-kind buttons get a faint border so they read as a
// distinct interactive element rather than text-with-an-icon.
kind === 'select' && 'border border-border bg-background hover:bg-accent',
disabled && 'cursor-not-allowed opacity-60 hover:bg-transparent',
className,
)}
@@ -260,11 +261,14 @@ function ReadButton({
{value ?? emptyText}
</span>
{!disabled && (
<Pencil
<Icon
className={cn(
// Show the pencil faintly at rest so users discover the field is
// editable without having to hover-and-test every label.
'h-3 w-3 opacity-20 transition-opacity group-hover:opacity-60',
// Pencil sits faintly so users discover free-text editability
// on hover; chevron is more present so the dropdown affordance
// is obvious before any interaction.
kind === 'select'
? 'h-3.5 w-3.5 opacity-60 transition-opacity group-hover:opacity-100'
: 'h-3 w-3 opacity-20 transition-opacity group-hover:opacity-60',
multiline && 'mt-1 shrink-0',
)}
/>

View File

@@ -18,32 +18,72 @@ interface Note {
isLocked: boolean;
createdAt: string;
updatedAt: string;
/** Aggregated-mode only: which child entity this note came from. */
source?: 'client' | 'interest' | 'yacht';
sourceId?: string;
sourceLabel?: string;
}
interface NotesListProps {
entityType: 'clients' | 'interests' | 'yachts' | 'companies';
entityType:
| 'clients'
| 'interests'
| 'yachts'
| 'companies'
| 'residential_clients'
| 'residential_interests';
entityId: string;
currentUserId?: string;
/**
* When `entityType='clients'` and this is true, the list aggregates
* notes from the client + their interests + directly-owned yachts.
* Notes from interests/yachts render with a source chip and are
* read-only here (edit them on the source entity's page).
*/
aggregate?: boolean;
}
const NOTE_EDIT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
export function NotesList({ entityType, entityId, currentUserId }: NotesListProps) {
/** Sort by source then chronologically inside each source.
* Used by the aggregated view's "Group by source" toggle. */
function sortByGroup(notes: Note[]): Note[] {
const sourceOrder: Record<string, number> = { client: 0, interest: 1, yacht: 2 };
return [...notes].sort((a, b) => {
const aRank = sourceOrder[a.source ?? 'client'] ?? 99;
const bRank = sourceOrder[b.source ?? 'client'] ?? 99;
if (aRank !== bRank) return aRank - bRank;
const aLabel = a.sourceLabel ?? '';
const bLabel = b.sourceLabel ?? '';
if (aLabel !== bLabel) return aLabel.localeCompare(bLabel);
return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
});
}
export function NotesList({ entityType, entityId, currentUserId, aggregate }: NotesListProps) {
const queryClient = useQueryClient();
const [newNote, setNewNote] = useState('');
const [editingId, setEditingId] = useState<string | null>(null);
const [editContent, setEditContent] = useState('');
const [groupBySource, setGroupBySource] = useState(false);
const endpoint = `/api/v1/${entityType}/${entityId}/notes`;
const queryKey = [entityType, entityId, 'notes'];
const aggregateOn = aggregate && entityType === 'clients';
const baseEndpoint = `/api/v1/${entityType}/${entityId}/notes`;
const listEndpoint = aggregateOn ? `${baseEndpoint}?aggregate=true` : baseEndpoint;
const queryKey = [entityType, entityId, 'notes', aggregateOn ? 'aggregated' : 'own'];
const { data: notes = [], isLoading } = useQuery<Note[]>({
queryKey,
queryFn: () => apiFetch<{ data: Note[] }>(endpoint).then((r) => r.data),
queryFn: () => apiFetch<{ data: Note[] }>(listEndpoint).then((r) => r.data),
});
// Mutations always target the parent entity (client). Aggregated
// notes from interests/yachts are read-only here — the rep edits
// them on the source entity's page (we surface a "Open source" link
// below). Keeping mutations against `baseEndpoint` keeps the POST
// route handler clean.
const createMutation = useMutation({
mutationFn: (content: string) => apiFetch(endpoint, { method: 'POST', body: { content } }),
mutationFn: (content: string) => apiFetch(baseEndpoint, { method: 'POST', body: { content } }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey });
setNewNote('');
@@ -52,7 +92,7 @@ export function NotesList({ entityType, entityId, currentUserId }: NotesListProp
const updateMutation = useMutation({
mutationFn: ({ noteId, content }: { noteId: string; content: string }) =>
apiFetch(`${endpoint}/${noteId}`, { method: 'PATCH', body: { content } }),
apiFetch(`${baseEndpoint}/${noteId}`, { method: 'PATCH', body: { content } }),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey });
setEditingId(null);
@@ -60,13 +100,17 @@ export function NotesList({ entityType, entityId, currentUserId }: NotesListProp
});
const deleteMutation = useMutation({
mutationFn: (noteId: string) => apiFetch(`${endpoint}/${noteId}`, { method: 'DELETE' }),
mutationFn: (noteId: string) => apiFetch(`${baseEndpoint}/${noteId}`, { method: 'DELETE' }),
onSuccess: () => queryClient.invalidateQueries({ queryKey }),
});
function canEdit(note: Note): boolean {
if (note.authorId !== currentUserId) return false;
if (note.isLocked) return false;
// Aggregated view: only client-level notes are editable in-place.
// Notes from interests/yachts must be edited on their own page so
// the right entity timeline records the change.
if (aggregateOn && note.source && note.source !== 'client') return false;
const elapsed = Date.now() - new Date(note.createdAt).getTime();
return elapsed < NOTE_EDIT_WINDOW_MS;
}
@@ -105,6 +149,29 @@ export function NotesList({ entityType, entityId, currentUserId }: NotesListProp
</div>
</div>
{/* Aggregated-mode controls — sort toggle. Only renders when
* aggregation is on and there's actually content to group. */}
{aggregateOn && notes.length > 0 && (
<div className="flex items-center justify-end gap-2 text-xs text-muted-foreground">
<span>View:</span>
<button
type="button"
className={!groupBySource ? 'font-medium text-foreground' : 'hover:text-foreground'}
onClick={() => setGroupBySource(false)}
>
Chronological
</button>
<span>·</span>
<button
type="button"
className={groupBySource ? 'font-medium text-foreground' : 'hover:text-foreground'}
onClick={() => setGroupBySource(true)}
>
Group by source
</button>
</div>
)}
{/* Notes list */}
{isLoading ? (
<div className="text-center py-8 text-muted-foreground">Loading notes...</div>
@@ -112,7 +179,7 @@ export function NotesList({ entityType, entityId, currentUserId }: NotesListProp
<div className="text-center py-8 text-muted-foreground">No notes yet</div>
) : (
<div className="space-y-3">
{notes.map((note) => (
{(groupBySource ? sortByGroup(notes) : notes).map((note) => (
<div key={note.id} className="flex gap-3 p-3 rounded-lg border bg-card">
<Avatar className="h-8 w-8 shrink-0">
<AvatarFallback className="text-xs">
@@ -120,11 +187,23 @@ export function NotesList({ entityType, entityId, currentUserId }: NotesListProp
</AvatarFallback>
</Avatar>
<div className="flex-1 min-w-0 space-y-1">
<div className="flex items-center gap-2 text-sm">
<div className="flex items-center gap-2 text-sm flex-wrap">
<span className="font-medium">{note.authorName ?? 'User'}</span>
<span className="text-muted-foreground">
{formatDistanceToNow(new Date(note.createdAt), { addSuffix: true })}
</span>
{aggregateOn && note.source && note.source !== 'client' && note.sourceLabel && (
<span
className={
note.source === 'interest'
? 'inline-flex items-center rounded-full bg-blue-100 text-blue-900 px-1.5 py-0.5 text-[10px] font-medium'
: 'inline-flex items-center rounded-full bg-emerald-100 text-emerald-900 px-1.5 py-0.5 text-[10px] font-medium'
}
title={`From ${note.source}`}
>
{note.source === 'interest' ? 'Interest' : 'Yacht'} · {note.sourceLabel}
</span>
)}
{note.isLocked && <Lock className="h-3 w-3 text-muted-foreground" />}
{canEdit(note) && (
<span className="text-xs text-muted-foreground">{getTimeRemaining(note)}</span>

View File

@@ -0,0 +1,82 @@
'use client';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useSavedViews } from '@/hooks/use-saved-views';
interface SaveViewDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
entityType: string;
currentFilters: Record<string, unknown>;
currentSort?: { field: string; direction: 'asc' | 'desc' };
}
/**
* Standalone save-view dialog. Lifted out of SavedViewsDropdown so the
* "Save current view" affordance can live inside the column picker
* (where the rep is already configuring the table) instead of as a
* top-level button. SavedViewsDropdown now only handles browsing and
* applying existing views — the save and read concerns are split.
*/
export function SaveViewDialog({
open,
onOpenChange,
entityType,
currentFilters,
currentSort,
}: SaveViewDialogProps) {
const { saveCurrentView } = useSavedViews(entityType);
const [viewName, setViewName] = useState('');
const [isSaving, setIsSaving] = useState(false);
async function handleSave() {
if (!viewName.trim()) return;
setIsSaving(true);
try {
await saveCurrentView(viewName.trim(), currentFilters, currentSort);
onOpenChange(false);
setViewName('');
} finally {
setIsSaving(false);
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Save view</DialogTitle>
</DialogHeader>
<div className="space-y-2">
<Label>View name</Label>
<Input
value={viewName}
onChange={(e) => setViewName(e.target.value)}
placeholder="My custom view"
onKeyDown={(e) => e.key === 'Enter' && handleSave()}
autoFocus
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleSave} disabled={!viewName.trim() || isSaving}>
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,135 +1,73 @@
'use client';
import { useState } from 'react';
import { Bookmark, Check, Plus, Trash2 } from 'lucide-react';
import { Bookmark, Check, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useSavedViews } from '@/hooks/use-saved-views';
interface SavedViewsDropdownProps {
entityType: string;
currentFilters: Record<string, unknown>;
currentSort?: { field: string; direction: 'asc' | 'desc' };
onApplyView: (filters: Record<string, unknown>, sort?: { field: string; direction: string }) => void;
onApplyView: (
filters: Record<string, unknown>,
sort?: { field: string; direction: string },
) => void;
}
export function SavedViewsDropdown({
entityType,
currentFilters,
currentSort,
onApplyView,
}: SavedViewsDropdownProps) {
const { views, activeViewId, saveCurrentView, deleteView, applyView } =
useSavedViews(entityType);
const [saveOpen, setSaveOpen] = useState(false);
const [viewName, setViewName] = useState('');
const [isSaving, setIsSaving] = useState(false);
/**
* Read-only browser for saved views. The "Save current view" affordance
* has moved into the ColumnPicker menu (see SaveViewDialog). This
* component renders nothing when the user has no saved views — the
* Bookmark button on its own is just visual noise until something has
* been saved.
*/
export function SavedViewsDropdown({ entityType, onApplyView }: SavedViewsDropdownProps) {
const { views, activeViewId, deleteView, applyView } = useSavedViews(entityType);
async function handleSave() {
if (!viewName.trim()) return;
setIsSaving(true);
try {
await saveCurrentView(viewName.trim(), currentFilters, currentSort);
setSaveOpen(false);
setViewName('');
} finally {
setIsSaving(false);
}
}
if (views.length === 0) return null;
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="h-8">
<Bookmark className="mr-1.5 h-3.5 w-3.5" />
Views
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{views.length === 0 ? (
<div className="px-2 py-3 text-sm text-muted-foreground text-center">
No saved views yet
</div>
) : (
views.map((view) => (
<DropdownMenuItem
key={view.id}
className="flex items-center justify-between"
onClick={() => {
applyView(view.id);
onApplyView(
view.filters as Record<string, unknown>,
view.sortConfig as { field: string; direction: string } | undefined,
);
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="sm" className="h-8">
<Bookmark className="mr-1.5 h-3.5 w-3.5" />
Views
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
{views.map((view) => (
<DropdownMenuItem
key={view.id}
className="flex items-center justify-between"
onClick={() => {
applyView(view.id);
onApplyView(
view.filters as Record<string, unknown>,
view.sortConfig as { field: string; direction: string } | undefined,
);
}}
>
<span className="truncate">{view.name}</span>
<div className="flex items-center gap-1">
{activeViewId === view.id && <Check className="h-3.5 w-3.5 text-primary" />}
<button
className="p-0.5 rounded hover:bg-muted"
onClick={(e) => {
e.stopPropagation();
deleteView(view.id);
}}
>
<span className="truncate">{view.name}</span>
<div className="flex items-center gap-1">
{activeViewId === view.id && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
<button
className="p-0.5 rounded hover:bg-muted"
onClick={(e) => {
e.stopPropagation();
deleteView(view.id);
}}
>
<Trash2 className="h-3 w-3 text-muted-foreground" />
</button>
</div>
</DropdownMenuItem>
))
)}
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => setSaveOpen(true)}>
<Plus className="mr-2 h-3.5 w-3.5" />
Save current view
<Trash2 className="h-3 w-3 text-muted-foreground" />
</button>
</div>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<Dialog open={saveOpen} onOpenChange={setSaveOpen}>
<DialogContent className="sm:max-w-sm">
<DialogHeader>
<DialogTitle>Save View</DialogTitle>
</DialogHeader>
<div className="space-y-2">
<Label>View name</Label>
<Input
value={viewName}
onChange={(e) => setViewName(e.target.value)}
placeholder="My custom view"
onKeyDown={(e) => e.key === 'Enter' && handleSave()}
/>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setSaveOpen(false)}>
Cancel
</Button>
<Button onClick={handleSave} disabled={!viewName.trim() || isSaving}>
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
))}
</DropdownMenuContent>
</DropdownMenu>
);
}