feat(02-02): add thread hooks, UI store, tab navigation, and thread list

- Create useThreads/useCandidates TanStack Query hooks
- Extend uiStore with candidate panel and resolve dialog state
- Add ThreadTabs component for gear/planning tab switching
- Add ThreadCard component with candidate count and price range chips
- Refactor index.tsx to tabbed HomePage with PlanningView
- Create placeholder thread detail route for navigation target
This commit is contained in:
2026-03-15 11:44:17 +01:00
parent 53d6fa445d
commit a9d624dc83
7 changed files with 472 additions and 14 deletions

View File

@@ -0,0 +1,77 @@
import { useNavigate } from "@tanstack/react-router";
import { formatPrice } from "../lib/formatters";
interface ThreadCardProps {
id: number;
name: string;
candidateCount: number;
minPriceCents: number | null;
maxPriceCents: number | null;
createdAt: string;
status: "active" | "resolved";
}
function formatDate(iso: string): string {
const d = new Date(iso);
return d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}
function formatPriceRange(
min: number | null,
max: number | null,
): string | null {
if (min == null && max == null) return null;
if (min === max) return formatPrice(min);
return `${formatPrice(min)} - ${formatPrice(max)}`;
}
export function ThreadCard({
id,
name,
candidateCount,
minPriceCents,
maxPriceCents,
createdAt,
status,
}: ThreadCardProps) {
const navigate = useNavigate();
const isResolved = status === "resolved";
const priceRange = formatPriceRange(minPriceCents, maxPriceCents);
return (
<button
type="button"
onClick={() =>
navigate({ to: "/threads/$threadId", params: { threadId: String(id) } })
}
className={`w-full text-left bg-white rounded-xl border border-gray-100 hover:border-gray-200 hover:shadow-sm transition-all p-4 ${
isResolved ? "opacity-60" : ""
}`}
>
<div className="flex items-start justify-between mb-2">
<h3 className="text-sm font-semibold text-gray-900 truncate">
{name}
</h3>
{isResolved && (
<span className="ml-2 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-500 shrink-0">
Resolved
</span>
)}
</div>
<div className="flex flex-wrap gap-1.5">
<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-purple-50 text-purple-700">
{candidateCount} {candidateCount === 1 ? "candidate" : "candidates"}
</span>
<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-gray-50 text-gray-600">
{formatDate(createdAt)}
</span>
{priceRange && (
<span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-50 text-green-700">
{priceRange}
</span>
)}
</div>
</button>
);
}

View File

@@ -0,0 +1,33 @@
interface ThreadTabsProps {
active: "gear" | "planning";
onChange: (tab: "gear" | "planning") => void;
}
const tabs = [
{ key: "gear" as const, label: "My Gear" },
{ key: "planning" as const, label: "Planning" },
];
export function ThreadTabs({ active, onChange }: ThreadTabsProps) {
return (
<div className="flex border-b border-gray-200">
{tabs.map((tab) => (
<button
key={tab.key}
type="button"
onClick={() => onChange(tab.key)}
className={`px-4 py-2.5 text-sm font-medium transition-colors relative ${
active === tab.key
? "text-blue-600"
: "text-gray-500 hover:text-gray-700"
}`}
>
{tab.label}
{active === tab.key && (
<span className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-600 rounded-t" />
)}
</button>
))}
</div>
);
}

View File

