feat(01-03): add slide-out panel, item form, category picker, and collection page

- CategoryPicker combobox with search, select, and inline create
- SlideOutPanel with backdrop, escape key, and slide animation
- ItemForm with all fields, validation, dollar-to-cents conversion
- Root layout with TotalsBar, panel, confirm dialog, and floating add button
- Collection page with card grid grouped by category, empty state

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-14 22:46:24 +01:00
parent b099a47eb4
commit 12fd14ff41
5 changed files with 736 additions and 2 deletions

View File

@@ -0,0 +1,200 @@
import { useState, useRef, useEffect } from "react";
import {
useCategories,
useCreateCategory,
} from "../hooks/useCategories";
interface CategoryPickerProps {
value: number;
onChange: (categoryId: number) => void;
}
export function CategoryPicker({ value, onChange }: CategoryPickerProps) {
const { data: categories = [] } = useCategories();
const createCategory = useCreateCategory();
const [inputValue, setInputValue] = useState("");
const [isOpen, setIsOpen] = useState(false);
const [highlightIndex, setHighlightIndex] = useState(-1);
const containerRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const listRef = useRef<HTMLUListElement>(null);
// Sync display value when value prop changes
const selectedCategory = categories.find((c) => c.id === value);
const filtered = categories.filter((c) =>
c.name.toLowerCase().includes(inputValue.toLowerCase()),
);
const showCreateOption =
inputValue.trim() !== "" &&
!categories.some(
(c) => c.name.toLowerCase() === inputValue.trim().toLowerCase(),
);
const totalOptions = filtered.length + (showCreateOption ? 1 : 0);
useEffect(() => {
function handleClickOutside(e: MouseEvent) {
if (
containerRef.current &&
!containerRef.current.contains(e.target as Node)
) {
setIsOpen(false);
// Reset input to selected category name
if (selectedCategory) {
setInputValue("");
}
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, [selectedCategory]);
function handleSelect(categoryId: number) {
onChange(categoryId);
setInputValue("");
setIsOpen(false);
setHighlightIndex(-1);
}
async function handleCreate() {
const name = inputValue.trim();
if (!name) return;
createCategory.mutate(
{ name, emoji: "\u{1F4E6}" },
{
onSuccess: (newCat) => {
handleSelect(newCat.id);
},
},
);
}
function handleKeyDown(e: React.KeyboardEvent) {
if (!isOpen) {
if (e.key === "ArrowDown" || e.key === "Enter") {
setIsOpen(true);
e.preventDefault();
}
return;
}
switch (e.key) {
case "ArrowDown":
e.preventDefault();
setHighlightIndex((i) => Math.min(i + 1, totalOptions - 1));
break;
case "ArrowUp":
e.preventDefault();
setHighlightIndex((i) => Math.max(i - 1, 0));
break;
case "Enter":
e.preventDefault();
if (highlightIndex >= 0 && highlightIndex < filtered.length) {
handleSelect(filtered[highlightIndex].id);
} else if (
showCreateOption &&
highlightIndex === filtered.length
) {
handleCreate();
}
break;
case "Escape":
setIsOpen(false);
setHighlightIndex(-1);
setInputValue("");
break;
}
}
// Scroll highlighted option into view
useEffect(() => {
if (highlightIndex >= 0 && listRef.current) {
const option = listRef.current.children[highlightIndex] as HTMLElement;
option?.scrollIntoView({ block: "nearest" });
}
}, [highlightIndex]);
return (
<div ref={containerRef} className="relative">
<input
ref={inputRef}
type="text"
role="combobox"
aria-expanded={isOpen}
aria-autocomplete="list"
aria-controls="category-listbox"
aria-activedescendant={
highlightIndex >= 0 ? `category-option-${highlightIndex}` : undefined
}
value={
isOpen
? inputValue
: selectedCategory
? `${selectedCategory.emoji} ${selectedCategory.name}`
: ""
}
placeholder="Search or create category..."
onChange={(e) => {
setInputValue(e.target.value);
setIsOpen(true);
setHighlightIndex(-1);
}}
onFocus={() => {
setIsOpen(true);
setInputValue("");
}}
onKeyDown={handleKeyDown}
className="w-full 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"
/>
{isOpen && (
<ul
ref={listRef}
id="category-listbox"
role="listbox"
className="absolute z-20 mt-1 w-full max-h-48 overflow-auto bg-white border border-gray-200 rounded-lg shadow-lg"
>
{filtered.map((cat, i) => (
<li
key={cat.id}
id={`category-option-${i}`}
role="option"
aria-selected={cat.id === value}
className={`px-3 py-2 text-sm cursor-pointer ${
i === highlightIndex
? "bg-blue-50 text-blue-900"
: "hover:bg-gray-50"
} ${cat.id === value ? "font-medium" : ""}`}
onClick={() => handleSelect(cat.id)}
onMouseEnter={() => setHighlightIndex(i)}
>
{cat.emoji} {cat.name}
</li>
))}
{showCreateOption && (
<li
id={`category-option-${filtered.length}`}
role="option"
aria-selected={false}
className={`px-3 py-2 text-sm cursor-pointer border-t border-gray-100 ${
highlightIndex === filtered.length
? "bg-blue-50 text-blue-900"
: "hover:bg-gray-50 text-gray-600"
}`}
onClick={handleCreate}
onMouseEnter={() => setHighlightIndex(filtered.length)}
>
+ Create "{inputValue.trim()}"
</li>
)}
{filtered.length === 0 && !showCreateOption && (
<li className="px-3 py-2 text-sm text-gray-400">
No categories found
</li>
)}
</ul>
)}
</div>
);
}

View File

@@ -0,0 +1,283 @@
import { useState, useEffect } from "react";
import { useCreateItem, useUpdateItem, useItems } from "../hooks/useItems";
import { useUIStore } from "../stores/uiStore";
import { CategoryPicker } from "./CategoryPicker";
import { ImageUpload } from "./ImageUpload";
interface ItemFormProps {
mode: "add" | "edit";
itemId?: number | null;
}
interface FormData {
name: string;
weightGrams: string;
priceDollars: string;
categoryId: number;
notes: string;
productUrl: string;
imageFilename: string | null;
}
const INITIAL_FORM: FormData = {
name: "",
weightGrams: "",
priceDollars: "",
categoryId: 1,
notes: "",
productUrl: "",
imageFilename: null,
};
export function ItemForm({ mode, itemId }: ItemFormProps) {
const { data: items } = useItems();
const createItem = useCreateItem();
const updateItem = useUpdateItem();
const closePanel = useUIStore((s) => s.closePanel);
const openConfirmDelete = useUIStore((s) => s.openConfirmDelete);
const [form, setForm] = useState<FormData>(INITIAL_FORM);
const [errors, setErrors] = useState<Record<string, string>>({});
// Pre-fill form when editing
useEffect(() => {
if (mode === "edit" && itemId != null && items) {
const item = items.find((i) => i.id === itemId);
if (item) {
setForm({
name: item.name,
weightGrams:
item.weightGrams != null ? String(item.weightGrams) : "",
priceDollars:
item.priceCents != null ? (item.priceCents / 100).toFixed(2) : "",
categoryId: item.categoryId,
notes: item.notes ?? "",
productUrl: item.productUrl ?? "",
imageFilename: item.imageFilename,
});
}
} else if (mode === "add") {
setForm(INITIAL_FORM);
}
}, [mode, itemId, items]);
function validate(): boolean {
const newErrors: Record<string, string> = {};
if (!form.name.trim()) {
newErrors.name = "Name is required";
}
if (form.weightGrams && (isNaN(Number(form.weightGrams)) || Number(form.weightGrams) < 0)) {
newErrors.weightGrams = "Must be a positive number";
}
if (form.priceDollars && (isNaN(Number(form.priceDollars)) || Number(form.priceDollars) < 0)) {
newErrors.priceDollars = "Must be a positive number";
}
if (
form.productUrl &&
form.productUrl.trim() !== "" &&
!form.productUrl.match(/^https?:\/\//)
) {
newErrors.productUrl = "Must be a valid URL (https://...)";
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
if (!validate()) return;
const payload = {
name: form.name.trim(),
weightGrams: form.weightGrams ? Number(form.weightGrams) : undefined,
priceCents: form.priceDollars
? Math.round(Number(form.priceDollars) * 100)
: undefined,
categoryId: form.categoryId,
notes: form.notes.trim() || undefined,
productUrl: form.productUrl.trim() || undefined,
imageFilename: form.imageFilename ?? undefined,
};
if (mode === "add") {
createItem.mutate(payload, {
onSuccess: () => {
setForm(INITIAL_FORM);
closePanel();
},
});
} else if (itemId != null) {
updateItem.mutate(
{ id: itemId, ...payload },
{ onSuccess: () => closePanel() },
);
}
}
const isPending = createItem.isPending || updateItem.isPending;
return (
<form onSubmit={handleSubmit} className="space-y-5">
{/* Name */}
<div>
<label
htmlFor="item-name"
className="block text-sm font-medium text-gray-700 mb-1"
>
Name *
</label>
<input
id="item-name"
type="text"
value={form.name}
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
className="w-full 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"
placeholder="e.g. Osprey Talon 22"
autoFocus
/>
{errors.name && (
<p className="mt-1 text-xs text-red-500">{errors.name}</p>
)}
</div>
{/* Weight */}
<div>
<label
htmlFor="item-weight"
className="block text-sm font-medium text-gray-700 mb-1"
>
Weight (g)
</label>
<input
id="item-weight"
type="number"
min="0"
step="any"
value={form.weightGrams}
onChange={(e) =>
setForm((f) => ({ ...f, weightGrams: e.target.value }))
}
className="w-full 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"
placeholder="e.g. 680"
/>
{errors.weightGrams && (
<p className="mt-1 text-xs text-red-500">{errors.weightGrams}</p>
)}
</div>
{/* Price */}
<div>
<label
htmlFor="item-price"
className="block text-sm font-medium text-gray-700 mb-1"
>
Price ($)
</label>
<input
id="item-price"
type="number"
min="0"
step="0.01"
value={form.priceDollars}
onChange={(e) =>
setForm((f) => ({ ...f, priceDollars: e.target.value }))
}
className="w-full 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"
placeholder="e.g. 129.99"
/>
{errors.priceDollars && (
<p className="mt-1 text-xs text-red-500">{errors.priceDollars}</p>
)}
</div>
{/* Category */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Category
</label>
<CategoryPicker
value={form.categoryId}
onChange={(id) => setForm((f) => ({ ...f, categoryId: id }))}
/>
</div>
{/* Notes */}
<div>
<label
htmlFor="item-notes"
className="block text-sm font-medium text-gray-700 mb-1"
>
Notes
</label>
<textarea
id="item-notes"
value={form.notes}
onChange={(e) => setForm((f) => ({ ...f, notes: e.target.value }))}
rows={3}
className="w-full 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 resize-none"
placeholder="Any additional notes..."
/>
</div>
{/* Product Link */}
<div>
<label
htmlFor="item-url"
className="block text-sm font-medium text-gray-700 mb-1"
>
Product Link
</label>
<input
id="item-url"
type="url"
value={form.productUrl}
onChange={(e) =>
setForm((f) => ({ ...f, productUrl: e.target.value }))
}
className="w-full 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"
placeholder="https://..."
/>
{errors.productUrl && (
<p className="mt-1 text-xs text-red-500">{errors.productUrl}</p>
)}
</div>
{/* Image */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Image
</label>
<ImageUpload
value={form.imageFilename}
onChange={(filename) =>
setForm((f) => ({ ...f, imageFilename: filename }))
}
/>
</div>
{/* Actions */}
<div className="flex gap-3 pt-2">
<button
type="submit"
disabled={isPending}
className="flex-1 py-2.5 px-4 bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white text-sm font-medium rounded-lg transition-colors"
>
{isPending
? "Saving..."
: mode === "add"
? "Add Item"
: "Save Changes"}
</button>
{mode === "edit" && itemId != null && (
<button
type="button"
onClick={() => openConfirmDelete(itemId)}
className="py-2.5 px-4 text-red-600 hover:bg-red-50 text-sm font-medium rounded-lg transition-colors"
>
Delete
</button>
)}
</div>
</form>
);
}

View File

@@ -0,0 +1,76 @@
import { useEffect } from "react";
interface SlideOutPanelProps {
isOpen: boolean;
onClose: () => void;
title: string;
children: React.ReactNode;
}
export function SlideOutPanel({
isOpen,
onClose,
title,
children,
}: SlideOutPanelProps) {
// Close on Escape key
useEffect(() => {
function handleKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") onClose();
}
if (isOpen) {
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}
}, [isOpen, onClose]);
return (
<>
{/* Backdrop */}
<div
className={`fixed inset-0 z-30 bg-black/20 transition-opacity ${
isOpen
? "opacity-100 pointer-events-auto"
: "opacity-0 pointer-events-none"
}`}
onClick={onClose}
/>
{/* Panel */}
<div
className={`fixed top-0 right-0 z-40 h-full w-full sm:w-[400px] bg-white shadow-xl transition-transform duration-300 ease-in-out ${
isOpen ? "translate-x-0" : "translate-x-full"
}`}
>
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
<h2 className="text-lg font-semibold text-gray-900">{title}</h2>
<button
type="button"
onClick={onClose}
className="p-1 text-gray-400 hover:text-gray-600 rounded"
>
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
{/* Content */}
<div className="overflow-y-auto h-[calc(100%-65px)] px-6 py-4">
{children}
</div>
</div>
</>
);
}

View File

@@ -1,14 +1,64 @@
import { createRootRoute, Outlet } from "@tanstack/react-router"; import { createRootRoute, Outlet } from "@tanstack/react-router";
import "../app.css"; import "../app.css";
import { TotalsBar } from "../components/TotalsBar";
import { SlideOutPanel } from "../components/SlideOutPanel";
import { ItemForm } from "../components/ItemForm";
import { ConfirmDialog } from "../components/ConfirmDialog";
import { useUIStore } from "../stores/uiStore";
export const Route = createRootRoute({ export const Route = createRootRoute({
component: RootLayout, component: RootLayout,
}); });
function RootLayout() { function RootLayout() {
const panelMode = useUIStore((s) => s.panelMode);
const editingItemId = useUIStore((s) => s.editingItemId);
const openAddPanel = useUIStore((s) => s.openAddPanel);
const closePanel = useUIStore((s) => s.closePanel);
const isOpen = panelMode !== "closed";
return ( return (
<div className="min-h-screen bg-gray-50"> <div className="min-h-screen bg-gray-50">
<TotalsBar />
<Outlet /> <Outlet />
{/* Slide-out Panel */}
<SlideOutPanel
isOpen={isOpen}
onClose={closePanel}
title={panelMode === "add" ? "Add Item" : "Edit Item"}
>
{panelMode === "add" && <ItemForm mode="add" />}
{panelMode === "edit" && (
<ItemForm mode="edit" itemId={editingItemId} />
)}
</SlideOutPanel>
{/* Confirm Delete Dialog */}
<ConfirmDialog />
{/* Floating Add Button */}
<button
type="button"
onClick={openAddPanel}
className="fixed bottom-6 right-6 z-20 w-14 h-14 bg-blue-600 hover:bg-blue-700 text-white rounded-full shadow-lg hover:shadow-xl transition-all flex items-center justify-center"
title="Add new item"
>
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 4v16m8-8H4"
/>
</svg>
</button>
</div> </div>
); );
} }

View File

@@ -1,13 +1,138 @@
import { createFileRoute } from "@tanstack/react-router"; import { createFileRoute } from "@tanstack/react-router";
import { useItems } from "../hooks/useItems";
import { useTotals } from "../hooks/useTotals";
import { CategoryHeader } from "../components/CategoryHeader";
import { ItemCard } from "../components/ItemCard";
import { useUIStore } from "../stores/uiStore";
export const Route = createFileRoute("/")({ export const Route = createFileRoute("/")({
component: CollectionPage, component: CollectionPage,
}); });
function CollectionPage() { function CollectionPage() {
const { data: items, isLoading: itemsLoading } = useItems();
const { data: totals } = useTotals();
const openAddPanel = useUIStore((s) => s.openAddPanel);
if (itemsLoading) {
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="h-6 bg-gray-200 rounded w-48" />
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{[1, 2, 3].map((i) => (
<div key={i} className="h-40 bg-gray-200 rounded-xl" />
))}
</div>
</div>
</div>
);
}
if (!items || items.length === 0) {
return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 text-center">
<div className="max-w-md mx-auto">
<div className="text-5xl mb-4">🎒</div>
<h2 className="text-xl font-semibold text-gray-900 mb-2">
Your collection is empty
</h2>
<p className="text-sm text-gray-500 mb-6">
Start cataloging your gear by adding your first item. Track weight,
price, and organize by category.
</p>
<button
type="button"
onClick={openAddPanel}
className="inline-flex items-center gap-2 px-5 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors"
>
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 4v16m8-8H4"
/>
</svg>
Add your first item
</button>
</div>
</div>
);
}
// Group items by categoryId
const groupedItems = new Map<
number,
{ items: typeof items; categoryName: string; categoryEmoji: string }
>();
for (const item of items) {
const group = groupedItems.get(item.categoryId);
if (group) {
group.items.push(item);
} else {
groupedItems.set(item.categoryId, {
items: [item],
categoryName: item.categoryName,
categoryEmoji: item.categoryEmoji,
});
}
}
// Build category totals lookup
const categoryTotalsMap = new Map<
number,
{ totalWeight: number; totalCost: number; itemCount: number }
>();
if (totals?.categories) {
for (const ct of totals.categories) {
categoryTotalsMap.set(ct.categoryId, {
totalWeight: ct.totalWeight,
totalCost: ct.totalCost,
itemCount: ct.itemCount,
});
}
}
return ( return (
<div className="p-8"> <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
<h1 className="text-2xl font-bold text-gray-900">GearBox Collection</h1> {Array.from(groupedItems.entries()).map(
([categoryId, { items: categoryItems, categoryName, categoryEmoji }]) => {
const catTotals = categoryTotalsMap.get(categoryId);
return (
<div key={categoryId} className="mb-8">
<CategoryHeader
categoryId={categoryId}
name={categoryName}
emoji={categoryEmoji}
totalWeight={catTotals?.totalWeight ?? 0}
totalCost={catTotals?.totalCost ?? 0}
itemCount={catTotals?.itemCount ?? categoryItems.length}
/>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{categoryItems.map((item) => (
<ItemCard
key={item.id}
id={item.id}
name={item.name}
weightGrams={item.weightGrams}
priceCents={item.priceCents}
categoryName={categoryName}
categoryEmoji={categoryEmoji}
imageFilename={item.imageFilename}
/>
))}
</div>
</div>
);
},
)}
</div> </div>
); );
} }