@@ -0,0 +1,61 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiPost, apiPut, apiDelete } from "../lib/api";
import type { CreateCandidate, UpdateCandidate } from "../../shared/types";
interface CandidateResponse {
id: number;
threadId: number;
name: string;
weightGrams: number | null;
priceCents: number | null;
categoryId: number;
notes: string | null;
productUrl: string | null;
imageFilename: string | null;
createdAt: string;
updatedAt: string;
}
export function useCreateCandidate(threadId: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: CreateCandidate & { imageFilename?: string }) =>
apiPost<CandidateResponse>(`/api/threads/${threadId}/candidates`, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["threads", threadId] });
queryClient.invalidateQueries({ queryKey: ["threads"] });
},
});
}
export function useUpdateCandidate(threadId: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
candidateId,
...data
}: UpdateCandidate & { candidateId: number; imageFilename?: string }) =>
apiPut<CandidateResponse>(
`/api/threads/${threadId}/candidates/${candidateId}`,
data,
),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["threads", threadId] });
queryClient.invalidateQueries({ queryKey: ["threads"] });
},
});
}
export function useDeleteCandidate(threadId: number) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (candidateId: number) =>
apiDelete<{ success: boolean }>(
`/api/threads/${threadId}/candidates/${candidateId}`,
),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["threads", threadId] });
queryClient.invalidateQueries({ queryKey: ["threads"] });
},
});
}

View File

@@ -0,0 +1,113 @@
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiGet, apiPost, apiPut, apiDelete } from "../lib/api";
interface ThreadListItem {
id: number;
name: string;
status: "active" | "resolved";
resolvedCandidateId: number | null;
createdAt: string;
updatedAt: string;
candidateCount: number;
minPriceCents: number | null;
maxPriceCents: number | null;
}
interface CandidateWithCategory {
id: number;
threadId: number;
name: string;
weightGrams: number | null;
priceCents: number | null;
categoryId: number;
notes: string | null;
productUrl: string | null;
imageFilename: string | null;
createdAt: string;
updatedAt: string;
categoryName: string;
categoryEmoji: string;
}
interface ThreadWithCandidates {
id: number;
name: string;
status: "active" | "resolved";
resolvedCandidateId: number | null;
createdAt: string;
updatedAt: string;
candidates: CandidateWithCategory[];
}
export function useThreads(includeResolved = false) {
return useQuery({
queryKey: ["threads", { includeResolved }],
queryFn: () =>
apiGet<ThreadListItem[]>(
`/api/threads${includeResolved ? "?includeResolved=true" : ""}`,
),
});
}
export function useThread(threadId: number | null) {
return useQuery({
queryKey: ["threads", threadId],
queryFn: () => apiGet<ThreadWithCandidates>(`/api/threads/${threadId}`),
enabled: threadId != null,
});
}
export function useCreateThread() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: { name: string }) =>
apiPost<ThreadListItem>("/api/threads", data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["threads"] });
},
});
}
export function useUpdateThread() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, ...data }: { id: number; name?: string }) =>
apiPut<ThreadListItem>(`/api/threads/${id}`, data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["threads"] });
},
});
}
export function useDeleteThread() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: number) =>
apiDelete<{ success: boolean }>(`/api/threads/${id}`),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["threads"] });
},
});
}
export function useResolveThread() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
threadId,
candidateId,
}: {
threadId: number;
candidateId: number;
}) =>
apiPost<{ success: boolean; item: unknown }>(
`/api/threads/${threadId}/resolve`,
{ candidateId },
),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["threads"] });
queryClient.invalidateQueries({ queryKey: ["items"] });
queryClient.invalidateQueries({ queryKey: ["totals"] });
},
});
}

View File

@@ -1,22 +1,49 @@
import { createFileRoute } from "@tanstack/react-router"; import { useState } from "react";
import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { z } from "zod";
import { useItems } from "../hooks/useItems"; import { useItems } from "../hooks/useItems";
import { useTotals } from "../hooks/useTotals"; import { useTotals } from "../hooks/useTotals";
import { useThreads, useCreateThread } from "../hooks/useThreads";
import { CategoryHeader } from "../components/CategoryHeader"; import { CategoryHeader } from "../components/CategoryHeader";
import { ItemCard } from "../components/ItemCard"; import { ItemCard } from "../components/ItemCard";
import { ThreadTabs } from "../components/ThreadTabs";
import { ThreadCard } from "../components/ThreadCard";
import { useUIStore } from "../stores/uiStore"; import { useUIStore } from "../stores/uiStore";
export const Route = createFileRoute("/")({ const searchSchema = z.object({
component: CollectionPage, tab: z.enum(["gear", "planning"]).catch("gear"),
}); });
function CollectionPage() { export const Route = createFileRoute("/")({
validateSearch: searchSchema,
component: HomePage,
});
function HomePage() {
const { tab } = Route.useSearch();
const navigate = useNavigate();
function handleTabChange(newTab: "gear" | "planning") {
navigate({ to: "/", search: { tab: newTab } });
}
return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
<ThreadTabs active={tab} onChange={handleTabChange} />
<div className="mt-6">
{tab === "gear" ? <CollectionView /> : <PlanningView />}
</div>
</div>
);
}
function CollectionView() {
const { data: items, isLoading: itemsLoading } = useItems(); const { data: items, isLoading: itemsLoading } = useItems();
const { data: totals } = useTotals(); const { data: totals } = useTotals();
const openAddPanel = useUIStore((s) => s.openAddPanel); const openAddPanel = useUIStore((s) => s.openAddPanel);
if (itemsLoading) { if (itemsLoading) {
return ( return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="animate-pulse space-y-6"> <div className="animate-pulse space-y-6">
<div className="h-6 bg-gray-200 rounded w-48" /> <div className="h-6 bg-gray-200 rounded w-48" />
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
@@ -25,13 +52,12 @@ function CollectionPage() {
))} ))}
</div> </div>
</div> </div>
</div>
); );
} }
if (!items || items.length === 0) { if (!items || items.length === 0) {
return ( return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 text-center"> <div className="py-16 text-center">
<div className="max-w-md mx-auto"> <div className="max-w-md mx-auto">
<div className="text-5xl mb-4">🎒</div> <div className="text-5xl mb-4">🎒</div>
<h2 className="text-xl font-semibold text-gray-900 mb-2"> <h2 className="text-xl font-semibold text-gray-900 mb-2">
@@ -101,7 +127,7 @@ function CollectionPage() {
} }
return ( return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6"> <>
{Array.from(groupedItems.entries()).map( {Array.from(groupedItems.entries()).map(
([categoryId, { items: categoryItems, categoryName, categoryEmoji }]) => { ([categoryId, { items: categoryItems, categoryName, categoryEmoji }]) => {
const catTotals = categoryTotalsMap.get(categoryId); const catTotals = categoryTotalsMap.get(categoryId);
@@ -133,6 +159,94 @@ function CollectionPage() {
); );
}, },
)} )}
</>
);
}
function PlanningView() {
const [showResolved, setShowResolved] = useState(false);
const [newThreadName, setNewThreadName] = useState("");
const { data: threads, isLoading } = useThreads(showResolved);
const createThread = useCreateThread();
function handleCreateThread(e: React.FormEvent) {
e.preventDefault();
const name = newThreadName.trim();
if (!name) return;
createThread.mutate(
{ name },
{ onSuccess: () => setNewThreadName("") },
);
}
if (isLoading) {
return (
<div className="animate-pulse space-y-4">
{[1, 2].map((i) => (
<div key={i} className="h-24 bg-gray-200 rounded-xl" />
))}
</div>
);
}
return (
<div>
{/* Create thread form */}
<form onSubmit={handleCreateThread} className="flex gap-2 mb-6">
<input
type="text"
value={newThreadName}
onChange={(e) => setNewThreadName(e.target.value)}
placeholder="New thread name..."
className="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
/>
<button
type="submit"
disabled={!newThreadName.trim() || createThread.isPending}
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"
>
{createThread.isPending ? "Creating..." : "Create"}
</button>
</form>
{/* Show resolved toggle */}
<label className="flex items-center gap-2 mb-4 text-sm text-gray-600 cursor-pointer">
<input
type="checkbox"
checked={showResolved}
onChange={(e) => setShowResolved(e.target.checked)}
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
Show archived threads
</label>
{/* Thread list */}
{!threads || threads.length === 0 ? (
<div className="py-12 text-center">
<div className="text-4xl mb-3">🔍</div>
<h3 className="text-lg font-semibold text-gray-900 mb-1">
No planning threads yet
</h3>
<p className="text-sm text-gray-500">
Start one to research your next purchase.
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{threads.map((thread) => (
<ThreadCard
key={thread.id}
id={thread.id}
name={thread.name}
candidateCount={thread.candidateCount}
minPriceCents={thread.minPriceCents}
maxPriceCents={thread.maxPriceCents}
createdAt={thread.createdAt}
status={thread.status}
/>
))}
</div>
)}
</div> </div>
); );
} }

View File

@@ -0,0 +1,15 @@
import { createFileRoute } from "@tanstack/react-router";
export const Route = createFileRoute("/threads/$threadId")({
component: ThreadDetailPage,
});
function ThreadDetailPage() {
const { threadId } = Route.useParams();
return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
<p>Thread {threadId} - detail page placeholder</p>
</div>
);
}

View File

@@ -1,6 +1,7 @@
import { create } from "zustand"; import { create } from "zustand";
interface UIState { interface UIState {
// Item panel state
panelMode: "closed" | "add" | "edit"; panelMode: "closed" | "add" | "edit";
editingItemId: number | null; editingItemId: number | null;
confirmDeleteItemId: number | null; confirmDeleteItemId: number | null;
@@ -10,9 +11,28 @@ interface UIState {
closePanel: () => void; closePanel: () => void;
openConfirmDelete: (itemId: number) => void; openConfirmDelete: (itemId: number) => void;
closeConfirmDelete: () => void; closeConfirmDelete: () => void;
// Candidate panel state
candidatePanelMode: "closed" | "add" | "edit";
editingCandidateId: number | null;
confirmDeleteCandidateId: number | null;
openCandidateAddPanel: () => void;
openCandidateEditPanel: (id: number) => void;
closeCandidatePanel: () => void;
openConfirmDeleteCandidate: (id: number) => void;
closeConfirmDeleteCandidate: () => void;
// Resolution dialog state
resolveThreadId: number | null;
resolveCandidateId: number | null;
openResolveDialog: (threadId: number, candidateId: number) => void;
closeResolveDialog: () => void;
} }
export const useUIStore = create<UIState>((set) => ({ export const useUIStore = create<UIState>((set) => ({
// Item panel
panelMode: "closed", panelMode: "closed",
editingItemId: null, editingItemId: null,
confirmDeleteItemId: null, confirmDeleteItemId: null,
@@ -22,4 +42,29 @@ export const useUIStore = create<UIState>((set) => ({
closePanel: () => set({ panelMode: "closed", editingItemId: null }), closePanel: () => set({ panelMode: "closed", editingItemId: null }),
openConfirmDelete: (itemId) => set({ confirmDeleteItemId: itemId }), openConfirmDelete: (itemId) => set({ confirmDeleteItemId: itemId }),
closeConfirmDelete: () => set({ confirmDeleteItemId: null }), closeConfirmDelete: () => set({ confirmDeleteItemId: null }),
// Candidate panel
candidatePanelMode: "closed",
editingCandidateId: null,
confirmDeleteCandidateId: null,
openCandidateAddPanel: () =>
set({ candidatePanelMode: "add", editingCandidateId: null }),
openCandidateEditPanel: (id) =>
set({ candidatePanelMode: "edit", editingCandidateId: id }),
closeCandidatePanel: () =>
set({ candidatePanelMode: "closed", editingCandidateId: null }),
openConfirmDeleteCandidate: (id) =>
set({ confirmDeleteCandidateId: id }),
closeConfirmDeleteCandidate: () =>
set({ confirmDeleteCandidateId: null }),
// Resolution dialog
resolveThreadId: null,
resolveCandidateId: null,
openResolveDialog: (threadId, candidateId) =>
set({ resolveThreadId: threadId, resolveCandidateId: candidateId }),
closeResolveDialog: () =>
set({ resolveThreadId: null, resolveCandidateId: null }),
})); }));