docs: complete project research
This commit is contained in:
@@ -1,362 +1,677 @@
|
|||||||
# Architecture Research
|
# Architecture Research
|
||||||
|
|
||||||
**Domain:** Single-user gear management and purchase planning web app
|
**Domain:** Gear management app -- v1.2 feature integration (search/filter, weight classification, weight distribution charts, candidate status tracking, weight unit selection)
|
||||||
**Researched:** 2026-03-14
|
**Researched:** 2026-03-16
|
||||||
**Confidence:** HIGH
|
**Confidence:** HIGH
|
||||||
|
|
||||||
## Standard Architecture
|
## System Overview: Integration Map
|
||||||
|
|
||||||
### System Overview
|
The v1.2 features integrate across all existing layers. This diagram shows where new components slot in relative to the current architecture.
|
||||||
|
|
||||||
```
|
```
|
||||||
┌─────────────────────────────────────────────────────────────────┐
|
CLIENT LAYER
|
||||||
│ Client (Browser) │
|
+-----------------------------------------------------------------+
|
||||||
│ ┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐ │
|
| Routes |
|
||||||
│ │ Dashboard │ │Collection │ │ Threads │ │ Setups │ │
|
| +------------+ +------------+ +------------+ |
|
||||||
│ │ Page │ │ Page │ │ Page │ │ Page │ │
|
| | /collection| | /threads/$ | | /setups/$ | |
|
||||||
│ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ └─────┬─────┘ │
|
| | [MODIFIED] | | [MODIFIED] | | [MODIFIED] | |
|
||||||
│ │ │ │ │ │
|
| +------+-----+ +------+-----+ +------+-----+ |
|
||||||
│ ┌─────┴──────────────┴──────────────┴──────────────┴─────┐ │
|
| | | | |
|
||||||
│ │ Shared UI Components │ │
|
| Components (NEW) |
|
||||||
│ │ (ItemCard, ComparisonTable, WeightBadge, CostBadge) │ │
|
| +------------+ +--------------+ +-------------+ |
|
||||||
│ └────────────────────────┬───────────────────────────────┘ │
|
| | SearchBar | | WeightChart | | UnitSelector| |
|
||||||
│ │ fetch() │
|
| +------------+ +--------------+ +-------------+ |
|
||||||
├───────────────────────────┼────────────────────────────────────┤
|
| |
|
||||||
│ Bun.serve() │
|
| Components (MODIFIED) |
|
||||||
│ ┌────────────────────────┴───────────────────────────────┐ │
|
| +------------+ +--------------+ +-------------+ |
|
||||||
│ │ API Routes Layer │ │
|
| | ItemCard | | CandidateCard| | TotalsBar | |
|
||||||
│ │ /api/items /api/threads /api/setups │ │
|
| | ItemForm | | CandidateForm| | CategoryHdr | |
|
||||||
│ │ /api/stats /api/candidates /api/images │ │
|
| +------------+ +--------------+ +-------------+ |
|
||||||
│ └────────────────────────┬───────────────────────────────┘ │
|
| |
|
||||||
│ │ │
|
| Hooks (NEW) Hooks (MODIFIED) |
|
||||||
│ ┌────────────────────────┴───────────────────────────────┐ │
|
| +------------------+ +------------------+ |
|
||||||
│ │ Service Layer │ │
|
| | useFormatWeight | | useSetups | |
|
||||||
│ │ ItemService ThreadService SetupService StatsService│ │
|
| +------------------+ | useThreads | |
|
||||||
│ └────────────────────────┬───────────────────────────────┘ │
|
| +------------------+ |
|
||||||
│ │ │
|
| |
|
||||||
│ ┌────────────────────────┴───────────────────────────────┐ │
|
| Lib (MODIFIED) Stores (NO CHANGE) |
|
||||||
│ │ Data Access (Drizzle ORM) │ │
|
| +------------------+ +------------------+ |
|
||||||
│ │ Schema + Queries │ │
|
| | formatters.ts | | uiStore.ts | |
|
||||||
│ └────────────────────────┬───────────────────────────────┘ │
|
| +------------------+ +------------------+ |
|
||||||
│ │ │
|
+-----------------------------------------------------------------+
|
||||||
│ ┌────────────────────────┴───────────────────────────────┐ │
|
| API Layer: lib/api.ts -- NO CHANGE |
|
||||||
│ │ SQLite (bun:sqlite) │ │
|
+-----------------------------------------------------------------+
|
||||||
│ │ gearbox.db file │ │
|
SERVER LAYER
|
||||||
│ └────────────────────────────────────────────────────────┘ │
|
| Routes (MODIFIED) |
|
||||||
└─────────────────────────────────────────────────────────────────┘
|
| +------------+ +------------+ +------------+ |
|
||||||
|
| | items.ts | | threads.ts | | setups.ts | |
|
||||||
|
| | (no change)| | (no change)| | +PATCH item| |
|
||||||
|
| +------+-----+ +------+-----+ +------+-----+ |
|
||||||
|
| | | | |
|
||||||
|
| Services (MODIFIED) |
|
||||||
|
| +------------+ +--------------+ +--------------+ |
|
||||||
|
| | item.svc | | thread.svc | | setup.svc | |
|
||||||
|
| | (no change)| | +cand.status | | +weightClass | |
|
||||||
|
| +------+-----+ +------+-------+ +------+-------+ |
|
||||||
|
+---------+----------------+----------------+---------------------+
|
||||||
|
DATABASE LAYER
|
||||||
|
| schema.ts (MODIFIED) |
|
||||||
|
| +----------------------------------------------------------+ |
|
||||||
|
| | setup_items: +weight_class TEXT DEFAULT 'base' | |
|
||||||
|
| | thread_candidates: +status TEXT DEFAULT 'researching' | |
|
||||||
|
| | settings: weightUnit row (uses existing key-value table) | |
|
||||||
|
| +----------------------------------------------------------+ |
|
||||||
|
| |
|
||||||
|
| tests/helpers/db.ts (MODIFIED -- add new columns) |
|
||||||
|
+-----------------------------------------------------------------+
|
||||||
```
|
```
|
||||||
|
|
||||||
This is a monolithic full-stack app running on a single Bun process. No microservices, no separate API server, no Docker. Bun's built-in fullstack dev server handles both static asset bundling and API routes from a single `Bun.serve()` call. SQLite is the database -- embedded, zero-config, accessed through Bun's native `bun:sqlite` module (3-6x faster than better-sqlite3).
|
## Feature-by-Feature Integration
|
||||||
|
|
||||||
### Component Responsibilities
|
### Feature 1: Search Items and Filter by Category
|
||||||
|
|
||||||
| Component | Responsibility | Typical Implementation |
|
**Scope:** Client-side filtering of already-fetched data. No server changes needed -- the collection is small enough (single user) that client-side filtering is both simpler and faster.
|
||||||
|-----------|----------------|------------------------|
|
|
||||||
| Dashboard Page | Entry point, summary cards, navigation | React page showing item count, active threads, setup stats |
|
|
||||||
| Collection Page | CRUD for gear items, filtering, sorting | React page with list/grid views, item detail modal |
|
|
||||||
| Threads Page | Purchase research threads with candidates | React page with thread list, candidate comparison view |
|
|
||||||
| Setups Page | Compose named setups from collection items | React page with drag/drop or select-to-add from collection |
|
|
||||||
| API Routes | HTTP endpoints for all data operations | Bun.serve() route handlers, REST-style |
|
|
||||||
| Service Layer | Business logic, calculations (weight/cost totals) | TypeScript modules with domain logic |
|
|
||||||
| Data Access | Schema definition, queries, migrations | Drizzle ORM with SQLite dialect |
|
|
||||||
| SQLite DB | Persistent storage | Single file, bun:sqlite native module |
|
|
||||||
| Image Storage | Photo uploads for gear items | Local filesystem (`./uploads/`) served as static files |
|
|
||||||
|
|
||||||
## Recommended Project Structure
|
**Integration points:**
|
||||||
|
|
||||||
|
| Layer | File | Change Type | Details |
|
||||||
|
|-------|------|-------------|---------|
|
||||||
|
| Client | `routes/collection/index.tsx` | MODIFY | Add search input and category filter dropdown above the gear grid in `CollectionView` |
|
||||||
|
| Client | NEW `components/SearchBar.tsx` | NEW | Reusable search input component with clear button |
|
||||||
|
| Client | `hooks/useItems.ts` | NO CHANGE | Already returns all items; filtering happens in the route |
|
||||||
|
|
||||||
|
**Data flow:**
|
||||||
|
|
||||||
```
|
```
|
||||||
src/
|
CollectionView (owns search/filter state via useState)
|
||||||
├── index.tsx # Bun.serve() entry point, route registration
|
|
|
||||||
├── pages/ # HTML entrypoints for each page
|
+-- SearchBar (controlled input, calls setSearchTerm)
|
||||||
│ ├── index.html # Dashboard
|
+-- CategoryFilter (dropdown from useCategories, calls setCategoryFilter)
|
||||||
│ ├── collection.html # Collection page
|
|
|
||||||
│ ├── threads.html # Planning threads page
|
+-- Items = useItems().data
|
||||||
│ └── setups.html # Setups page
|
.filter(item => matchesSearch(item.name, searchTerm))
|
||||||
├── client/ # React frontend code
|
.filter(item => !categoryFilter || item.categoryId === categoryFilter)
|
||||||
│ ├── components/ # Shared UI components
|
|
|
||||||
│ │ ├── ItemCard.tsx
|
+-- Grouped by category -> rendered as before
|
||||||
│ │ ├── WeightBadge.tsx
|
|
||||||
│ │ ├── CostBadge.tsx
|
|
||||||
│ │ ├── ComparisonTable.tsx
|
|
||||||
│ │ ├── StatusBadge.tsx
|
|
||||||
│ │ └── Layout.tsx
|
|
||||||
│ ├── pages/ # Page-level React components
|
|
||||||
│ │ ├── Dashboard.tsx
|
|
||||||
│ │ ├── Collection.tsx
|
|
||||||
│ │ ├── ThreadList.tsx
|
|
||||||
│ │ ├── ThreadDetail.tsx
|
|
||||||
│ │ ├── SetupList.tsx
|
|
||||||
│ │ └── SetupDetail.tsx
|
|
||||||
│ ├── hooks/ # Custom React hooks
|
|
||||||
│ │ ├── useItems.ts
|
|
||||||
│ │ ├── useThreads.ts
|
|
||||||
│ │ └── useSetups.ts
|
|
||||||
│ └── lib/ # Client utilities
|
|
||||||
│ ├── api.ts # Fetch wrapper for API calls
|
|
||||||
│ └── formatters.ts # Weight/cost formatting helpers
|
|
||||||
├── server/ # Backend code
|
|
||||||
│ ├── routes/ # API route handlers
|
|
||||||
│ │ ├── items.ts
|
|
||||||
│ │ ├── threads.ts
|
|
||||||
│ │ ├── candidates.ts
|
|
||||||
│ │ ├── setups.ts
|
|
||||||
│ │ ├── images.ts
|
|
||||||
│ │ └── stats.ts
|
|
||||||
│ └── services/ # Business logic
|
|
||||||
│ ├── item.service.ts
|
|
||||||
│ ├── thread.service.ts
|
|
||||||
│ ├── setup.service.ts
|
|
||||||
│ └── stats.service.ts
|
|
||||||
├── db/ # Database layer
|
|
||||||
│ ├── schema.ts # Drizzle table definitions
|
|
||||||
│ ├── index.ts # Database connection singleton
|
|
||||||
│ ├── seed.ts # Optional dev seed data
|
|
||||||
│ └── migrations/ # Drizzle Kit generated migrations
|
|
||||||
├── shared/ # Types shared between client and server
|
|
||||||
│ └── types.ts # Item, Thread, Candidate, Setup types
|
|
||||||
uploads/ # Gear photos (gitignored, outside src/)
|
|
||||||
drizzle.config.ts # Drizzle Kit config
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Structure Rationale
|
**Why client-side:** The `useItems()` hook already fetches all items. For a single-user app, even 500 items is trivially fast to filter in memory. Adding server-side search would mean new API parameters, new query logic, and pagination -- all unnecessary complexity. If the collection grows beyond ~2000 items someday, server-side search can be added to the existing `getAllItems` service function by accepting optional `search` and `categoryId` parameters and adding Drizzle `like()` + `eq()` conditions.
|
||||||
|
|
||||||
- **`client/` and `server/` separation:** Clear boundary between browser code and server code. Both import from `shared/` and `db/` (server only) but never from each other.
|
**Pattern -- filtered items with useMemo:**
|
||||||
- **`pages/` HTML entrypoints:** Bun's fullstack server uses HTML files as route entrypoints. Each HTML file imports its corresponding React component tree.
|
|
||||||
- **`server/routes/` + `server/services/`:** Routes handle HTTP concerns (parsing params, status codes). Services handle business logic (calculating totals, validating state transitions). This prevents bloated route handlers.
|
|
||||||
- **`db/schema.ts` as single source of truth:** All table definitions in one file. Drizzle infers TypeScript types from the schema, so types flow from DB to API to client.
|
|
||||||
- **`shared/types.ts`:** API response types and domain enums shared between client and server. Avoids type drift.
|
|
||||||
- **`uploads/` outside `src/`:** User-uploaded images are not source code. Served as static files by Bun.
|
|
||||||
|
|
||||||
## Architectural Patterns
|
|
||||||
|
|
||||||
### Pattern 1: Bun Fullstack Monolith
|
|
||||||
|
|
||||||
**What:** Single Bun.serve() process serves HTML pages, bundled React assets, and API routes. No separate frontend dev server, no proxy config, no CORS.
|
|
||||||
**When to use:** Single-user apps, prototypes, small team projects where deployment simplicity matters.
|
|
||||||
**Trade-offs:** Extremely simple to deploy (one process, one command), but no horizontal scaling. For GearBox this is ideal -- single user, no scaling needed.
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```typescript
|
```typescript
|
||||||
// src/index.tsx
|
// In CollectionView component
|
||||||
import homepage from "./pages/index.html";
|
const [searchTerm, setSearchTerm] = useState("");
|
||||||
import collectionPage from "./pages/collection.html";
|
const [categoryFilter, setCategoryFilter] = useState<number | null>(null);
|
||||||
import { itemRoutes } from "./server/routes/items";
|
|
||||||
import { threadRoutes } from "./server/routes/threads";
|
|
||||||
|
|
||||||
Bun.serve({
|
const filteredItems = useMemo(() => {
|
||||||
routes: {
|
if (!items) return [];
|
||||||
"/": homepage,
|
return items
|
||||||
"/collection": collectionPage,
|
.filter(item => {
|
||||||
...itemRoutes,
|
if (!searchTerm) return true;
|
||||||
...threadRoutes,
|
return item.name.toLowerCase().includes(searchTerm.toLowerCase());
|
||||||
},
|
})
|
||||||
development: true,
|
.filter(item => {
|
||||||
});
|
if (!categoryFilter) return true;
|
||||||
|
return item.categoryId === categoryFilter;
|
||||||
|
});
|
||||||
|
}, [items, searchTerm, categoryFilter]);
|
||||||
```
|
```
|
||||||
|
|
||||||
### Pattern 2: Service Layer for Business Logic
|
No debounce library needed -- `useMemo` re-computes on keystroke, and filtering an in-memory array of <1000 items is sub-millisecond. Debounce is only needed if triggering API calls.
|
||||||
|
|
||||||
**What:** Route handlers delegate to service modules that contain domain logic. Services are pure functions or classes that take data in and return results, with no HTTP awareness.
|
**The category filter already exists** in `PlanningView` (lines 191-209 and 277-290 in `collection/index.tsx`). The same pattern should be reused for the gear tab with an icon-aware dropdown replacing the plain `<select>`. The existing `useCategories` hook provides the category list.
|
||||||
**When to use:** When routes would otherwise contain calculation logic (weight totals, cost impact analysis, status transitions).
|
|
||||||
**Trade-offs:** Slightly more files, but logic is testable without HTTP mocking and reusable across routes.
|
**Planning category filter upgrade:** The current plain `<select>` in PlanningView should be upgraded to an icon-aware dropdown that shows Lucide icons next to category names. This is a shared component that both the gear tab filter and the planning tab filter can use.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Feature 2: Weight Classification (Base / Worn / Consumable)
|
||||||
|
|
||||||
|
**Scope:** Per-item-per-setup classification. An item's classification depends on the setup context (a rain jacket might be "worn" in one setup and "base" in another). This means the classification lives on the `setup_items` join table, not on the `items` table.
|
||||||
|
|
||||||
|
**Integration points:**
|
||||||
|
|
||||||
|
| Layer | File | Change Type | Details |
|
||||||
|
|-------|------|-------------|---------|
|
||||||
|
| DB | `schema.ts` | MODIFY | Add `weightClass` column to `setup_items` |
|
||||||
|
| DB | Drizzle migration | NEW | `ALTER TABLE setup_items ADD COLUMN weight_class TEXT NOT NULL DEFAULT 'base'` |
|
||||||
|
| Shared | `schemas.ts` | MODIFY | Add `weightClass` to sync schema, add update schema |
|
||||||
|
| Shared | `types.ts` | NO CHANGE | Types auto-infer from Drizzle schema |
|
||||||
|
| Server | `setup.service.ts` | MODIFY | `getSetupWithItems` returns `weightClass`; add `updateSetupItemClass` function |
|
||||||
|
| Server | `routes/setups.ts` | MODIFY | Add `PATCH /:id/items/:itemId` for classification update |
|
||||||
|
| Client | `hooks/useSetups.ts` | MODIFY | `SetupItemWithCategory` type adds `weightClass`; add `useUpdateSetupItemClass` mutation |
|
||||||
|
| Client | `routes/setups/$setupId.tsx` | MODIFY | Show classification badges, add toggle UI, compute classification totals |
|
||||||
|
| Client | `components/ItemCard.tsx` | MODIFY | Accept optional `weightClass` prop for setup context |
|
||||||
|
| Test | `tests/helpers/db.ts` | MODIFY | Add `weight_class` column to `setup_items` CREATE TABLE |
|
||||||
|
|
||||||
|
**Schema change:**
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```typescript
|
```typescript
|
||||||
// server/services/setup.service.ts
|
// In schema.ts -- setup_items table
|
||||||
export function calculateSetupTotals(items: Item[]): SetupTotals {
|
export const setupItems = sqliteTable("setup_items", {
|
||||||
return {
|
|
||||||
totalWeight: items.reduce((sum, i) => sum + (i.weightGrams ?? 0), 0),
|
|
||||||
totalCost: items.reduce((sum, i) => sum + (i.priceCents ?? 0), 0),
|
|
||||||
itemCount: items.length,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function computeCandidateImpact(
|
|
||||||
setup: Setup,
|
|
||||||
candidate: Candidate
|
|
||||||
): Impact {
|
|
||||||
const currentTotals = calculateSetupTotals(setup.items);
|
|
||||||
return {
|
|
||||||
weightDelta: (candidate.weightGrams ?? 0) - (setup.replacingItem?.weightGrams ?? 0),
|
|
||||||
costDelta: (candidate.priceCents ?? 0) - (setup.replacingItem?.priceCents ?? 0),
|
|
||||||
newTotalWeight: currentTotals.totalWeight + this.weightDelta,
|
|
||||||
newTotalCost: currentTotals.totalCost + this.costDelta,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Pattern 3: Drizzle ORM with bun:sqlite
|
|
||||||
|
|
||||||
**What:** Drizzle provides type-safe SQL query building and schema-as-code migrations on top of Bun's native SQLite. Schema definitions double as TypeScript type sources.
|
|
||||||
**When to use:** Any Bun + SQLite project that wants type safety without the overhead of a full ORM like Prisma.
|
|
||||||
**Trade-offs:** Lightweight (no query engine, no runtime overhead). SQL-first philosophy means you write SQL-like code, not abstract methods. Migration tooling via Drizzle Kit is solid but simpler than Prisma Migrate.
|
|
||||||
|
|
||||||
**Example:**
|
|
||||||
```typescript
|
|
||||||
// db/schema.ts
|
|
||||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
|
||||||
|
|
||||||
export const items = sqliteTable("items", {
|
|
||||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||||
name: text("name").notNull(),
|
setupId: integer("setup_id")
|
||||||
category: text("category"),
|
.notNull()
|
||||||
weightGrams: integer("weight_grams"),
|
.references(() => setups.id, { onDelete: "cascade" }),
|
||||||
priceCents: integer("price_cents"),
|
itemId: integer("item_id")
|
||||||
purchaseSource: text("purchase_source"),
|
.notNull()
|
||||||
productUrl: text("product_url"),
|
.references(() => items.id, { onDelete: "cascade" }),
|
||||||
notes: text("notes"),
|
weightClass: text("weight_class").notNull().default("base"),
|
||||||
imageFilename: text("image_filename"),
|
// Values: "base" | "worn" | "consumable"
|
||||||
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
|
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Data Flow
|
**Why on setup_items, not items:** LighterPack and all serious gear tracking tools classify items per-loadout. A sleeping bag is "base weight" in a backpacking setup but might not be in a day hike setup. The same pair of hiking boots is "worn weight" in every setup, but this is a user choice per context. Storing on the join table preserves this flexibility at zero additional complexity -- the `setup_items` table already exists.
|
||||||
|
|
||||||
### Request Flow
|
**New endpoint for classification update:**
|
||||||
|
|
||||||
```
|
The existing sync pattern (delete-all + re-insert) would destroy classification data on every item add/remove. Instead, add a targeted update endpoint:
|
||||||
[User clicks "Add Item"]
|
|
||||||
|
|
```typescript
|
||||||
[React component] --> fetch("/api/items", { method: "POST", body })
|
// In setup.service.ts
|
||||||
|
|
export function updateSetupItemClass(
|
||||||
[Bun.serve route handler] --> validates input, calls service
|
db: Db,
|
||||||
|
|
setupId: number,
|
||||||
[ItemService.create()] --> business logic, defaults
|
itemId: number,
|
||||||
|
|
weightClass: "base" | "worn" | "consumable",
|
||||||
[Drizzle ORM] --> db.insert(items).values(...)
|
) {
|
||||||
|
|
return db
|
||||||
[bun:sqlite] --> writes to gearbox.db
|
.update(setupItems)
|
||||||
|
|
.set({ weightClass })
|
||||||
[Response] <-- { id, name, ... } JSON <-- 201 Created
|
.where(
|
||||||
|
|
sql`${setupItems.setupId} = ${setupId} AND ${setupItems.itemId} = ${itemId}`,
|
||||||
[React state update] --> re-renders item list
|
)
|
||||||
|
.run();
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Key Data Flows
|
```typescript
|
||||||
|
// In routes/setups.ts -- new PATCH route
|
||||||
1. **Collection CRUD:** Straightforward REST. Client sends item data, server validates, persists, returns updated item. Client hooks (useItems) manage local state.
|
app.patch("/:setupId/items/:itemId", zValidator("json", updateSetupItemClassSchema), (c) => {
|
||||||
|
const db = c.get("db");
|
||||||
2. **Thread lifecycle:** Create thread -> Add candidates -> Compare -> Resolve (pick winner). Resolution triggers: candidate becomes a collection item, thread status changes to "resolved", other candidates marked as rejected. This is the most stateful flow.
|
const setupId = Number(c.req.param("setupId"));
|
||||||
|
const itemId = Number(c.req.param("itemId"));
|
||||||
3. **Setup composition:** User selects items from collection to add to a named setup. Server calculates aggregate weight/cost. When viewing a thread candidate, "impact on setup" is computed by comparing candidate against current setup totals (or against a specific item being replaced).
|
const { weightClass } = c.req.valid("json");
|
||||||
|
updateSetupItemClass(db, setupId, itemId, weightClass);
|
||||||
4. **Dashboard aggregation:** Dashboard fetches summary stats via `/api/stats` -- total items, total collection value, active threads count, setup count. This is a read-only aggregation endpoint, not a separate data store.
|
return c.json({ success: true });
|
||||||
|
});
|
||||||
5. **Image upload:** Multipart form upload to `/api/images`, saved to `./uploads/` with a UUID filename. The filename is stored on the item record. Images served as static files.
|
|
||||||
|
|
||||||
### Data Model Relationships
|
|
||||||
|
|
||||||
```
|
|
||||||
items (gear collection)
|
|
||||||
|
|
|
||||||
|-- 1:N --> setup_items (junction) <-- N:1 -- setups
|
|
||||||
|
|
|
||||||
|-- 1:N --> thread_candidates (when resolved, candidate -> item)
|
|
||||||
|
|
||||||
threads (planning threads)
|
|
||||||
|
|
|
||||||
|-- 1:N --> candidates (potential purchases)
|
|
||||||
|-- status: researching | ordered | arrived
|
|
||||||
|-- resolved_as: winner | rejected | null
|
|
||||||
|
|
||||||
setups
|
|
||||||
|
|
|
||||||
|-- N:M --> items (via setup_items junction table)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### State Management
|
**Also update syncSetupItems** to preserve existing classifications or accept them:
|
||||||
|
|
||||||
No global state library needed. React hooks + fetch are sufficient for a single-user app with this complexity level.
|
```typescript
|
||||||
|
// Updated syncSetupItems to accept optional weightClass
|
||||||
```
|
export function syncSetupItems(
|
||||||
[React Hook per domain] [API call] [Server] [SQLite]
|
db: Db,
|
||||||
useItems() state --------> GET /api/items --> route handler --> SELECT
|
setupId: number,
|
||||||
| |
|
items: Array<{ itemId: number; weightClass?: string }>,
|
||||||
|<-- setItems(data) <--- JSON response <--- query result <------+
|
) {
|
||||||
|
return db.transaction((tx) => {
|
||||||
|
tx.delete(setupItems).where(eq(setupItems.setupId, setupId)).run();
|
||||||
|
for (const item of items) {
|
||||||
|
tx.insert(setupItems)
|
||||||
|
.values({
|
||||||
|
setupId,
|
||||||
|
itemId: item.itemId,
|
||||||
|
weightClass: item.weightClass ?? "base",
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Each page manages its own state via custom hooks (`useItems`, `useThreads`, `useSetups`). No Redux, no Zustand. If a mutation on one page affects another (e.g., resolving a thread adds an item to collection), the target page simply refetches on mount.
|
**Sync schema update:**
|
||||||
|
|
||||||
## Scaling Considerations
|
```typescript
|
||||||
|
export const syncSetupItemsSchema = z.object({
|
||||||
|
items: z.array(z.object({
|
||||||
|
itemId: z.number().int().positive(),
|
||||||
|
weightClass: z.enum(["base", "worn", "consumable"]).default("base"),
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
| Scale | Architecture Adjustments |
|
This is a **breaking change** to the sync API shape (from `{ itemIds: number[] }` to `{ items: [...] }`). The single call site is `useSyncSetupItems` in `useSetups.ts`, called from `ItemPicker.tsx`.
|
||||||
|-------|--------------------------|
|
|
||||||
| Single user (GearBox) | SQLite + single Bun process. Zero infrastructure. This is the target. |
|
|
||||||
| 1-10 users | Still fine with SQLite in WAL mode. Add basic auth if needed. |
|
|
||||||
| 100+ users | Switch to PostgreSQL, add connection pooling, consider separate API server. Not relevant for this project. |
|
|
||||||
|
|
||||||
### Scaling Priorities
|
**Client-side classification totals** are computed from the setup items array, not from a separate API:
|
||||||
|
|
||||||
1. **First bottleneck:** Image storage. If users upload many high-res photos, disk fills up. Mitigation: resize on upload (sharp library), limit file sizes.
|
```typescript
|
||||||
2. **Second bottleneck:** SQLite write contention under concurrent access. Not a concern for single-user. If it ever matters, switch to WAL mode or PostgreSQL.
|
const baseWeight = setup.items
|
||||||
|
.filter(i => i.weightClass === "base")
|
||||||
|
.reduce((sum, i) => sum + (i.weightGrams ?? 0), 0);
|
||||||
|
|
||||||
## Anti-Patterns
|
const wornWeight = setup.items
|
||||||
|
.filter(i => i.weightClass === "worn")
|
||||||
|
.reduce((sum, i) => sum + (i.weightGrams ?? 0), 0);
|
||||||
|
|
||||||
### Anti-Pattern 1: Storing Money as Floats
|
const consumableWeight = setup.items
|
||||||
|
.filter(i => i.weightClass === "consumable")
|
||||||
|
.reduce((sum, i) => sum + (i.weightGrams ?? 0), 0);
|
||||||
|
```
|
||||||
|
|
||||||
**What people do:** Use `float` or JavaScript `number` for prices (e.g., `19.99`).
|
**UI for classification toggle:** A three-segment toggle on each item card within the setup detail view. Clicking a segment calls `useUpdateSetupItemClass`. The three segments use the same pill-tab pattern already used for Active/Resolved in PlanningView.
|
||||||
**Why it's wrong:** Floating point arithmetic causes rounding errors. `0.1 + 0.2 !== 0.3`. Price calculations silently drift.
|
|
||||||
**Do this instead:** Store prices as integers in cents (`1999` for $19.99). Format for display only in the UI layer. The schema uses `priceCents: integer`.
|
|
||||||
|
|
||||||
### Anti-Pattern 2: Overengineering State Management
|
---
|
||||||
|
|
||||||
**What people do:** Install Redux/Zustand/Jotai for a single-user CRUD app, create elaborate store slices, actions, reducers.
|
### Feature 3: Weight Distribution Visualization
|
||||||
**Why it's wrong:** Adds complexity with zero benefit when there is one user and no shared state across tabs or real-time updates.
|
|
||||||
**Do this instead:** Use React hooks with fetch. `useState` + `useEffect` + a thin API wrapper. Refetch on mount. Keep it boring.
|
|
||||||
|
|
||||||
### Anti-Pattern 3: SPA with Client-Side Routing for Everything
|
**Scope:** Donut chart showing weight breakdown by category (on collection page) and by classification (on setup detail page). Uses `react-minimal-pie-chart` (~2kB gzipped) instead of Recharts (~45kB) because this is the only chart in the app.
|
||||||
|
|
||||||
**What people do:** Build a full SPA with React Router, lazy loading, code splitting for 4-5 pages.
|
**Integration points:**
|
||||||
**Why it's wrong:** Bun's fullstack server already handles page routing via HTML entrypoints. Adding client-side routing means duplicating routing logic, losing Bun's built-in asset optimization per page, and adding bundle complexity.
|
|
||||||
**Do this instead:** Use Bun's HTML-based routing. Each page is a separate HTML entrypoint with its own React tree. Navigation between pages is standard `<a href>` links. Keep client-side routing for in-page state (e.g., tabs within thread detail) only.
|
|
||||||
|
|
||||||
### Anti-Pattern 4: Storing Computed Aggregates in the Database
|
| Layer | File | Change Type | Details |
|
||||||
|
|-------|------|-------------|---------|
|
||||||
|
| Package | `package.json` | MODIFY | Add `react-minimal-pie-chart` dependency |
|
||||||
|
| Client | NEW `components/WeightChart.tsx` | NEW | Reusable donut chart component |
|
||||||
|
| Client | `routes/collection/index.tsx` | MODIFY | Add chart above category list in gear tab |
|
||||||
|
| Client | `routes/setups/$setupId.tsx` | MODIFY | Add classification breakdown chart |
|
||||||
|
| Client | `hooks/useTotals.ts` | NO CHANGE | Already returns `CategoryTotals[]` with weights |
|
||||||
|
|
||||||
**What people do:** Store `totalWeight` and `totalCost` on the setup record, then try to keep them in sync when items change.
|
**Why react-minimal-pie-chart over Recharts:** The app needs exactly one chart type (donut/pie). Recharts adds ~45kB gzipped for a full charting library when only the PieChart component is used. `react-minimal-pie-chart` is <3kB gzipped, has zero dependencies beyond React, supports donut charts via `lineWidth` prop, includes animation, and provides label support. It is the right tool for a focused need.
|
||||||
**Why it's wrong:** Stale data, sync bugs, update anomalies. Items get edited but setup totals do not get recalculated.
|
|
||||||
**Do this instead:** Compute totals on read. SQLite is fast enough for `SUM()` across a handful of items. Calculate in the service layer or as a SQL aggregate. For a single-user app with small datasets, this is effectively instant.
|
|
||||||
|
|
||||||
## Integration Points
|
**Chart component pattern:**
|
||||||
|
|
||||||
### External Services
|
```typescript
|
||||||
|
// components/WeightChart.tsx
|
||||||
|
import { PieChart } from "react-minimal-pie-chart";
|
||||||
|
|
||||||
| Service | Integration Pattern | Notes |
|
interface WeightChartProps {
|
||||||
|---------|---------------------|-------|
|
segments: Array<{
|
||||||
| None for v1 | N/A | Single-user local app, no external APIs needed |
|
label: string;
|
||||||
| Product URLs | Outbound links only | Store URLs to retailer pages, no API scraping |
|
value: number; // weight in grams (always grams internally)
|
||||||
|
color: string;
|
||||||
|
}>;
|
||||||
|
size?: number;
|
||||||
|
}
|
||||||
|
|
||||||
### Internal Boundaries
|
export function WeightChart({ segments, size = 200 }: WeightChartProps) {
|
||||||
|
const filtered = segments.filter(s => s.value > 0);
|
||||||
|
if (filtered.length === 0) return null;
|
||||||
|
|
||||||
| Boundary | Communication | Notes |
|
return (
|
||||||
|----------|---------------|-------|
|
<PieChart
|
||||||
| Client <-> Server | REST API (JSON over fetch) | No WebSockets needed, no real-time requirements |
|
data={filtered.map(s => ({
|
||||||
| Routes <-> Services | Direct function calls | Same process, no serialization overhead |
|
title: s.label,
|
||||||
| Services <-> Database | Drizzle ORM queries | Type-safe, no raw SQL strings |
|
value: s.value,
|
||||||
| Server <-> Filesystem | Image read/write | `./uploads/` directory for gear photos |
|
color: s.color,
|
||||||
|
}))}
|
||||||
|
lineWidth={35} // donut style
|
||||||
|
paddingAngle={2}
|
||||||
|
rounded
|
||||||
|
animate
|
||||||
|
animationDuration={500}
|
||||||
|
style={{ height: size, width: size }}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Build Order (Dependency Chain)
|
**Two usage contexts:**
|
||||||
|
|
||||||
The architecture implies this build sequence:
|
1. **Collection page** -- weight by category. Data source: `useTotals().data.categories`. Each `CategoryTotals` already has `totalWeight` and `categoryName`. Assign a consistent color per category (use category index mapped to a palette array).
|
||||||
|
|
||||||
1. **Database schema + Drizzle setup** -- Everything depends on the data model. Define tables for items, threads, candidates, setups, setup_items first.
|
2. **Setup detail page** -- weight by classification. Data source: computed from `setup.items` grouping by `weightClass`. Three fixed colors for base/worn/consumable.
|
||||||
2. **API routes for items (CRUD)** -- The core entity. Threads and setups reference items.
|
|
||||||
3. **Collection UI** -- First visible feature. Validates the data model and API work end-to-end.
|
|
||||||
4. **Thread + candidate API and UI** -- Depends on items existing to resolve candidates into the collection.
|
|
||||||
5. **Setup composition API and UI** -- Depends on items existing to compose into setups.
|
|
||||||
6. **Dashboard** -- Aggregates stats from all other entities. Build last since it reads from everything.
|
|
||||||
7. **Polish: image upload, impact calculations, status tracking** -- Enhancement layer on top of working CRUD.
|
|
||||||
|
|
||||||
This ordering means each phase produces a usable increment: after phase 3 you have a working gear catalog, after phase 4 you can plan purchases, after phase 5 you can compose setups.
|
**Color palette for categories:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const CATEGORY_COLORS = [
|
||||||
|
"#6B7280", "#3B82F6", "#10B981", "#F59E0B",
|
||||||
|
"#EF4444", "#8B5CF6", "#EC4899", "#14B8A6",
|
||||||
|
"#F97316", "#6366F1", "#84CC16", "#06B6D4",
|
||||||
|
];
|
||||||
|
|
||||||
|
function getCategoryColor(index: number): string {
|
||||||
|
return CATEGORY_COLORS[index % CATEGORY_COLORS.length];
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Classification colors (matching the app's muted palette):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const CLASSIFICATION_COLORS = {
|
||||||
|
base: "#6B7280", // gray -- the core pack weight
|
||||||
|
worn: "#3B82F6", // blue -- on your body
|
||||||
|
consumable: "#F59E0B", // amber -- gets used up
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
**Chart placement:** On the collection page, the chart appears as a compact summary card above the category-grouped items, alongside the global totals. On the setup detail page, it appears in the sticky sub-bar area or as a collapsible section showing base/worn/consumable breakdown with a legend. Keep it compact -- this is a supplementary visualization, not the primary UI.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Feature 4: Candidate Status Tracking
|
||||||
|
|
||||||
|
**Scope:** Track candidate lifecycle from "researching" through "ordered" to "arrived". This is a column on the `thread_candidates` table, displayed as a badge on `CandidateCard`, and editable inline.
|
||||||
|
|
||||||
|
**Integration points:**
|
||||||
|
|
||||||
|
| Layer | File | Change Type | Details |
|
||||||
|
|-------|------|-------------|---------|
|
||||||
|
| DB | `schema.ts` | MODIFY | Add `status` column to `thread_candidates` |
|
||||||
|
| DB | Drizzle migration | NEW | `ALTER TABLE thread_candidates ADD COLUMN status TEXT NOT NULL DEFAULT 'researching'` |
|
||||||
|
| Shared | `schemas.ts` | MODIFY | Add `status` to candidate schemas |
|
||||||
|
| Server | `thread.service.ts` | MODIFY | Include `status` in candidate creates and updates |
|
||||||
|
| Server | `routes/threads.ts` | NO CHANGE | Already passes through all candidate fields |
|
||||||
|
| Client | `hooks/useThreads.ts` | MODIFY | `CandidateWithCategory` type adds `status` |
|
||||||
|
| Client | `hooks/useCandidates.ts` | NO CHANGE | `useUpdateCandidate` already handles partial updates |
|
||||||
|
| Client | `components/CandidateCard.tsx` | MODIFY | Show status badge, add click-to-cycle |
|
||||||
|
| Client | `components/CandidateForm.tsx` | MODIFY | Add status selector to form |
|
||||||
|
| Test | `tests/helpers/db.ts` | MODIFY | Add `status` column to `thread_candidates` CREATE TABLE |
|
||||||
|
|
||||||
|
**Schema change:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// In schema.ts -- thread_candidates table
|
||||||
|
export const threadCandidates = sqliteTable("thread_candidates", {
|
||||||
|
// ... existing fields ...
|
||||||
|
status: text("status").notNull().default("researching"),
|
||||||
|
// Values: "researching" | "ordered" | "arrived"
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Status badge colors (matching app's muted palette from v1.1):**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const CANDIDATE_STATUS_STYLES = {
|
||||||
|
researching: "bg-gray-100 text-gray-600",
|
||||||
|
ordered: "bg-amber-50 text-amber-600",
|
||||||
|
arrived: "bg-green-50 text-green-600",
|
||||||
|
} as const;
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline status cycling:** On `CandidateCard`, clicking the status badge cycles to the next state (researching -> ordered -> arrived). This calls the existing `useUpdateCandidate` mutation with just the status field. No new endpoint needed -- the `updateCandidate` service already accepts partial updates via `updateCandidateSchema.partial()`.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// In CandidateCard
|
||||||
|
const STATUS_ORDER = ["researching", "ordered", "arrived"] as const;
|
||||||
|
|
||||||
|
function cycleStatus(current: string) {
|
||||||
|
const idx = STATUS_ORDER.indexOf(current as any);
|
||||||
|
return STATUS_ORDER[(idx + 1) % STATUS_ORDER.length];
|
||||||
|
}
|
||||||
|
|
||||||
|
// onClick handler for status badge:
|
||||||
|
updateCandidate.mutate({
|
||||||
|
candidateId: id,
|
||||||
|
status: cycleStatus(status),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**Candidate creation default:** New candidates default to "researching". The `createCandidateSchema` includes `status` as optional with default.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export const createCandidateSchema = z.object({
|
||||||
|
// ... existing fields ...
|
||||||
|
status: z.enum(["researching", "ordered", "arrived"]).default("researching"),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Feature 5: Weight Unit Selection
|
||||||
|
|
||||||
|
**Scope:** User preference stored in the `settings` table, applied globally across all weight displays. The database always stores grams -- unit conversion is a display-only concern handled in the client formatter.
|
||||||
|
|
||||||
|
**Integration points:**
|
||||||
|
|
||||||
|
| Layer | File | Change Type | Details |
|
||||||
|
|-------|------|-------------|---------|
|
||||||
|
| DB | `settings` table | NO SCHEMA CHANGE | Uses existing key-value `settings` table: `{ key: "weightUnit", value: "g" }` |
|
||||||
|
| Server | Settings routes | NO CHANGE | Existing `GET/PUT /api/settings/:key` handles this |
|
||||||
|
| Client | `hooks/useSettings.ts` | MODIFY | Add `useWeightUnit` convenience hook |
|
||||||
|
| Client | `lib/formatters.ts` | MODIFY | `formatWeight` accepts unit parameter |
|
||||||
|
| Client | NEW `hooks/useFormatWeight.ts` | NEW | Hook combining weight unit setting + formatter |
|
||||||
|
| Client | ALL components showing weight | MODIFY | Use new formatting approach |
|
||||||
|
| Client | `components/ItemForm.tsx` | MODIFY | Weight input label shows current unit, converts on submit |
|
||||||
|
| Client | `components/CandidateForm.tsx` | MODIFY | Same as ItemForm |
|
||||||
|
| Client | NEW `components/UnitSelector.tsx` | NEW | Unit picker UI (segmented control or dropdown) |
|
||||||
|
|
||||||
|
**Settings approach -- why not a new table:**
|
||||||
|
|
||||||
|
The `settings` table already exists with a `key/value` pattern, and `useSettings.ts` already has `useSetting(key)` and `useUpdateSetting`. Adding weight unit is:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// In useSettings.ts
|
||||||
|
export function useWeightUnit() {
|
||||||
|
return useSetting("weightUnit"); // Returns "g" | "oz" | "lb" | "kg" or null (default to "g")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Conversion constants:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const GRAMS_PER_UNIT = {
|
||||||
|
g: 1,
|
||||||
|
oz: 28.3495,
|
||||||
|
lb: 453.592,
|
||||||
|
kg: 1000,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
type WeightUnit = keyof typeof GRAMS_PER_UNIT;
|
||||||
|
```
|
||||||
|
|
||||||
|
**Modified formatWeight:**
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export function formatWeight(
|
||||||
|
grams: number | null | undefined,
|
||||||
|
unit: WeightUnit = "g",
|
||||||
|
): string {
|
||||||
|
if (grams == null) return "--";
|
||||||
|
const converted = grams / GRAMS_PER_UNIT[unit];
|
||||||
|
const decimals = unit === "g" ? 0 : unit === "kg" ? 2 : 1;
|
||||||
|
return `${converted.toFixed(decimals)} ${unit}`;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Threading unit through components -- custom hook approach:**
|
||||||
|
|
||||||
|
Create a `useFormatWeight()` hook. Components call it to get a unit-aware formatter. No React Context needed -- `useSetting()` already provides reactive data through React Query.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// hooks/useFormatWeight.ts
|
||||||
|
import { useSetting } from "./useSettings";
|
||||||
|
import { formatWeight as rawFormat, type WeightUnit } from "../lib/formatters";
|
||||||
|
|
||||||
|
export function useFormatWeight() {
|
||||||
|
const { data: unitSetting } = useSetting("weightUnit");
|
||||||
|
const unit = (unitSetting ?? "g") as WeightUnit;
|
||||||
|
|
||||||
|
return {
|
||||||
|
unit,
|
||||||
|
formatWeight: (grams: number | null | undefined) => rawFormat(grams, unit),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Components that display weight (ItemCard, CandidateCard, CategoryHeader, TotalsBar, SetupDetailPage) call `const { formatWeight } = useFormatWeight()` instead of importing `formatWeight` directly from `lib/formatters.ts`. This is 6-8 call sites to update.
|
||||||
|
|
||||||
|
**Weight input handling:** When the user enters weight in the form, the input accepts the selected unit and converts to grams before sending to the API. The label changes from "Weight (g)" to "Weight (oz)" etc.
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// In ItemForm, the label reads from the hook
|
||||||
|
const { unit } = useFormatWeight();
|
||||||
|
// Label: `Weight (${unit})`
|
||||||
|
|
||||||
|
// On submit, before payload construction:
|
||||||
|
const weightGrams = form.weightValue
|
||||||
|
? Number(form.weightValue) * GRAMS_PER_UNIT[unit]
|
||||||
|
: undefined;
|
||||||
|
```
|
||||||
|
|
||||||
|
**When editing an existing item**, the form pre-fills by converting stored grams back to the display unit:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
const displayWeight = item.weightGrams != null
|
||||||
|
? (item.weightGrams / GRAMS_PER_UNIT[unit]).toFixed(unit === "g" ? 0 : unit === "kg" ? 2 : 1)
|
||||||
|
: "";
|
||||||
|
```
|
||||||
|
|
||||||
|
**Unit selector placement:** In the TotalsBar component. The user sees the unit right where weights are displayed and can switch inline. A small segmented control or dropdown next to the weight display in the top bar.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## New vs Modified Files -- Complete Inventory
|
||||||
|
|
||||||
|
### New Files (5)
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `src/client/components/SearchBar.tsx` | Reusable search input with clear button |
|
||||||
|
| `src/client/components/WeightChart.tsx` | Donut chart wrapper around react-minimal-pie-chart |
|
||||||
|
| `src/client/components/UnitSelector.tsx` | Weight unit segmented control / dropdown |
|
||||||
|
| `src/client/hooks/useFormatWeight.ts` | Hook combining weight unit setting + formatter |
|
||||||
|
| `src/db/migrations/XXXX_v1.2_columns.sql` | Drizzle migration for new columns |
|
||||||
|
|
||||||
|
### Modified Files (15)
|
||||||
|
|
||||||
|
| File | What Changes |
|
||||||
|
|------|-------------|
|
||||||
|
| `package.json` | Add `react-minimal-pie-chart` dependency |
|
||||||
|
| `src/db/schema.ts` | Add `weightClass` to setup_items, `status` to thread_candidates |
|
||||||
|
| `src/shared/schemas.ts` | Add `status` to candidate schemas, update sync schema |
|
||||||
|
| `src/server/services/setup.service.ts` | Return `weightClass`, add `updateSetupItemClass`, update `syncSetupItems` |
|
||||||
|
| `src/server/services/thread.service.ts` | Include `status` in candidate create/update |
|
||||||
|
| `src/server/routes/setups.ts` | Add `PATCH /:id/items/:itemId` for classification |
|
||||||
|
| `src/client/lib/formatters.ts` | `formatWeight` accepts unit param, add conversion constants |
|
||||||
|
| `src/client/hooks/useSetups.ts` | `SetupItemWithCategory` adds `weightClass`, update sync mutation, add classification mutation |
|
||||||
|
| `src/client/hooks/useThreads.ts` | `CandidateWithCategory` adds `status` field |
|
||||||
|
| `src/client/hooks/useSettings.ts` | Add `useWeightUnit` convenience export |
|
||||||
|
| `src/client/routes/collection/index.tsx` | Add SearchBar + category filter to gear tab, add weight chart |
|
||||||
|
| `src/client/routes/setups/$setupId.tsx` | Classification toggles per item, classification chart, updated totals |
|
||||||
|
| `src/client/components/ItemCard.tsx` | Optional `weightClass` badge in setup context |
|
||||||
|
| `src/client/components/CandidateCard.tsx` | Status badge + click-to-cycle behavior |
|
||||||
|
| `tests/helpers/db.ts` | Add `weight_class` and `status` columns to CREATE TABLE statements |
|
||||||
|
|
||||||
|
### Unchanged Files
|
||||||
|
|
||||||
|
| File | Why No Change |
|
||||||
|
|------|-------------|
|
||||||
|
| `src/client/lib/api.ts` | Existing fetch wrappers handle all new API shapes |
|
||||||
|
| `src/client/stores/uiStore.ts` | No new panel/dialog state needed |
|
||||||
|
| `src/server/routes/items.ts` | Search is client-side |
|
||||||
|
| `src/server/services/item.service.ts` | No query changes needed |
|
||||||
|
| `src/server/services/totals.service.ts` | Category totals unchanged; classification totals computed client-side |
|
||||||
|
| `src/server/routes/totals.ts` | No new endpoints |
|
||||||
|
| `src/server/index.ts` | No new route registrations (setups routes already registered) |
|
||||||
|
|
||||||
|
## Build Order (Dependency-Aware)
|
||||||
|
|
||||||
|
The features have specific dependencies that dictate build order.
|
||||||
|
|
||||||
|
```
|
||||||
|
Phase 1: Weight Unit Selection
|
||||||
|
+-- Modifies formatWeight which is used everywhere
|
||||||
|
+-- Must be done first so subsequent weight displays use the new formatter
|
||||||
|
+-- Dependencies: none (uses existing settings infrastructure)
|
||||||
|
|
||||||
|
Phase 2: Search/Filter
|
||||||
|
+-- Pure client-side addition, no schema changes
|
||||||
|
+-- Can be built independently
|
||||||
|
+-- Dependencies: none
|
||||||
|
|
||||||
|
Phase 3: Candidate Status Tracking
|
||||||
|
+-- Schema migration (simple column add)
|
||||||
|
+-- Minimal integration surface
|
||||||
|
+-- Dependencies: none (but batch schema migration with Phase 4)
|
||||||
|
|
||||||
|
Phase 4: Weight Classification
|
||||||
|
+-- Schema migration + sync API change + new PATCH endpoint
|
||||||
|
+-- Requires weight unit work to be done (displays classification totals)
|
||||||
|
+-- Dependencies: Phase 1 (weight formatting)
|
||||||
|
|
||||||
|
Phase 5: Weight Distribution Charts
|
||||||
|
+-- Depends on weight classification (for setup breakdown chart)
|
||||||
|
+-- Depends on weight unit (chart labels need formatted weights)
|
||||||
|
+-- Dependencies: Phase 1 + Phase 4
|
||||||
|
+-- npm dependency: react-minimal-pie-chart
|
||||||
|
```
|
||||||
|
|
||||||
|
**Batch Phase 3 and Phase 4 schema migrations into one Drizzle migration** since they both add columns. Run `bun run db:generate` once after both schema changes are made.
|
||||||
|
|
||||||
|
## Data Flow Changes Summary
|
||||||
|
|
||||||
|
### Current Data Flows (unchanged)
|
||||||
|
|
||||||
|
```
|
||||||
|
useItems() -> GET /api/items -> getAllItems(db) -> items JOIN categories
|
||||||
|
useThreads() -> GET /api/threads -> getAllThreads(db) -> threads JOIN categories
|
||||||
|
useSetups() -> GET /api/setups -> getAllSetups(db) -> setups + subqueries
|
||||||
|
useTotals() -> GET /api/totals -> getCategoryTotals -> items GROUP BY categoryId
|
||||||
|
```
|
||||||
|
|
||||||
|
### New/Modified Data Flows
|
||||||
|
|
||||||
|
```
|
||||||
|
Search/Filter:
|
||||||
|
CollectionView local state (searchTerm, categoryFilter)
|
||||||
|
-> useMemo over useItems().data
|
||||||
|
-> no API change
|
||||||
|
|
||||||
|
Weight Unit:
|
||||||
|
useFormatWeight() -> useSetting("weightUnit") -> GET /api/settings/weightUnit
|
||||||
|
-> formatWeight(grams, unit) -> display string
|
||||||
|
|
||||||
|
Candidate Status:
|
||||||
|
CandidateCard click -> useUpdateCandidate({ status: "ordered" })
|
||||||
|
-> PUT /api/threads/:id/candidates/:cid -> updateCandidate(db, cid, { status })
|
||||||
|
|
||||||
|
Weight Classification:
|
||||||
|
Setup detail -> getSetupWithItems now returns weightClass per item
|
||||||
|
-> client groups by weightClass for totals
|
||||||
|
-> PATCH /api/setups/:id/items/:itemId updates classification
|
||||||
|
|
||||||
|
Weight Chart:
|
||||||
|
Collection: useTotals().data.categories -> WeightChart segments
|
||||||
|
Setup: setup.items grouped by weightClass -> WeightChart segments
|
||||||
|
```
|
||||||
|
|
||||||
|
## Anti-Patterns to Avoid
|
||||||
|
|
||||||
|
### Anti-Pattern 1: Server-Side Search for Small Collections
|
||||||
|
|
||||||
|
**What people do:** Build a search API with pagination, debounced requests, loading states
|
||||||
|
**Why it's wrong for this app:** Single-user app with <1000 items. Server round-trips add latency and complexity for zero benefit. Client already has all items in React Query cache.
|
||||||
|
**Do this instead:** Filter in-memory using `useMemo` over the cached items array.
|
||||||
|
|
||||||
|
### Anti-Pattern 2: Weight Classification on the Items Table
|
||||||
|
|
||||||
|
**What people do:** Add `weightClass` column to `items` table
|
||||||
|
**Why it's wrong:** An item's classification is context-dependent -- the same item can be "base" in one setup and not present in another. Putting it on `items` forces a single global classification.
|
||||||
|
**Do this instead:** Put `weightClass` on `setup_items` join table. This is how LighterPack and every serious gear tracker works.
|
||||||
|
|
||||||
|
### Anti-Pattern 3: Converting Stored Values to User's Unit
|
||||||
|
|
||||||
|
**What people do:** Store weights in the user's preferred unit, or convert on the server before sending
|
||||||
|
**Why it's wrong:** Changing the unit preference would require re-interpreting all stored data. Different users (future multi-user) might prefer different units from the same data.
|
||||||
|
**Do this instead:** Always store grams in the database. Convert to display unit only in the client formatter. The conversion is a pure function with no side effects.
|
||||||
|
|
||||||
|
### Anti-Pattern 4: Heavy Charting Library for One Chart Type
|
||||||
|
|
||||||
|
**What people do:** Install Recharts (~45kB) or Chart.js (~67kB) for a single donut chart
|
||||||
|
**Why it's wrong:** Massive bundle size overhead for minimal usage. These libraries are designed for dashboards with many chart types.
|
||||||
|
**Do this instead:** Use `react-minimal-pie-chart` (<3kB) which does exactly donut/pie charts with zero dependencies.
|
||||||
|
|
||||||
|
### Anti-Pattern 5: React Context Provider for Weight Unit
|
||||||
|
|
||||||
|
**What people do:** Build a full React Context provider with `createContext`, `useContext`, a Provider wrapper component
|
||||||
|
**Why it's excessive here:** The `useSetting("weightUnit")` hook already provides reactive data through React Query. Adding a Context layer on top adds indirection for no benefit.
|
||||||
|
**Do this instead:** Create a simple custom hook `useFormatWeight()` that internally calls `useSetting("weightUnit")`. React Query already handles caching and reactivity.
|
||||||
|
|
||||||
## Sources
|
## Sources
|
||||||
|
|
||||||
- [Bun Fullstack Dev Server docs](https://bun.com/docs/bundler/fullstack) -- Official documentation on Bun's HTML-based routing and asset bundling
|
- [Drizzle ORM Filters Documentation](https://orm.drizzle.team/docs/operators) -- like, and, or operators for SQLite
|
||||||
- [bun:sqlite API Reference](https://bun.com/reference/bun/sqlite) -- Native SQLite module documentation
|
- [Drizzle ORM Conditional Filters Guide](https://orm.drizzle.team/docs/guides/conditional-filters-in-query) -- dynamic filter patterns
|
||||||
- [Building Full-Stack App with Bun.js, React and Drizzle ORM](https://awplife.com/building-full-stack-app-with-bun-js-react-drizzle/) -- Project structure reference
|
- [SQLite LIKE case sensitivity with Drizzle](https://github.com/drizzle-team/drizzle-orm-docs/issues/239) -- SQLite LIKE is case-insensitive for ASCII
|
||||||
- [Bun v3.1 Release (InfoQ)](https://www.infoq.com/news/2026/01/bun-v3-1-release/) -- Zero-config frontend, built-in DB clients
|
- [react-minimal-pie-chart npm](https://www.npmjs.com/package/react-minimal-pie-chart) -- lightweight pie/donut chart, <3kB gzipped
|
||||||
- [Bun + React + Hono pattern](https://dev.to/falconz/serving-a-react-app-and-hono-api-together-with-bun-1gfg) -- Alternative fullstack patterns
|
- [react-minimal-pie-chart GitHub](https://github.com/toomuchdesign/react-minimal-pie-chart) -- API docs and examples
|
||||||
- [Inventory Management DB Design (Medium)](https://medium.com/@bhargavkoya56/weekly-db-project-1-inventory-management-db-design-seed-from-schema-design-to-performance-8e6b56445fe6) -- Schema design patterns for inventory systems
|
- [LighterPack Tutorial - 99Boulders](https://www.99boulders.com/lighterpack-tutorial) -- base/worn/consumable weight classification standard
|
||||||
|
- [Pack Weight Categories](https://hikertimes.com/difference-between-base-weight-and-total-weight/) -- base weight vs total weight definitions
|
||||||
|
- [Pack Weight Calculator](https://backpackpeek.com/blog/pack-weight-calculator-base-weight-guide) -- weight classification guide
|
||||||
|
|
||||||
---
|
---
|
||||||
*Architecture research for: GearBox gear management app*
|
*Architecture research for: GearBox v1.2 Collection Power-Ups*
|
||||||
*Researched: 2026-03-14*
|
*Researched: 2026-03-16*
|
||||||
|
|||||||
@@ -1,201 +1,244 @@
|
|||||||
# Feature Research
|
# Feature Research: v1.2 Collection Power-Ups
|
||||||
|
|
||||||
**Domain:** Gear management and purchase planning (personal inventory + research workflow)
|
**Domain:** Gear management -- search/filter, weight classification, weight visualization, candidate status tracking, weight unit selection
|
||||||
**Researched:** 2026-03-14
|
**Researched:** 2026-03-16
|
||||||
**Confidence:** HIGH
|
**Confidence:** HIGH
|
||||||
|
**Scope:** New features only. v1.0/v1.1 features (item CRUD, categories, threads, setups, dashboard, onboarding, images, icons) are already shipped.
|
||||||
|
|
||||||
## Feature Landscape
|
## Table Stakes
|
||||||
|
|
||||||
### Table Stakes (Users Expect These)
|
Features that gear management users expect. Missing these makes the app feel incomplete for collections beyond ~20 items.
|
||||||
|
|
||||||
Features users assume exist. Missing these = product feels incomplete.
|
| Feature | Why Expected | Complexity | Dependencies on Existing |
|
||||||
|
|---------|--------------|------------|--------------------------|
|
||||||
|
| Search items by name | Every competitor with an inventory concept has search. Hikt highlights "searchable digital closet." PackLight Supporter Edition has inventory search. Once a collection exceeds 30 items, scrolling to find something is painful. LighterPack notably lacks this and users complain. | LOW | Items query (`useItems`), collection view. Client-side only -- no API changes needed for <500 items. |
|
||||||
|
| Filter items by category | Already partially exists in Planning view (category dropdown for threads). Collection view groups by category visually but has no filter. Users need to quickly narrow to "show me just my shelter items." | LOW | Categories query (`useCategories`), collection view. Client-side filtering of already-fetched items. |
|
||||||
|
| Weight unit selection (g, oz, lb, kg) | Universal across all competitors. LighterPack supports toggling between g/oz/lb/kg. Packrat offers per-item input in any unit with display conversion. Backpacking Light forum users specifically praise apps that let you "enter item weights in grams and switch the entire display to lbs & oz." Gear specs come in mixed units -- a sleeping bag in lbs/oz, a fuel canister in grams. | LOW | `formatWeight()` in `lib/formatters.ts`, `settings` table (already exists with key/value store), TotalsBar, ItemCard, CandidateCard, SetupCard -- every weight display. |
|
||||||
|
| Weight classification (base/worn/consumable) | LighterPack pioneered this three-way split and it is now universal. Hikt, PackLight, Packstack, HikeLite, 99Boulders spreadsheet -- all support it. "Base weight" is the core metric of the ultralight community. Without classification, weight totals are a single number with no actionable insight. | MEDIUM | `setup_items` join table (needs new column), setup detail view, setup service, totals computation. Schema migration required. |
|
||||||
|
|
||||||
| Feature | Why Expected | Complexity | Notes |
|
## Differentiators
|
||||||
|---------|--------------|------------|-------|
|
|
||||||
| Item CRUD with core fields (name, weight, price, category) | Every gear app and spreadsheet has this. It is the minimum unit of value. | LOW | Weight and price are the two fields users care about most. Category groups items visually. |
|
|
||||||
| Weight unit support (g, oz, lb, kg) | Gear communities are split between metric and imperial. LighterPack, GearGrams, Hikt all support multi-unit. | LOW | Store in grams internally, display in user-preferred unit. Conversion is trivial. |
|
|
||||||
| Automatic weight/cost totals | Spreadsheets do this. Every competitor does this. Manual math = why bother with an app. | LOW | Sum by category, by setup, by collection. Real-time recalculation on any change. |
|
|
||||||
| Categories/grouping | LighterPack, GearGrams, Packstack all organize by category (shelter, sleep, cook, clothing, etc.). Without grouping, lists become unreadable past 20 items. | LOW | User-defined categories. Suggest defaults but allow custom. |
|
|
||||||
| Named setups / packing lists | LighterPack has lists, GearGrams has lists, Packstack has trips, Hikt has packing lists. Composing subsets of your gear into purpose-specific loadouts is universal. | MEDIUM | Items belong to collection; setups reference items from collection. Many-to-many relationship. |
|
|
||||||
| Setup weight/cost breakdown | Every competitor shows base weight, worn weight, consumable weight as separate totals. Pie charts or percentage breakdowns by category are standard (LighterPack pioneered this). | MEDIUM | Weight classification (base/worn/consumable) per item per setup. Visual breakdown is expected. |
|
|
||||||
| Notes/description per item | Spreadsheet users write notes. Every competitor supports free text on items. Useful for fit notes, durability observations, model year specifics. | LOW | Plain text field. No rich text needed for v1. |
|
|
||||||
| Product links / URLs | Users track where they found or bought items. Spreadsheets always have a "link" column. | LOW | Single URL field per item. |
|
|
||||||
| Photos per item | Hikt, GearCloset, and Packrat all support item photos. Visual identification matters -- many gear items look similar in text. | MEDIUM | Image upload and storage. Start with one photo per item; multi-photo is a differentiator. |
|
|
||||||
| Search and filter | Once a collection exceeds 30-40 items, finding things without search is painful. Hikt highlights "searchable digital closet." | LOW | Filter by category, search by name. Basic but essential. |
|
|
||||||
| Import from CSV | GearGrams, HikeLite, HikerHerd, Packrat all support CSV import. Users migrating from spreadsheets (GearBox's primary audience) need this. | MEDIUM | Define a simple CSV schema. Map columns to fields. Handle unit conversion on import. |
|
|
||||||
| Export to CSV | Companion to import. Users want data portability and backup ability. | LOW | Straightforward serialization of collection data. |
|
|
||||||
|
|
||||||
### Differentiators (Competitive Advantage)
|
Features that set GearBox apart or add meaningful value beyond what competitors offer.
|
||||||
|
|
||||||
Features that set the product apart. Not required, but valuable.
|
| Feature | Value Proposition | Complexity | Dependencies on Existing |
|
||||||
|
|---------|-------------------|------------|--------------------------|
|
||||||
|
| Weight distribution visualization (donut/pie chart) | LighterPack's pie chart is iconic and widely cited as its best feature. "The pie chart at the top is a great way to visualize how your pack weight breaks down by category." PackLight uses bar graphs. GearBox can do this per-setup with a modern donut chart that also shows base/worn/consumable breakdown -- a combination no competitor offers cleanly. | MEDIUM | Totals data (already computed server-side per category), weight classification (new), a chart library (react-minimal-pie-chart at 2kB or Recharts). |
|
||||||
|
| Candidate status tracking (researching/ordered/arrived) | No competitor has this. Research confirmed: the specific workflow of tracking purchase status through stages does not exist in any gear management app. This is unique to GearBox's planning thread concept. It makes threads a living document of the purchase lifecycle, not just a comparison tool. | LOW | `thread_candidates` table (needs new `status` column), CandidateCard, CandidateForm. Simple text field migration. |
|
||||||
|
| Planning category filter with icon-aware dropdown | Already partially built as a plain `<select>` in PlanningView. Upgrading to show Lucide icons alongside category names makes filtering feel polished and consistent with the icon picker UX. | LOW | Existing CategoryPicker component pattern, existing category filter state in PlanningView. |
|
||||||
|
| Weight classification shown per-setup (not global) | In LighterPack, worn/consumable flags are per-item within a list. In GearBox, items exist in a global collection and appear in multiple setups. The same jacket might be "worn" in a summer bikepacking setup but "base weight" (packed in panniers) in a winter setup. Classification belongs on the setup_items join, not on the item itself. This is architecturally superior to competitors. | MEDIUM | `setup_items` table schema, setup sync endpoint, setup detail UI. |
|
||||||
|
|
||||||
| Feature | Value Proposition | Complexity | Notes |
|
## Anti-Features
|
||||||
|---------|-------------------|------------|-------|
|
|
||||||
| Purchase planning threads | No competitor has this. LighterPack, GearGrams, Packstack, Hikt are all post-purchase tools. GearBox's core value is the pre-purchase research workflow: create a thread, add candidates, compare, decide, then move the winner to your collection. This is the single biggest differentiator. | HIGH | Thread model with candidate items, status tracking, resolution workflow. This is the app's reason to exist. |
|
|
||||||
| Impact preview ("how does this affect my setup?") | No competitor shows how a potential purchase changes your overall setup weight/cost. Users currently do this math manually in spreadsheets. Seeing "+120g to base weight, +$85 to total cost" before buying is uniquely valuable. | MEDIUM | Requires linking threads to setups. Calculate delta between current item (if replacing) and candidate. |
|
|
||||||
| Thread resolution workflow | The lifecycle of "researching -> ordered -> arrived -> in collection" does not exist in any competitor. Closing a thread and promoting the winner to your collection is a novel workflow that mirrors how people actually buy gear. | MEDIUM | Status state machine on thread items. Resolution action that creates/updates collection item. |
|
|
||||||
| Side-by-side candidate comparison | Wishlist apps let you save items. GearBox lets you compare candidates within a thread on the dimensions that matter (weight, price, notes). Similar to product comparison on retail sites, but for your specific context. | MEDIUM | Comparison view pulling from thread candidates. Highlight differences in weight/price. |
|
|
||||||
| Priority/ranking within threads | Mark favorites among candidates. Simple but no gear app does this because no gear app has a research/planning concept. | LOW | Numeric rank or star/favorite flag per candidate in a thread. |
|
|
||||||
| Multi-photo per item | Most competitors support zero or one photo. Multiple photos (product shots, detail shots, in-use shots) add real value for gear tracking. | MEDIUM | Gallery per item. Storage considerations. Defer to v1.x. |
|
|
||||||
| Weight distribution visualization | LighterPack's pie chart is iconic. A clean, modern version with interactive breakdowns by category adds polish. | MEDIUM | Chart component showing percentage of total weight by category. |
|
|
||||||
| Hobby-agnostic data model | Competitors are hiking/backpacking-specific. GearBox works for bikepacking, sim racing, photography, cycling, or any collection hobby. The data model uses generic "categories" rather than hardcoded "shelter/sleep/cook." | LOW | Architecture decision more than feature. No hiking-specific terminology baked into the model. |
|
|
||||||
|
|
||||||
### Anti-Features (Commonly Requested, Often Problematic)
|
Features to explicitly NOT build in this milestone.
|
||||||
|
|
||||||
Features that seem good but create problems.
|
| Anti-Feature | Why Avoid | What to Do Instead |
|
||||||
|
|--------------|-----------|-------------------|
|
||||||
|
| Per-item weight input in multiple units | Packrat lets you enter "2 lb 3 oz" per item. This adds parsing complexity, ambiguous storage, and conversion bugs. | Store grams internally (already done). Convert for display only. Users enter grams; if they want oz input, they convert mentally or we add a unit toggle on the input field later. |
|
||||||
|
| Interactive chart drill-down (click to zoom) | LighterPack lets you click pie slices to zoom into category breakdowns. Adds significant interaction complexity. | Static donut chart with hover tooltips. Drill-down is a future enhancement. |
|
||||||
|
| Weight goals / targets ("your target base weight is X") | Some apps show ultralight thresholds. Adds opinionated norms that conflict with hobby-agnostic design. | Show the numbers. Let users interpret them. |
|
||||||
|
| Custom weight classification labels | Beyond base/worn/consumable. Some users want "luxury" or "shared" categories. | Three classifications cover 95% of use cases. The notes field handles edge cases. |
|
||||||
|
| Server-side search / full-text search | SQLite FTS5 or similar. Premature for a single-user app with <1000 items. | Client-side filtering of the already-fetched items array. Simpler, faster for the expected data scale. |
|
||||||
|
| Worn/consumable at the global item level | Tempting to add a classification column to the `items` table. | Classification varies by setup context. A rain shell is "worn" on a day hike but "base weight" (packed) on a bike tour. The join table `setup_items` is the correct location. |
|
||||||
|
|
||||||
| Feature | Why Requested | Why Problematic | Alternative |
|
## Feature Details
|
||||||
|---------|---------------|-----------------|-------------|
|
|
||||||
| Multi-user / social sharing | "Share my setup with friends," "collaborate on packing lists." Hikt Premium has real-time collaboration. | Adds auth, permissions, data isolation, and massive complexity to a single-user app. The PROJECT.md explicitly scopes this out. Premature for v1. | Export/share as read-only link or image in a future version. No auth needed. |
|
### 1. Search and Filter
|
||||||
| Price tracking / deal alerts | Wishlist apps (Sortd, WishUpon) track price drops. Seems useful for purchase planning. | Requires scraping or API integrations with retailers. Fragile, maintenance-heavy, legally gray. Completely different product category. | Store the price you found manually. Link to the product page. Users can check prices themselves. |
|
|
||||||
| Barcode/product database scanning | Hikt has barcode scanning and product database lookup. Seems like it saves time. | Requires maintaining or licensing a product database. Outdoor gear barcodes are inconsistent. Mobile-first feature that does not fit a web-first app. | Manual entry is fine for a collection that grows by 1-5 items per month. Not a data-entry-heavy workflow. |
|
**What users expect:** A text input that filters visible items by name as you type. A category dropdown or pill selector to filter by category. Both should work together (search within a category).
|
||||||
| Custom comparison parameters | "Let me define which fields to compare (warmth rating, denier, waterproof rating)." | Turns a simple app into a configurable schema builder. Massive complexity for marginal value. PROJECT.md lists this as out of scope for v1. | Use the notes field for specs. Fixed comparison on weight/price covers 80% of use cases. |
|
|
||||||
| Community gear database / shared catalog | "Browse what other people use," "copy someone's gear list." Hikt has community packing lists. | Requires moderation, data quality controls, user accounts, and content management. Completely different product. | Stay focused on personal inventory. Community features are a different app. |
|
**Domain patterns observed:**
|
||||||
| Mobile native app | PackLight and Hikt have iOS/Android apps. | Doubles or triples development effort. Web-first serves the use case (gear management is a desk activity, not a trailside activity). PROJECT.md scopes this out. | Responsive web design. Works on mobile browsers for quick lookups. |
|
- Hikt: Searchable gear closet with category and specification filters
|
||||||
| Real-time weather integration | Packstack integrates weather for trip planning. | Requires external API, ongoing costs, and is only relevant to outdoor-specific use cases. GearBox is hobby-agnostic. | Out of scope. Users check weather separately. |
|
- PackLight: Inventory search (premium feature) with category organization
|
||||||
| Automated "what to bring" recommendations | AI/rule-based suggestions based on trip conditions. | Requires domain knowledge per hobby, weather data, user preference modeling. Over-engineered for a personal tool. | Users build their own setups. They know their gear. |
|
- Backpacking Light Calculator: Search filter in gear locker and within packs
|
||||||
|
- LighterPack: No text search -- widely considered a gap
|
||||||
|
|
||||||
|
**Recommended implementation:**
|
||||||
|
- Sticky search bar above the collection grid with a text input and category filter dropdown
|
||||||
|
- Client-side filtering using `Array.filter()` on the items array from `useItems()`
|
||||||
|
- Case-insensitive substring match on item name
|
||||||
|
- Category filter as pills or dropdown (reuse the pattern from PlanningView)
|
||||||
|
- URL search params for filter state (shareable filtered views, consistent with existing `?tab=` pattern)
|
||||||
|
- Clear filters button when any filter is active
|
||||||
|
- Result count displayed ("showing 12 of 47 items")
|
||||||
|
|
||||||
|
**Complexity:** LOW. Pure client-side. No API changes. ~100 lines of new component code plus minor state management.
|
||||||
|
|
||||||
|
### 2. Weight Classification (Base/Worn/Consumable)
|
||||||
|
|
||||||
|
**What users expect:** Every item in a setup can be marked as one of three types:
|
||||||
|
- **Base weight**: Items carried in the pack. The fixed weight of your loadout. This is the primary metric ultralight hikers optimize.
|
||||||
|
- **Worn weight**: Items on your body while hiking (shoes, primary clothing, watch, sunglasses). Not counted toward pack weight but tracked as part of "skin-out" weight.
|
||||||
|
- **Consumable weight**: Items that deplete during a trip (food, water, fuel, sunscreen). Variable weight not counted toward base weight.
|
||||||
|
|
||||||
|
**Domain patterns observed:**
|
||||||
|
- LighterPack: Per-item icons (shirt icon = worn, flame icon = consumable). Default = base weight. Totals show base/worn/consumable/total separately.
|
||||||
|
- Packstack: "Separates base weight, worn weight, and consumables so you always know exactly what your pack weighs."
|
||||||
|
- HikeLite: "Mark heavy clothing as worn to see your true base weight."
|
||||||
|
- 99Boulders spreadsheet: Column with dropdown: WORN / CONSUMABLE / - (dash = base).
|
||||||
|
|
||||||
|
**Critical design decision -- classification scope:**
|
||||||
|
In LighterPack, items only exist within lists, so the flag is per-item-per-list inherently. In GearBox, items live in a global collection and are referenced by setups. The classification MUST live on the `setup_items` join table, not on the `items` table. Reason: the same item can have different classifications in different setups (a puffy jacket is "worn" on a cold-weather hike but "base weight" in a three-season setup where it stays packed).
|
||||||
|
|
||||||
|
**Recommended implementation:**
|
||||||
|
- Add `classification TEXT NOT NULL DEFAULT 'base'` column to `setup_items` table
|
||||||
|
- Valid values: `"base"`, `"worn"`, `"consumable"`
|
||||||
|
- Default to `"base"` (most items are base weight; this matches user expectation)
|
||||||
|
- UI: Small segmented control or icon toggle on each item within the setup detail view
|
||||||
|
- LighterPack-style icons: backpack icon (base), shirt icon (worn), flame/droplet icon (consumable)
|
||||||
|
- Setup totals recalculated: show base weight, worn weight, consumable weight, and total (skin-out) as four separate numbers
|
||||||
|
- SQL aggregation update: `SUM(CASE WHEN classification = 'base' THEN weight_grams ELSE 0 END)` etc.
|
||||||
|
|
||||||
|
**Complexity:** MEDIUM. Requires schema migration, API changes (sync endpoint must accept classification), service layer updates, and UI for per-item classification within setup views.
|
||||||
|
|
||||||
|
### 3. Weight Distribution Visualization
|
||||||
|
|
||||||
|
**What users expect:** A chart showing where the weight is. By category is standard. By classification (base/worn/consumable) is a bonus.
|
||||||
|
|
||||||
|
**Domain patterns observed:**
|
||||||
|
- LighterPack: Color-coded pie chart by category, click to drill down. "As you enter each piece of equipment, a pie chart immediately displays a breakdown of where your weight is appropriated." Colors are customizable per category.
|
||||||
|
- PackLight: Bar graph comparing category weights
|
||||||
|
- OutPack: Category breakdown graph
|
||||||
|
|
||||||
|
**Two chart contexts:**
|
||||||
|
1. **Collection-level**: Weight by category across the whole collection. Uses existing `useTotals()` data.
|
||||||
|
2. **Setup-level**: Weight by category AND by classification within a specific setup. More useful because setups represent actual loadouts.
|
||||||
|
|
||||||
|
**Recommended implementation:**
|
||||||
|
- Donut chart (modern feel, consistent with GearBox's minimalist aesthetic)
|
||||||
|
- Library: `react-minimal-pie-chart` (2kB gzipped, zero dependencies, SVG-based) over Recharts (40kB+). GearBox only needs pie/donut -- no line charts, bar charts, etc.
|
||||||
|
- Setup detail view: Donut chart showing weight by category, with center text showing total base weight
|
||||||
|
- Optional toggle: switch between "by category" and "by classification" views
|
||||||
|
- Color assignment: Derive from category or classification type (base = neutral gray, worn = blue, consumable = amber)
|
||||||
|
- Hover tooltips showing category name, weight, and percentage
|
||||||
|
- Responsive: Chart should work on mobile viewports
|
||||||
|
|
||||||
|
**Complexity:** MEDIUM. New dependency, new component, integration with totals data. The chart itself is straightforward; the data aggregation for per-setup-per-category-per-classification is the main work.
|
||||||
|
|
||||||
|
### 4. Candidate Status Tracking
|
||||||
|
|
||||||
|
**What users expect:** This is novel -- no competitor has it. The workflow mirrors real purchase behavior:
|
||||||
|
1. **Researching** (default): You found this product, added it to a thread, and are evaluating it
|
||||||
|
2. **Ordered**: You decided to buy it and placed an order
|
||||||
|
3. **Arrived**: The product has been delivered. Ready for thread resolution.
|
||||||
|
|
||||||
|
**Why this matters:** Without status tracking, threads are a flat list of candidates. With it, threads become a living purchase tracker. A user can see at a glance "I ordered the Nemo Tensor, still researching two other pads."
|
||||||
|
|
||||||
|
**Recommended implementation:**
|
||||||
|
- Add `status TEXT NOT NULL DEFAULT 'researching'` column to `thread_candidates` table
|
||||||
|
- Valid values: `"researching"`, `"ordered"`, `"arrived"`
|
||||||
|
- UI: Status badge on CandidateCard (small colored pill, similar to existing weight/price badges)
|
||||||
|
- Color scheme: researching = gray/neutral, ordered = amber/yellow, arrived = green
|
||||||
|
- Status change: Dropdown or simple click-to-cycle on the candidate card
|
||||||
|
- Thread-level summary: Show count by status ("2 researching, 1 ordered")
|
||||||
|
- When resolving a thread, only candidates with status "arrived" should be selectable as winners (soft constraint -- show a warning, not a hard block, since users may resolve with a "researching" candidate they just bought in-store)
|
||||||
|
|
||||||
|
**Complexity:** LOW. Simple column addition, enum-like text field, badge rendering, optional status transition UI.
|
||||||
|
|
||||||
|
### 5. Weight Unit Selection
|
||||||
|
|
||||||
|
**What users expect:** Choose a preferred unit (grams, ounces, pounds, kilograms) and have ALL weight displays in the app use that unit. LighterPack toggles between g/oz/lb/kg at the top level. The BPL Calculator app lets you "enter item weights in grams and switch the entire display to lbs & oz."
|
||||||
|
|
||||||
|
**Domain patterns observed:**
|
||||||
|
- LighterPack: Toggle at list level between lb/oz/g/kg. Only changes summary display, not per-item display.
|
||||||
|
- Packrat: "Input items in different units, choose how they're displayed, and freely convert between them."
|
||||||
|
- BPL Calculator: Global settings change, applied to all displays
|
||||||
|
- WeighMyGear: Input locked to grams, less intuitive
|
||||||
|
|
||||||
|
**Recommended implementation:**
|
||||||
|
- Store preference in existing `settings` table as `{ key: "weightUnit", value: "g" }` (default: grams)
|
||||||
|
- Supported units: `g` (grams), `oz` (ounces), `lb` (pounds + ounces), `kg` (kilograms)
|
||||||
|
- Conversion constants: 1 oz = 28.3495g, 1 lb = 453.592g, 1 kg = 1000g
|
||||||
|
- Display format per unit:
|
||||||
|
- `g`: "450g" (round to integer)
|
||||||
|
- `oz`: "15.9 oz" (one decimal)
|
||||||
|
- `lb`: "2 lb 3 oz" (pounds + remainder ounces, traditional format)
|
||||||
|
- `kg`: "1.45 kg" (two decimals)
|
||||||
|
- Update `formatWeight()` to accept unit parameter or read from a React context/hook
|
||||||
|
- Settings UI: Simple dropdown or segmented control, accessible from a settings page or inline in the TotalsBar
|
||||||
|
- Internal storage stays as grams (already the case with `weight_grams` column)
|
||||||
|
- Affects: TotalsBar, ItemCard, CandidateCard, SetupCard, CategoryHeader, setup detail view, chart tooltips
|
||||||
|
|
||||||
|
**Complexity:** LOW. No schema changes. Update the `formatWeight()` function, add a settings hook, propagate the unit to all display points. The main effort is touching every component that displays weight (there are ~6-8 call sites).
|
||||||
|
|
||||||
|
### 6. Planning Category Filter with Icon-Aware Dropdown
|
||||||
|
|
||||||
|
**What users expect:** The existing category filter in PlanningView is a plain `<select>` without icons. Since categories now have Lucide icons (v1.1), the filter should show them.
|
||||||
|
|
||||||
|
**Recommended implementation:**
|
||||||
|
- Replace the native `<select>` with a custom dropdown component that renders `<LucideIcon>` alongside category names
|
||||||
|
- Match the visual style of the CategoryPicker used in thread creation
|
||||||
|
- Same functionality, better visual consistency
|
||||||
|
|
||||||
|
**Complexity:** LOW. UI-only change. Replace ~20 lines of `<select>` with a custom dropdown component.
|
||||||
|
|
||||||
## Feature Dependencies
|
## Feature Dependencies
|
||||||
|
|
||||||
```
|
```
|
||||||
[Item CRUD + Core Fields]
|
[Weight Unit Selection] --independent-- (affects all displays, no schema changes)
|
||||||
|
|
|
|
||||||
+--requires--> [Categories]
|
+-- should ship first (all other features benefit from correct unit display)
|
||||||
|
|
|
||||||
+--enables---> [Named Setups / Packing Lists]
|
|
||||||
| |
|
|
||||||
| +--enables---> [Setup Weight/Cost Breakdown]
|
|
||||||
| |
|
|
||||||
| +--enables---> [Impact Preview] (also requires Planning Threads)
|
|
||||||
|
|
|
||||||
+--enables---> [Planning Threads]
|
|
||||||
|
|
|
||||||
+--enables---> [Candidate Comparison]
|
|
||||||
|
|
|
||||||
+--enables---> [Thread Resolution Workflow]
|
|
||||||
| |
|
|
||||||
| +--creates---> items in [Collection]
|
|
||||||
|
|
|
||||||
+--enables---> [Priority/Ranking]
|
|
||||||
|
|
|
||||||
+--enables---> [Status Tracking] (researching -> ordered -> arrived)
|
|
||||||
|
|
||||||
[Search & Filter] --enhances--> [Item CRUD] (becomes essential at ~30+ items)
|
[Search & Filter] --independent-- (pure client-side, no schema changes)
|
||||||
|
|
|
||||||
|
+-- no dependencies on other v1.2 features
|
||||||
|
|
||||||
[Import CSV] --populates--> [Item CRUD] (bootstrap for spreadsheet migrants)
|
[Candidate Status Tracking] --independent-- (schema change on thread_candidates only)
|
||||||
|
|
|
||||||
|
+-- no dependencies on other v1.2 features
|
||||||
|
|
||||||
[Photos] --enhances--> [Item CRUD] (independent, can add anytime)
|
[Weight Classification] --depends-on--> [existing setup_items table]
|
||||||
|
|
|
||||||
|
+-- schema migration on setup_items
|
||||||
|
+-- enables [Weight Distribution Visualization]
|
||||||
|
|
||||||
[Weight Unit Support] --enhances--> [All weight displays] (must be in from day one)
|
[Weight Distribution Visualization] --depends-on--> [Weight Classification]
|
||||||
|
|
|
||||||
|
+-- needs classification data to show base/worn/consumable breakdown
|
||||||
|
+-- can show by-category chart without classification (partial value)
|
||||||
|
+-- new dependency: react-minimal-pie-chart
|
||||||
|
|
||||||
|
[Planning Category Filter Icons] --depends-on--> [existing CategoryPicker pattern]
|
||||||
|
|
|
||||||
|
+-- pure UI enhancement
|
||||||
```
|
```
|
||||||
|
|
||||||
### Dependency Notes
|
### Implementation Order Rationale
|
||||||
|
|
||||||
- **Named Setups require Item CRUD:** Setups are compositions of existing collection items. The collection must exist first.
|
1. **Weight Unit Selection** first -- touches formatting everywhere, foundational for all subsequent weight displays
|
||||||
- **Planning Threads require Item CRUD:** Thread candidates have the same data shape as collection items (weight, price, etc.). Reuse the item model.
|
2. **Search & Filter** second -- standalone, immediately useful, low risk
|
||||||
- **Impact Preview requires both Setups and Threads:** You need a setup to compare against and a thread candidate to evaluate. This is a later-phase feature.
|
3. **Candidate Status Tracking** third -- standalone schema change, simple
|
||||||
- **Thread Resolution creates Collection Items:** The resolution workflow bridges threads and collection. Both must be stable before resolution logic is built.
|
4. **Planning Category Filter** fourth -- quick UI polish
|
||||||
- **Import CSV populates Collection:** Import is a bootstrap feature for users migrating from spreadsheets. Should be available early but after the core item model is solid.
|
5. **Weight Classification** fifth -- most complex schema change, affects setup data model
|
||||||
|
6. **Weight Distribution Visualization** last -- depends on classification, needs chart library, highest UI complexity
|
||||||
|
|
||||||
## MVP Definition
|
## Complexity Summary
|
||||||
|
|
||||||
### Launch With (v1)
|
| Feature | Schema Change | API Change | New Dependency | UI Scope | Overall |
|
||||||
|
|---------|---------------|------------|----------------|----------|---------|
|
||||||
Minimum viable product -- what is needed to validate the concept and replace a spreadsheet.
|
| Search & Filter | None | None | None | Collection view only | LOW |
|
||||||
|
| Weight Unit Selection | None (uses settings) | None (settings API exists) | None | All weight displays (~8 components) | LOW |
|
||||||
- [ ] Item CRUD with weight, price, category, notes, product link -- the core inventory
|
| Candidate Status Tracking | `thread_candidates.status` column | Update candidate CRUD | None | CandidateCard, CandidateForm | LOW |
|
||||||
- [ ] User-defined categories -- organize items meaningfully
|
| Planning Category Filter | None | None | None | PlanningView dropdown | LOW |
|
||||||
- [ ] Weight unit support (g, oz, lb, kg) -- non-negotiable for gear community
|
| Weight Classification | `setup_items.classification` column | Update setup sync + detail endpoints | None | Setup detail view | MEDIUM |
|
||||||
- [ ] Automatic weight/cost totals by category and overall -- the reason to use an app over a text file
|
| Weight Distribution Chart | None | Possibly new totals endpoint | react-minimal-pie-chart (~2kB) | New chart component | MEDIUM |
|
||||||
- [ ] Named setups with item selection and totals -- compose loadouts from your collection
|
|
||||||
- [ ] Planning threads with candidate items -- the core differentiator, add candidates you are researching
|
|
||||||
- [ ] Side-by-side candidate comparison on weight/price -- the payoff of the thread concept
|
|
||||||
- [ ] Thread resolution (pick a winner, move to collection) -- close the loop
|
|
||||||
- [ ] Dashboard home page -- clean entry point per PROJECT.md constraints
|
|
||||||
- [ ] Search and filter on collection -- usability at scale
|
|
||||||
|
|
||||||
### Add After Validation (v1.x)
|
|
||||||
|
|
||||||
Features to add once core is working and the planning thread workflow is proven.
|
|
||||||
|
|
||||||
- [ ] Impact preview ("this candidate adds +120g to your Summer Bikepacking setup") -- requires setups + threads to be stable
|
|
||||||
- [ ] Status tracking on thread items (researching / ordered / arrived) -- lifecycle tracking
|
|
||||||
- [ ] Priority/ranking within threads -- mark favorites among candidates
|
|
||||||
- [ ] Photos per item -- visual identification, one photo per item initially
|
|
||||||
- [ ] CSV import/export -- migration path from spreadsheets, data portability
|
|
||||||
- [ ] Weight distribution visualization (pie/bar chart by category) -- polish feature
|
|
||||||
|
|
||||||
### Future Consideration (v2+)
|
|
||||||
|
|
||||||
Features to defer until product-market fit is established.
|
|
||||||
|
|
||||||
- [ ] Multi-photo gallery per item -- storage and UI complexity
|
|
||||||
- [ ] Shareable read-only links for setups -- lightweight sharing without auth
|
|
||||||
- [ ] Drag-and-drop reordering in lists and setups -- UX refinement
|
|
||||||
- [ ] Bulk operations (multi-select, bulk categorize, bulk delete) -- power user feature
|
|
||||||
- [ ] Dark mode -- common request, low priority for initial launch
|
|
||||||
- [ ] Item history / changelog (track weight after modifications, price changes) -- advanced tracking
|
|
||||||
|
|
||||||
## Feature Prioritization Matrix
|
|
||||||
|
|
||||||
| Feature | User Value | Implementation Cost | Priority |
|
|
||||||
|---------|------------|---------------------|----------|
|
|
||||||
| Item CRUD with core fields | HIGH | LOW | P1 |
|
|
||||||
| Categories | HIGH | LOW | P1 |
|
|
||||||
| Weight unit support | HIGH | LOW | P1 |
|
|
||||||
| Auto weight/cost totals | HIGH | LOW | P1 |
|
|
||||||
| Named setups | HIGH | MEDIUM | P1 |
|
|
||||||
| Planning threads | HIGH | HIGH | P1 |
|
|
||||||
| Candidate comparison | HIGH | MEDIUM | P1 |
|
|
||||||
| Thread resolution | HIGH | MEDIUM | P1 |
|
|
||||||
| Dashboard home | MEDIUM | LOW | P1 |
|
|
||||||
| Search and filter | MEDIUM | LOW | P1 |
|
|
||||||
| Impact preview | HIGH | MEDIUM | P2 |
|
|
||||||
| Status tracking (threads) | MEDIUM | LOW | P2 |
|
|
||||||
| Priority/ranking (threads) | MEDIUM | LOW | P2 |
|
|
||||||
| Photos per item | MEDIUM | MEDIUM | P2 |
|
|
||||||
| CSV import/export | MEDIUM | MEDIUM | P2 |
|
|
||||||
| Weight visualization charts | MEDIUM | MEDIUM | P2 |
|
|
||||||
| Multi-photo gallery | LOW | MEDIUM | P3 |
|
|
||||||
| Shareable links | LOW | MEDIUM | P3 |
|
|
||||||
| Drag-and-drop reordering | LOW | MEDIUM | P3 |
|
|
||||||
| Bulk operations | LOW | MEDIUM | P3 |
|
|
||||||
|
|
||||||
**Priority key:**
|
|
||||||
- P1: Must have for launch
|
|
||||||
- P2: Should have, add when possible
|
|
||||||
- P3: Nice to have, future consideration
|
|
||||||
|
|
||||||
## Competitor Feature Analysis
|
|
||||||
|
|
||||||
| Feature | LighterPack | GearGrams | Packstack | Hikt | GearBox (Our Approach) |
|
|
||||||
|---------|-------------|-----------|-----------|------|------------------------|
|
|
||||||
| Gear inventory | Per-list only (no central closet) | Central library + lists | Full gear library | Full closet with search | Full collection as central source of truth |
|
|
||||||
| Weight tracking | Excellent -- base/worn/consumable splits, pie charts | Good -- multi-unit, category totals | Good -- base/worn/consumable | Excellent -- smart insights | Base/worn/consumable with unit flexibility |
|
|
||||||
| Packing lists / setups | Unlimited lists (web) | Multiple lists via drag-drop | Trip-based (2 free) | 3 free lists, more with premium | Named setups composed from collection |
|
|
||||||
| Purchase planning | None | None | None | None | Planning threads with candidates, comparison, resolution -- unique |
|
|
||||||
| Impact analysis | None | None | None | None | Show how a candidate changes setup weight/cost -- unique |
|
|
||||||
| Photos | None | None | None | Yes | Yes (v1.x) |
|
|
||||||
| Import/export | None (copy-linked lists only) | CSV import | None mentioned | LighterPack import, CSV | CSV import/export (v1.x) |
|
|
||||||
| Mobile | No native app (web only, poor mobile UX) | Web only | iOS only | iOS + Android + web | Web-first, responsive design |
|
|
||||||
| Sharing | Shareable links | None mentioned | Shareable trip links | Community lists, collaboration | Deferred (v2+, read-only links) |
|
|
||||||
| Hobby scope | Hiking/backpacking only | Hiking/backpacking only | Hiking/backpacking only | Hiking/backpacking only | Any hobby (bikepacking, sim racing, photography, etc.) |
|
|
||||||
| Pricing | Free | Free | Freemium (2 lists free) | Freemium (3 lists free) | Single-user, no tiers |
|
|
||||||
| Status | Open source, aging, no mobile | Maintained but dated | Active development | Actively developed, modern | New entrant with unique purchase planning angle |
|
|
||||||
|
|
||||||
## Sources
|
## Sources
|
||||||
|
|
||||||
- [LighterPack](https://lighterpack.com/) -- free web-based gear list tool, community standard
|
- [LighterPack](https://lighterpack.com/) -- weight classification and pie chart visualization patterns
|
||||||
- [GearGrams](https://www.geargrams.com/) -- drag-and-drop gear library with multi-unit support
|
- [LighterPack Tutorial (99Boulders)](https://www.99boulders.com/lighterpack-tutorial) -- detailed feature walkthrough
|
||||||
- [Packstack](https://www.packstack.io/) -- trip-centric gear management with weather integration
|
- [LighterPack Tutorial (Backpackers.com)](https://backpackers.com/blog/how-to-calculate-backpack-weight-with-lighterpack/) -- base/worn/consumable definitions
|
||||||
- [Hikt](https://hikt.app/) -- modern gear manager with mobile apps and community features
|
- [Hikt](https://hikt.app/) -- searchable gear closet, base vs worn weight display
|
||||||
- [Hikt Blog: Best Backpacking Gear Apps 2026](https://hikt.app/blog/best-backpacking-gear-apps-2026/) -- competitive comparison
|
- [PackLight (iOS)](https://apps.apple.com/us/app/packlight-for-backpacking/id1054845207) -- search, custom categories, bar graph visualization
|
||||||
- [HikeLite](https://hikeliteapp.com/) -- ultralight gear management with CSV support
|
- [Packstack](https://www.packstack.io/) -- base/worn/consumable weight separation
|
||||||
- [Packrat](https://www.packrat.app/) -- iOS/Android gear inventory with CSV/JSON import
|
- [HikeLite](https://hikeliteapp.com/) -- worn weight marking, CSV import format
|
||||||
- [LighterPack GitHub Issues](https://github.com/galenmaly/lighterpack/issues) -- user feature requests and limitations
|
- [Packrat](https://www.packrat.app/) -- flexible weight unit input and display conversion
|
||||||
- [Palespruce Bikepacking Gear Spreadsheet](http://www.palespruce.com/bikepacking-gear-spreadsheet/) -- spreadsheet workflow GearBox replaces
|
- [BPL Calculator Forum Discussion](https://backpackinglight.com/forums/topic/new-backpacking-hiking-weight-calculator-app/) -- unit conversion UX, search filter patterns
|
||||||
- [99Boulders Backpacking Gear List Spreadsheet](https://www.99boulders.com/backpacking-gear-list-spreadsheet) -- spreadsheet workflow patterns
|
- [react-minimal-pie-chart (GitHub)](https://github.com/toomuchdesign/react-minimal-pie-chart) -- 2kB lightweight chart library
|
||||||
|
- [Best React Chart Libraries 2025 (LogRocket)](https://blog.logrocket.com/best-react-chart-libraries-2025/) -- chart library comparison
|
||||||
|
- [LighterPack GitHub Issues](https://github.com/galenmaly/lighterpack/issues) -- user feature requests
|
||||||
|
- [OutPack](https://outpack.app/) -- modern LighterPack alternative with category breakdown graphs
|
||||||
|
- [Pack Weight Calculator Guide (BackpackPeek)](https://backpackpeek.com/blog/pack-weight-calculator-base-weight-guide) -- base weight calculation methodology
|
||||||
|
|
||||||
---
|
---
|
||||||
*Feature research for: Gear management and purchase planning*
|
*Feature research for: v1.2 Collection Power-Ups (search/filter, weight classification, visualization, candidate status, weight units)*
|
||||||
*Researched: 2026-03-14*
|
*Researched: 2026-03-16*
|
||||||
|
|||||||
@@ -1,136 +1,202 @@
|
|||||||
# Pitfalls Research
|
# Pitfalls Research
|
||||||
|
|
||||||
**Domain:** Gear management, collection tracking, purchase planning (single-user web app)
|
**Domain:** Adding search/filter, weight classification, weight distribution charts, candidate status tracking, and weight unit selection to an existing gear management app (GearBox v1.2)
|
||||||
**Researched:** 2026-03-14
|
**Researched:** 2026-03-16
|
||||||
**Confidence:** HIGH (domain-specific patterns well-documented across gear community and inventory app space)
|
**Confidence:** HIGH (pitfalls derived from direct codebase analysis + domain-specific patterns from gear tracking community + React/SQLite ecosystem knowledge)
|
||||||
|
|
||||||
## Critical Pitfalls
|
## Critical Pitfalls
|
||||||
|
|
||||||
### Pitfall 1: Unit Handling Treated as Display-Only
|
### Pitfall 1: Weight Unit Conversion Rounding Accumulation
|
||||||
|
|
||||||
**What goes wrong:**
|
**What goes wrong:**
|
||||||
Weight and price values are stored as bare numbers without unit metadata. The app assumes everything is grams or dollars, then breaks when users enter ounces, pounds, kilograms, or foreign currencies. Worse: calculations like "total setup weight" silently produce garbage when items have mixed units. A 200g tent and a 5lb sleeping bag get summed as 205.
|
GearBox stores weight as `real("weight_grams")` (a floating-point column in SQLite). When adding unit selection (g, oz, lb, kg), the naive approach is to convert on display and let users input in their preferred unit, converting back to grams on save. The problem: repeated round-trip conversions accumulate rounding errors. A user enters `5.3 oz`, which converts to `150.253...g`, gets stored as `150.253`, then displayed back as `5.30 oz` (fine so far). But if the user opens the edit form (which shows `5.30 oz`), makes no changes, and saves, the value reconverts from the displayed `5.30` to `150.2535g` -- a different value from what was stored. Over multiple edit cycles, weights drift. More critically, the existing `SUM(items.weight_grams)` aggregates in `setup.service.ts` and `totals.service.ts` will accumulate these micro-errors across dozens of items, producing totals that visibly disagree with manual addition of displayed values. A setup showing items of "5.3 oz + 2.1 oz" but a total of "7.41 oz" (instead of 7.40 oz) erodes trust in the app's core value proposition.
|
||||||
|
|
||||||
**Why it happens:**
|
**Why it happens:**
|
||||||
In a single-user app it feels safe to skip unit handling -- "I'll just always use grams." But real product specs come in mixed units (manufacturers list in oz, g, kg, lb), and copy-pasting from product pages means mixed data creeps in immediately.
|
The conversion factor between grams and ounces (28.3495) is irrational enough that floating-point representation always involves truncation. Combined with SQLite's `REAL` type (8-byte IEEE 754 float, ~15 digits of precision), individual items are accurate enough, but the accumulation across conversions and summation surfaces visible errors.
|
||||||
|
|
||||||
**How to avoid:**
|
**How to avoid:**
|
||||||
Store all weights in a canonical unit (grams) at write time. Accept input in any unit but convert on save. Store the original unit for display purposes but always compute on the canonical value. Build a simple conversion layer from day one -- it is 20 lines of code now vs. a data migration later.
|
1. Store weights in grams as the canonical unit -- this is already done. Good.
|
||||||
|
2. Convert only at the display boundary (the `formatWeight` function in `lib/formatters.ts`). Never convert grams to another unit, let the user edit, and convert back.
|
||||||
|
3. When the user inputs in oz/lb/kg, convert to grams once on save and store. The edit form should always load the stored grams value and re-convert for display, never re-convert from a previously displayed value.
|
||||||
|
4. Round only at the final display step, not during storage. Use `Number(value.toFixed(1))` for display, never for the stored value.
|
||||||
|
5. For totals, compute `SUM(weight_grams)` in SQL (already done), then convert the total to display units once. Do not sum converted per-item display values.
|
||||||
|
6. Consider changing `weight_grams` from `real` to `integer` to store milligrams (or tenths of grams) for sub-gram precision without floating-point issues. This is a larger migration but eliminates the class of errors entirely.
|
||||||
|
|
||||||
**Warning signs:**
|
**Warning signs:**
|
||||||
- Weight field is a plain number input with no unit selector
|
- Edit form pre-fills with a converted value and saves by reconverting that value
|
||||||
- No conversion logic exists anywhere in the codebase
|
- `formatWeight` is called before summation rather than after
|
||||||
- Aggregation functions (total weight) do simple `SUM()` without unit awareness
|
- Unit conversion is done in multiple places (client and server) with different rounding
|
||||||
|
- Tests compare floating-point totals with `===` instead of tolerance-based comparison
|
||||||
|
|
||||||
**Phase to address:**
|
**Phase to address:**
|
||||||
Phase 1 (Data model / Core CRUD) -- unit handling must be in the schema from the start. Retrofitting requires migrating every existing item.
|
Phase 1 (Weight unit selection) -- the conversion layer must be designed correctly from the start. Getting this wrong poisons every downstream feature (charts, setup totals, classification breakdowns).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Pitfall 2: Rigid Category Hierarchy Instead of Flexible Tagging
|
### Pitfall 2: Weight Classification Stored at Wrong Level
|
||||||
|
|
||||||
**What goes wrong:**
|
**What goes wrong:**
|
||||||
The app ships with a fixed category tree (Shelter > Tents > 1-Person Tents) that works for bikepacking but fails for sim racing gear, photography equipment, or any other hobby. Users cannot create categories, and items that span categories (a jacket that is both "clothing" and "rain gear") get awkwardly forced into one slot. The "generic enough for any hobby" goal from PROJECT.md dies on contact with a rigid hierarchy.
|
Weight classification (base weight / worn / consumable) seems like a property of the item itself -- "my rain jacket is always worn weight." So the developer adds a `classification` column to the `items` table. But this is wrong: the same item can be classified differently in different setups. A rain jacket is "worn" in a summer bikepacking setup but "base weight" (packed in the bag) in a winter setup where you wear a heavier outer shell. By putting classification on the item, users cannot accurately model multiple setups with the same gear, which is the entire point of the setup feature.
|
||||||
|
|
||||||
**Why it happens:**
|
**Why it happens:**
|
||||||
Hierarchical categories feel structured and "correct" during design. Flat tags feel messy. But hierarchies require knowing the domain upfront, and GearBox explicitly needs to support arbitrary hobbies.
|
LighterPack and similar tools model classification at the list level (each list has its own classification per item), but when you look at the GearBox schema, the `setup_items` join table only has `(id, setup_id, item_id)`. It feels more natural to add a column to the item itself rather than to a join table, especially since the current `setup_items` table is minimal. The single-user context also makes it feel like "my items have fixed classifications."
|
||||||
|
|
||||||
**How to avoid:**
|
**How to avoid:**
|
||||||
Use a flat tag/label system as the primary organization mechanism. Users create their own tags ("bikepacking", "sleep-system", "cook-kit"). An item can have multiple tags. Optionally allow a single "category" field for broad grouping, but do not enforce hierarchy. Tags are the flexible axis; a single category field is the structured axis.
|
Add `classification TEXT DEFAULT 'base'` to the `setup_items` table, not to `items`. This means:
|
||||||
|
- The same item can have different classifications in different setups
|
||||||
|
- Classification is optional and defaults to "base" (the most common case)
|
||||||
|
- The `items` table stays generic -- classification is a setup-level concern
|
||||||
|
- Existing `setup_items` rows get a sensible default via the migration
|
||||||
|
- SQL aggregates for setup totals can easily group by classification: `SUM(CASE WHEN setup_items.classification = 'base' THEN items.weight_grams ELSE 0 END)`
|
||||||
|
|
||||||
|
If classification is also useful outside of setups (e.g., in the collection view for a general breakdown), add it as an optional `defaultClassification` on `items` that serves as a hint when adding items to setups, but the authoritative classification is always on `setup_items`.
|
||||||
|
|
||||||
**Warning signs:**
|
**Warning signs:**
|
||||||
- Schema has a `category_id` foreign key to a `categories` table with `parent_id`
|
- `classification` column added to `items` table
|
||||||
- Seed data contains a pre-built category tree
|
- Setup detail view shows classification but cannot be different per setup
|
||||||
- Adding a new hobby requires modifying the database
|
- Weight breakdown chart shows the same classification for an item across all setups
|
||||||
|
- No way to classify an item as "worn" in one setup and "base" in another
|
||||||
|
|
||||||
**Phase to address:**
|
**Phase to address:**
|
||||||
Phase 1 (Data model) -- this is a schema-level decision. Changing from hierarchy to tags after data exists requires migration of every item's categorization.
|
Phase 2 (Weight classification) -- this is the single most important schema decision in v1.2. Getting it wrong requires migrating data out of the `items` table into `setup_items` later, which means reconciling possibly-different classifications that users already set.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Pitfall 3: Planning Thread State Machine Complexity Explosion
|
### Pitfall 3: Search/Filter Implemented Server-Side for a Client-Side Dataset
|
||||||
|
|
||||||
**What goes wrong:**
|
**What goes wrong:**
|
||||||
Thread items have statuses (researching, ordered, arrived) plus a thread-level resolution (pick winner, close thread, move to collection). Developers build these as independent fields without modeling the valid state transitions, leading to impossible states: an item marked "arrived" in a thread that was "cancelled," or a "winner" that was never "ordered." The UI then needs defensive checks everywhere, and bugs appear as ghost items in the collection.
|
The developer adds a `GET /api/items?search=tent&category=3` endpoint, sending filtered results from the server. This means:
|
||||||
|
- Every keystroke fires an API request (or requires debouncing, adding latency)
|
||||||
|
- The client's React Query cache for `["items"]` now contains different data depending on filter params, causing stale/inconsistent state
|
||||||
|
- Category grouping in `CollectionView` breaks because the full list is no longer available
|
||||||
|
- The existing `useTotals()` hook returns totals for all items, but the list shows filtered items -- a confusing mismatch
|
||||||
|
|
||||||
**Why it happens:**
|
**Why it happens:**
|
||||||
Status tracking looks simple -- it is just a string field. But the combination of item-level status + thread-level lifecycle + the "move winner to collection" side effect creates a state machine with many transitions, and without explicit modeling, invalid states are reachable.
|
Server-side filtering is the "correct" pattern at scale, and most tutorials teach it that way. But GearBox is a single-user app where the entire collection fits comfortably in memory. The existing `useItems()` hook already fetches all items in one call and the collection view groups them client-side.
|
||||||
|
|
||||||
**How to avoid:**
|
**How to avoid:**
|
||||||
Model the thread lifecycle as an explicit state machine with defined transitions. Document which item statuses are valid in each thread state. The "resolve thread" action should be a single transaction that: (1) validates the winner exists, (2) creates the collection item, (3) marks the thread as resolved, (4) updates the thread item status. Use a state diagram during design, not just field definitions.
|
Implement search and filter entirely on the client side:
|
||||||
|
1. Keep `useItems()` fetching the full list (it already does)
|
||||||
|
2. Add filter state (search query, category ID) as URL search params or React state in the collection page
|
||||||
|
3. Filter the `items` array in the component using `Array.filter()` before grouping and rendering
|
||||||
|
4. The totals bar should continue to show collection totals (unfiltered), not filtered totals -- or show both ("showing 12 of 47 items")
|
||||||
|
5. Only move to server-side filtering if the collection exceeds ~500 items, which is far beyond typical for a single-user gear app
|
||||||
|
|
||||||
|
This preserves the existing caching behavior, requires zero API changes, and gives instant feedback on every keystroke.
|
||||||
|
|
||||||
**Warning signs:**
|
**Warning signs:**
|
||||||
- Thread status and item status are independent string/enum fields with no transition validation
|
- New query parameters added to `GET /api/items` endpoint
|
||||||
- No transaction wrapping the "resolve thread + create collection item" flow
|
- `useItems` hook accepts filter params, creating multiple cache entries
|
||||||
- UI shows impossible combinations (resolved thread with "researching" items)
|
- Search input has a debounce delay
|
||||||
|
- Filtered view totals disagree with dashboard totals
|
||||||
|
|
||||||
**Phase to address:**
|
**Phase to address:**
|
||||||
Phase 2 (Planning threads) -- design the state machine before writing any thread code. Do not add statuses incrementally.
|
Phase 1 (Search/filter) -- the decision to filter client-side vs server-side affects where state lives and must be decided before building the UI.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Pitfall 4: Image Storage Strategy Causes Data Loss or Bloat
|
### Pitfall 4: Candidate Status Transition Without Validation
|
||||||
|
|
||||||
**What goes wrong:**
|
**What goes wrong:**
|
||||||
Two failure modes: (A) Images stored as file paths break when files are moved, deleted, or the app directory changes. Dangling references show broken image icons everywhere. (B) Images stored as BLOBs in SQLite bloat the database, slow down backups, and make the DB file unwieldy as the collection grows.
|
The existing thread system has a simple `status: "active" | "resolved"` on threads and no status on candidates. Adding candidate status tracking (researching -> ordered -> arrived) as a simple text column without transition validation allows impossible states: a candidate marked "arrived" in a thread that was already "resolved," or a candidate going from "arrived" back to "researching." Worse, the existing `resolveThread` function in `thread.service.ts` copies candidate data to create a collection item -- but does not check or update candidate status, so a "researching" candidate can be resolved as the winner (logically wrong, though the data flow works).
|
||||||
|
|
||||||
**Why it happens:**
|
**Why it happens:**
|
||||||
Image storage seems like a simple problem. File paths are the obvious approach but create a coupling between database records and filesystem state. BLOBs seem self-contained but do not scale with photo-heavy collections.
|
The current codebase uses plain strings for thread status with no validation layer. The developer follows the same pattern for candidate status: just a text column with no constraints. SQLite does not enforce enum values, so any string is accepted.
|
||||||
|
|
||||||
**How to avoid:**
|
**How to avoid:**
|
||||||
Store images in a dedicated directory within the app's data folder (e.g., `data/images/{item-id}/`). Store relative paths in the database (never absolute). Generate deterministic filenames from item ID + timestamp to avoid collisions. On item deletion, clean up the image directory. For thumbnails under 100KB, SQLite BLOBs are actually 35% faster than filesystem reads, so consider storing thumbnails as BLOBs while keeping full-size images on disk.
|
1. Define valid candidate statuses as a union type: `"researching" | "ordered" | "arrived"` in `schemas.ts`
|
||||||
|
2. Add Zod validation for the status field with `.refine()` or `z.enum()` to reject invalid values at the API level
|
||||||
|
3. Define valid transitions: `researching -> ordered -> arrived` (and optionally `* -> dropped`)
|
||||||
|
4. In the service layer, validate that the requested status transition is valid before applying it (e.g., cannot go from "arrived" to "researching")
|
||||||
|
5. When resolving a thread, do NOT require a specific candidate status -- the user may resolve with a "researching" candidate if they decide to buy it outright. But DO update all non-winner candidates to a terminal state like "dropped" in the same transaction.
|
||||||
|
6. Add a check in `resolveThread`: if the thread is already resolved, reject the operation (this check already exists in the current code -- good)
|
||||||
|
|
||||||
**Warning signs:**
|
**Warning signs:**
|
||||||
- Absolute file paths in the database
|
- Candidate status is a plain `text()` column with no Zod enum validation
|
||||||
- No cleanup logic when items are deleted (orphaned images accumulate)
|
- No transition validation in the update candidate service
|
||||||
- Database file growing much larger than expected (images stored as BLOBs)
|
- `resolveThread` does not update non-winner candidate statuses
|
||||||
- No fallback/placeholder when an image file is missing
|
- UI allows arbitrary status changes via a dropdown with no constraints
|
||||||
|
|
||||||
**Phase to address:**
|
**Phase to address:**
|
||||||
Phase 1 (Core CRUD with item photos) -- image handling must be decided before any photos are stored. Migrating image storage strategy later requires moving files and updating every record.
|
Phase 3 (Candidate status tracking) -- must be designed with awareness of the existing thread resolution flow in `thread.service.ts`. The status field and transition logic should be added together, not incrementally.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Pitfall 5: Setup Composition Breaks on Collection Changes
|
### Pitfall 5: Weight Distribution Chart Diverges from Displayed Totals
|
||||||
|
|
||||||
**What goes wrong:**
|
**What goes wrong:**
|
||||||
A setup ("Summer Bikepacking") references items from the collection. When an item is deleted from the collection, updated, or replaced via a planning thread resolution, the setup silently breaks -- showing stale data, missing items, or incorrect totals. The user's carefully composed setup becomes untrustworthy.
|
The weight distribution chart (e.g., a donut chart showing weight by category or by classification) computes its data from one source, while the totals bar and setup detail page compute from another. The chart might use client-side summation of displayed (rounded) values while the totals use SQL `SUM()`. Or the chart uses the `useTotals()` hook data while the setup page computes totals inline (as `$setupId.tsx` currently does on lines 53-61). These different computation paths produce different numbers for the same data, and when a chart slice says "Shelter: 2,450g" but the category header says "Shelter: 2,451g," users lose trust.
|
||||||
|
|
||||||
**Why it happens:**
|
**Why it happens:**
|
||||||
Setups are modeled as a simple join table (setup_id, item_id) without considering what happens when the item side changes. The relationship is treated as static when it is actually dynamic.
|
The codebase already has two computation paths for totals: `totals.service.ts` computes via SQL aggregates, and the setup detail page computes via JavaScript reduce on the client. These happen to agree now because there is no unit conversion, but adding unit display and classification filtering creates more opportunities for divergence.
|
||||||
|
|
||||||
**How to avoid:**
|
**How to avoid:**
|
||||||
Use foreign keys with explicit `ON DELETE` behavior (not CASCADE -- that silently removes setup entries). When an item is deleted, mark the setup-item link as "removed" and show a visual indicator in the setup view ("1 item no longer in collection"). When a planning thread resolves and replaces an item, offer to update setups that contained the old item. Setups should always recompute totals from live item data, never cache them.
|
1. Establish a single source of truth for all weight computations: the SQL aggregate in the service layer.
|
||||||
|
2. For chart data, create a dedicated endpoint or extend `GET /api/totals` to return breakdowns by category AND by classification (for setups). Do not recompute in the chart component.
|
||||||
|
3. For setup-specific charts, extend `getSetupWithItems` to return pre-computed breakdowns, or compute them from the setup's item list using a shared utility function that is used by both the totals display and the chart.
|
||||||
|
4. Unit conversion happens once, at the display layer, using the same `formatWeight` function everywhere.
|
||||||
|
5. Write a test that compares the chart data source against the totals data source and asserts they agree.
|
||||||
|
|
||||||
**Warning signs:**
|
**Warning signs:**
|
||||||
- Setup totals are stored as columns rather than computed from item data
|
- Chart component does its own `reduce()` on item data instead of using the same data as the totals display
|
||||||
- No foreign key constraints between setups and items
|
- Two different API endpoints return weight totals for the same scope and the values differ by small amounts
|
||||||
- Deleting a collection item does not check if it belongs to any setup
|
- Chart labels show different precision than text displays (chart: "2.4 kg", header: "2,451 g")
|
||||||
- No UI indication when a setup references a missing item
|
- No shared utility function for weight summation
|
||||||
|
|
||||||
**Phase to address:**
|
**Phase to address:**
|
||||||
Phase 3 (Setups) -- but the foreign key design must be planned in Phase 1 when the items table is created. The item schema needs to anticipate setup references.
|
Phase 3 (Weight distribution visualization) -- but the single-source-of-truth pattern should be established in Phase 1 when refactoring formatters for unit selection.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Pitfall 6: Comparison View That Does Not Actually Help Decisions
|
### Pitfall 6: Schema Migration Breaks Test Helper
|
||||||
|
|
||||||
**What goes wrong:**
|
**What goes wrong:**
|
||||||
The side-by-side comparison in planning threads shows raw data (weight: 450g, price: $120) without context. Users cannot see at a glance which candidate is lighter, cheaper, or how each compares to what they already own. The comparison becomes a formatted table, not a decision tool. Users go back to their spreadsheet because it was easier to add formulas.
|
GearBox's test infrastructure uses a manual `createTestDb()` function in `tests/helpers/db.ts` that creates tables with raw SQL `CREATE TABLE` statements instead of using Drizzle's migration system. When adding new columns (e.g., `classification` to `setup_items`, `status` to `thread_candidates`, `weight_unit` to `settings`), the developer updates `src/db/schema.ts` and runs `bun run db:generate` + `bun run db:push`, but forgets to update the test helper's CREATE TABLE statements. All tests pass in the test database (which has the old schema) while the real database has the new schema -- or worse, tests fail with cryptic column-not-found errors and the developer wastes time debugging the wrong thing.
|
||||||
|
|
||||||
**Why it happens:**
|
**Why it happens:**
|
||||||
Building a comparison view that displays data is easy. Building one that surfaces insights ("this is 30% lighter than your current tent but costs 2x more") requires computing deltas against the existing collection, which is a different feature than just showing two items side by side.
|
The test helper duplicates the schema definition in raw SQL rather than deriving it from the Drizzle schema. This is a known pattern in the codebase (documented in CLAUDE.md: "When adding schema columns, update both `src/db/schema.ts` and the test helper's CREATE TABLE statements"). But under the pressure of adding multiple schema changes across several features, it is easy to miss one table or one column.
|
||||||
|
|
||||||
**How to avoid:**
|
**How to avoid:**
|
||||||
Design comparison views to show: (1) absolute values for each candidate, (2) deltas between candidates (highlighted: lighter/heavier, cheaper/more expensive), (3) delta against the current item being replaced from the collection. Use color coding or directional indicators (green down arrow for weight savings, red up arrow for cost increase). This is the core value proposition of GearBox -- do not ship a comparison that is worse than a spreadsheet.
|
1. **Every schema change PR must include the corresponding test helper update.** Add this as a checklist item in the development workflow.
|
||||||
|
2. Consider writing a simple validation test that compares the columns in `createTestDb()` tables against the Drizzle schema definition, failing if they diverge. This catches the problem automatically.
|
||||||
|
3. For v1.2, since multiple schema changes are landing (classification on setup_items, status on candidates, possibly weight_unit in settings), batch the test helper update and verify all changes in one pass.
|
||||||
|
4. Long-term: investigate using Drizzle's `migrate()` with in-memory SQLite to eliminate the duplication entirely.
|
||||||
|
|
||||||
**Warning signs:**
|
**Warning signs:**
|
||||||
- Comparison view is a static table with no computed differences
|
- Schema column added to `schema.ts` but not to `tests/helpers/db.ts`
|
||||||
- No way to link a thread to "the item I'm replacing" from the collection
|
- Tests pass locally but queries fail at runtime
|
||||||
- Weight/cost impact on overall setup is not visible from the thread view
|
- New service function works in the app but throws in tests
|
||||||
|
- Test database has fewer columns than production database
|
||||||
|
|
||||||
**Phase to address:**
|
**Phase to address:**
|
||||||
Phase 2 (Planning threads) -- comparison is the heart of the thread feature. Build the delta computation alongside the basic thread CRUD, not as a follow-up.
|
Every phase that touches the schema. Must be addressed in Phase 1 (unit settings), Phase 2 (classification on setup_items), and Phase 3 (candidate status). Each phase should verify test helper parity as a completion criterion.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Pitfall 7: Weight Unit Preference Stored Wrong, Applied Wrong
|
||||||
|
|
||||||
|
**What goes wrong:**
|
||||||
|
The developer stores the user's preferred weight unit as a setting (using the existing `settings` table with key-value pairs). But then applies it inconsistently: the collection page shows grams, the setup page shows ounces, the chart shows kilograms. Or the setting is read once on page load and cached in Zustand, so changing the preference requires a page refresh. Or the setting is read on every render, causing a flash of "g" before the "oz" preference loads.
|
||||||
|
|
||||||
|
**Why it happens:**
|
||||||
|
The `settings` table is a key-value store with no type safety. The preference is a string like `"oz"` that must be parsed and applied in many places: `formatWeight` in formatters, chart labels, totals bar, setup detail, item cards, category headers. Missing any one of these locations creates an inconsistency.
|
||||||
|
|
||||||
|
**How to avoid:**
|
||||||
|
1. Store the preference in the `settings` table as `{ key: "weightUnit", value: "g" | "oz" | "lb" | "kg" }`.
|
||||||
|
2. Create a `useWeightUnit()` hook that wraps `useSettings()` and returns the parsed unit with a fallback to `"g"`.
|
||||||
|
3. Modify `formatWeight` to accept a unit parameter: `formatWeight(grams, unit)`. This is a single function used everywhere, so changing it propagates automatically.
|
||||||
|
4. Do NOT store converted values anywhere -- always store grams, convert at display time.
|
||||||
|
5. Use React Query for the settings fetch so the preference is cached and shared across components. When the user changes their preference, invalidate `["settings"]` and all displays update simultaneously via React Query's reactivity.
|
||||||
|
6. Handle the loading state: show raw grams (or a loading skeleton) until the preference is loaded. Do not flash a different unit.
|
||||||
|
|
||||||
|
**Warning signs:**
|
||||||
|
- `formatWeight` does not accept a unit parameter -- it is hardcoded to `"g"`
|
||||||
|
- Weight unit preference is stored in Zustand instead of React Query (settings endpoint)
|
||||||
|
- Some components use `formatWeight` and some inline their own formatting
|
||||||
|
- Changing the unit preference does not update all visible weights without a page refresh
|
||||||
|
|
||||||
|
**Phase to address:**
|
||||||
|
Phase 1 (Weight unit selection) -- this is foundational infrastructure. The `formatWeight` refactor and `useWeightUnit` hook must exist before building any other feature that displays weight.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -140,21 +206,24 @@ Shortcuts that seem reasonable but create long-term problems.
|
|||||||
|
|
||||||
| Shortcut | Immediate Benefit | Long-term Cost | When Acceptable |
|
| Shortcut | Immediate Benefit | Long-term Cost | When Acceptable |
|
||||||
|----------|-------------------|----------------|-----------------|
|
|----------|-------------------|----------------|-----------------|
|
||||||
| Caching setup totals in a column | Faster reads, simpler queries | Stale data when items change, bugs when totals disagree with item sum | Never -- always compute from source items |
|
| Adding classification to `items` instead of `setup_items` | Simpler schema, no join table changes | Cannot have different classifications per setup; future migration required | Never -- the per-setup model is the correct one |
|
||||||
| Storing currency as float | Simple to implement | Floating point rounding errors in price totals (classic $0.01 bugs) | Never -- use integer cents or a decimal type |
|
| Client-side unit conversion on both read and write paths | Simple bidirectional conversion | Rounding drift over edit cycles, inconsistent totals | Never -- convert once on write, display-only on read |
|
||||||
| Skipping "replaced by" links in threads | Simpler thread resolution | Cannot track upgrade history, cannot auto-update setups | Only in earliest prototype, must add before thread resolution ships |
|
| Separate chart data computation from totals computation | Faster chart development, no API changes | Numbers disagree between chart and text displays | Only if a shared utility function ensures identical computation |
|
||||||
| Hardcoding unit labels | Faster initial development | Cannot support multiple hobbies with different unit conventions (e.g., ml for water bottles) | MVP only if unit conversion layer is planned for next phase |
|
| Hardcoding chart library colors per category | Quick to implement | Colors collide when user adds categories; no dark mode support | MVP only if using a predictable color generation function is planned |
|
||||||
| Single image per item | Simpler UI and storage | Gear often needs multiple angles, especially for condition tracking | Acceptable for v1 if schema supports multiple images (just limit UI to one) |
|
| Adding candidate status without transition validation | Faster to implement | Invalid states accumulate, resolve logic has edge cases | Only if validation is added before the feature ships to production |
|
||||||
|
| Debouncing search instead of client-side filter | Familiar pattern from server-filtered apps | Unnecessary latency, complex cache management | Never for this app's scale (sub-500 items) |
|
||||||
|
|
||||||
## Integration Gotchas
|
## Integration Gotchas
|
||||||
|
|
||||||
Common mistakes when connecting to external services.
|
Since v1.2 is adding features to an existing system rather than integrating external services, these are internal integration points where new features interact with existing ones.
|
||||||
|
|
||||||
| Integration | Common Mistake | Correct Approach |
|
| Integration Point | Common Mistake | Correct Approach |
|
||||||
|-------------|----------------|------------------|
|
|-------------------|----------------|------------------|
|
||||||
| Product link scraping | Attempting to auto-fetch product details from URLs, which breaks constantly as sites change layouts | Store the URL as a plain link. Do not scrape. Let users enter details manually. Scraping is a maintenance burden that exceeds its value for a single-user app. |
|
| Search/filter + category grouping | Filtering items breaks the existing category-grouped layout because the group headers disappear when no items match | Filter within groups: show category headers only for groups with matching items. Empty groups should hide, not show "no items." |
|
||||||
| Image URLs vs local storage | Hotlinking product images from retailer sites, which break when products are delisted | Always download and store images locally. External URLs rot within months. |
|
| Weight classification + existing setup totals | Adding classification changes how totals are computed (base weight vs total weight), but existing setup list cards show `totalWeight` which was previously "everything" | Keep `totalWeight` as the sum of all items. Add `baseWeight` as a new computed field (sum of items where classification = 'base'). Show both in the setup detail view. |
|
||||||
| Export/import formats | Building a custom JSON format that only GearBox understands | Support CSV import/export as the universal fallback. Users are migrating from spreadsheets -- CSV is their native format. |
|
| Candidate status + thread resolution | Adding status to candidates but not updating `resolveThread` to handle it | The `resolveThread` transaction must set winner status to a terminal state and non-winners to "dropped." New candidates added to an already-resolved thread should be rejected. |
|
||||||
|
| Unit selection + React Query cache | Changing the weight unit preference does not invalidate the items cache because items are stored in grams regardless | The unit preference is a display concern, not a data concern. Do NOT invalidate items/totals on unit change. Just re-render with the new unit. Ensure `formatWeight` is called reactively, not cached. |
|
||||||
|
| Weight chart + empty/null weights | Chart component crashes or shows misleading data when items have `null` weight | Filter out items with null weight from chart data. Show a note like "3 items excluded (no weight recorded)." Never treat null as 0 in a chart -- that makes the chart lie. |
|
||||||
|
|
||||||
## Performance Traps
|
## Performance Traps
|
||||||
|
|
||||||
@@ -162,10 +231,11 @@ Patterns that work at small scale but fail as usage grows.
|
|||||||
|
|
||||||
| Trap | Symptoms | Prevention | When It Breaks |
|
| Trap | Symptoms | Prevention | When It Breaks |
|
||||||
|------|----------|------------|----------------|
|
|------|----------|------------|----------------|
|
||||||
| Loading all collection items for every setup view | Slow page loads, high memory usage | Paginate collection views; setup views should query only member items | 500+ items in collection |
|
| Re-rendering entire collection on search keystroke | UI jank on every character typed in search box | Use `useMemo` to memoize the filtered list; ensure `ItemCard` is memoized with `React.memo` | 100+ items with images |
|
||||||
| Recomputing all setup totals on every item edit | Edit latency increases linearly with number of setups | Only recompute totals for setups containing the edited item | 20+ setups referencing overlapping items |
|
| Chart re-renders on every parent state change | Chart animation restarts on unrelated state updates (e.g., opening a panel) | Memoize chart data computation with `useMemo`; wrap chart component in `React.memo`; use `isAnimationActive={false}` after initial render | Any chart library with entrance animations |
|
||||||
| Storing full-resolution photos without thumbnails | Page loads become unusably slow when browsing collection | Generate thumbnails on upload; use thumbnails in list views, full images only in detail view | 50+ items with photos |
|
| Recharts SVG rendering with many category slices | Donut chart becomes sluggish with 20+ categories, each with a tooltip and label | Limit chart to top N categories by weight, group the rest into "Other." Recharts is SVG-based, so keep segments under ~15. | 20+ categories (unlikely for single user, but possible) |
|
||||||
| Loading all thread candidates for comparison | Irrelevant for small threads, but threads can accumulate many "considered" items | Limit comparison view to 3-4 selected candidates; archive dismissed ones | 15+ candidates in a single thread |
|
| Fetching settings on every component that displays weight | Waterfall of settings requests, or flash of unconverted weights | Use React Query with `staleTime: Infinity` for settings (they change rarely). Prefetch settings at app root. | First load of any page with weights |
|
||||||
|
| Computing classification breakdown per-render | Expensive reduce operations on every render cycle | Compute once in `useMemo` keyed on the items array and classification data | Setups with 50+ items (common for full bikepacking lists) |
|
||||||
|
|
||||||
## Security Mistakes
|
## Security Mistakes
|
||||||
|
|
||||||
@@ -173,9 +243,9 @@ Domain-specific security issues beyond general web security.
|
|||||||
|
|
||||||
| Mistake | Risk | Prevention |
|
| Mistake | Risk | Prevention |
|
||||||
|---------|------|------------|
|
|---------|------|------------|
|
||||||
| No backup mechanism for SQLite database | Single file corruption = total data loss of entire collection | Implement automatic periodic backups (copy the .db file). Provide a manual "export all" button. Single-user apps have no server-side backup by default. |
|
| Candidate status field accepts arbitrary strings | SQLite text column accepts anything; UI may display unexpected values or XSS payloads in status badges | Validate status against enum in Zod schema. Reject unknown values at API level. Use `z.enum(["researching", "ordered", "arrived"])`. |
|
||||||
| Product URLs stored without sanitization | Stored URLs could contain javascript: protocol or XSS payloads if rendered as links | Validate URLs on save (must be http/https). Render with `rel="noopener noreferrer"`. |
|
| Search query used in raw SQL LIKE | SQL injection if search string is interpolated into query (unlikely with Drizzle ORM but possible in raw SQL aggregates) | Use Drizzle's `like()` or `ilike()` operators which parameterize automatically. Never use template literals in `sql\`\`` with unsanitized user input. |
|
||||||
| Image uploads without size/type validation | Malicious or accidental upload of huge files or non-image files | Validate file type (accept only jpg/png/webp) and enforce max size (e.g., 5MB) on upload. |
|
| Unit preference allows arbitrary values | Settings table stores any string; a crafted value could break formatWeight or cause display issues | Validate unit against `z.enum(["g", "oz", "lb", "kg"])` both on read and write. Use a typed constant for the allowed values. |
|
||||||
|
|
||||||
## UX Pitfalls
|
## UX Pitfalls
|
||||||
|
|
||||||
@@ -183,25 +253,28 @@ Common user experience mistakes in this domain.
|
|||||||
|
|
||||||
| Pitfall | User Impact | Better Approach |
|
| Pitfall | User Impact | Better Approach |
|
||||||
|---------|-------------|-----------------|
|
|---------|-------------|-----------------|
|
||||||
| Requiring all fields to add an item | Users abandon data entry because they do not know the weight or price yet for items they already own | Only require name. Make weight, price, category, etc. optional. Users fill in details over time. |
|
| Search clears when switching tabs (gear/planning/setups) | User searches for "tent," switches to planning to check threads, switches back and search is gone | Persist search query as a URL search parameter (`?tab=gear&q=tent`). TanStack Router already handles tab via search params. |
|
||||||
| No bulk operations for collection management | Adding 30 existing items one-by-one is painful enough that users never finish initial setup | Provide CSV import for initial collection population. Consider a "quick add" mode with minimal fields. |
|
| Unit selection buried in settings page | User cannot quickly toggle between g and oz when comparing products listed in different units | Add a unit toggle/selector directly in the weight display area (e.g., in the TotalsBar or a small dropdown next to weight values). Keep global preference in settings, but allow quick access. |
|
||||||
| Thread resolution is destructive | User resolves a thread and loses all the research notes and rejected candidates | Archive resolved threads, do not delete them. Users want to reference why they chose item X over Y months later. |
|
| Classification picker adds friction to setup composition | User must classify every item when adding it to a setup, turning a quick "add to loadout" into a tedious process | Default all items to "base" classification. Allow bulk reclassification. Show classification as an optional second step after composing the setup. |
|
||||||
| Flat item list with no visual grouping | Collection becomes an unscannable wall of text at 50+ items | Group by tag/category in the default view. Provide sort options (weight, price, date added). Show item thumbnails in list view. |
|
| Chart with no actionable insight | A pie chart showing "Shelter: 40%, Sleep: 25%, Cooking: 20%" is pretty but does not help the user make decisions | Pair the chart with a list sorted by weight. Highlight the heaviest category. If possible, show how the breakdown compares to "typical" or to other setups. At minimum, make chart segments clickable to filter to that category. |
|
||||||
| Weight displayed without context | "450g" means nothing without knowing if that is heavy or light for this category | Show weight relative to the lightest/heaviest item in the same category, or relative to the item being replaced |
|
| Status badges with no timestamps | User sees "ordered" but cannot remember when they ordered, or whether it has been suspiciously long | Store status change timestamps. Show relative time ("ordered 3 days ago"). Highlight statuses that have been stale too long ("ordered 30+ days ago -- still waiting?"). |
|
||||||
| No "undo" for destructive actions | Accidental deletion of an item with detailed notes is unrecoverable | Soft-delete with a 30-day trash, or at minimum a confirmation dialog that names the item being deleted |
|
| Filter resets feel destructive | User applies multiple filters (category + search), then accidentally clears one and loses the other | Show active filters as dismissible chips/pills above the list. Each filter is independently clearable. A "clear all" button resets everything. |
|
||||||
|
|
||||||
## "Looks Done But Isn't" Checklist
|
## "Looks Done But Isn't" Checklist
|
||||||
|
|
||||||
Things that appear complete but are missing critical pieces.
|
Things that appear complete but are missing critical pieces.
|
||||||
|
|
||||||
- [ ] **Item CRUD:** Often missing image cleanup on delete -- verify orphaned images are removed when items are deleted
|
- [ ] **Search/filter:** Often missing keyboard shortcut (Cmd/Ctrl+K to focus search) -- verify search is easily accessible without mouse
|
||||||
- [ ] **Planning threads:** Often missing the "link to existing collection item being replaced" -- verify threads can reference what they are upgrading
|
- [ ] **Search/filter:** Often missing empty state for "no results" -- verify a helpful message appears when search matches nothing, distinct from "collection is empty"
|
||||||
- [ ] **Setup composition:** Often missing recomputation on item changes -- verify that editing an item's weight updates all setups containing it
|
- [ ] **Weight classification:** Often missing the per-setup model -- verify the same item can have different classifications in different setups
|
||||||
- [ ] **CSV import:** Often missing unit detection/conversion -- verify that importing "5 oz" vs "142g" both result in correct canonical storage
|
- [ ] **Weight classification:** Often missing "unclassified" handling -- verify items with no classification default to "base" in all computations
|
||||||
- [ ] **Thread resolution:** Often missing setup propagation -- verify that resolving a thread and adding the winner to collection offers to update setups that contained the replaced item
|
- [ ] **Weight chart:** Often missing null-weight items -- verify items without weight data are excluded from chart with a visible note, not silently treated as 0g
|
||||||
- [ ] **Comparison view:** Often missing delta computation -- verify that the comparison shows differences between candidates, not just raw values side by side
|
- [ ] **Weight chart:** Often missing responsiveness -- verify chart renders correctly on mobile widths (Recharts needs `ResponsiveContainer` wrapper)
|
||||||
- [ ] **Dashboard totals:** Often missing staleness handling -- verify dashboard stats reflect current data, not cached snapshots
|
- [ ] **Candidate status:** Often missing transition validation -- verify a candidate cannot go from "arrived" back to "researching"
|
||||||
- [ ] **Item deletion:** Often missing setup impact check -- verify the user is warned "This item is in 3 setups" before confirming deletion
|
- [ ] **Candidate status:** Often missing integration with thread resolution -- verify resolving a thread updates all candidate statuses appropriately
|
||||||
|
- [ ] **Unit selection:** Often missing consistent application -- verify every weight display in the app (cards, headers, totals, charts, setup detail, item picker) uses the selected unit
|
||||||
|
- [ ] **Unit selection:** Often missing the edit form -- verify the item/candidate edit form shows weight in the selected unit and converts correctly on save
|
||||||
|
- [ ] **Unit selection:** Often missing chart axis labels -- verify the chart shows the correct unit in labels and tooltips
|
||||||
|
|
||||||
## Recovery Strategies
|
## Recovery Strategies
|
||||||
|
|
||||||
@@ -209,12 +282,13 @@ When pitfalls occur despite prevention, how to recover.
|
|||||||
|
|
||||||
| Pitfall | Recovery Cost | Recovery Steps |
|
| Pitfall | Recovery Cost | Recovery Steps |
|
||||||
|---------|---------------|----------------|
|
|---------|---------------|----------------|
|
||||||
| Mixed units without conversion | MEDIUM | Add unit column to items table. Write a migration script that prompts user to confirm/correct units for existing items. Recompute all setup totals. |
|
| Classification on items instead of setup_items | HIGH | Add classification column to setup_items. Write migration to copy item classification to all setup_item rows referencing it. Remove classification from items. Review all service queries. |
|
||||||
| Rigid category hierarchy | HIGH | Migrate categories to tags (each leaf category becomes a tag). Update all item references. Redesign category UI to tag-based UI. |
|
| Rounding drift from bidirectional conversion | MEDIUM | Audit all items for drift (compare stored grams to expected values). Fix formatWeight to convert only at display. One-time data cleanup for items with suspicious fractional grams. |
|
||||||
| Thread state machine bugs | MEDIUM | Audit all threads for impossible states. Write a cleanup script. Add transition validation. Retest all state transitions. |
|
| Chart data disagrees with totals | LOW | Refactor chart to use the same data source as totals. Create shared utility. No data migration needed. |
|
||||||
| Image path breakage | LOW-MEDIUM | Write a script that scans DB for broken image paths. Move images to canonical location. Update paths. Add fallback placeholder. |
|
| Test helper out of sync with schema | LOW | Update CREATE TABLE statements in test helper. Run all tests. Fix any that relied on the old schema. |
|
||||||
| Stale setup totals | LOW | Drop cached total columns. Replace with computed queries. One-time migration, no data loss. |
|
| Server-side search causing cache issues | MEDIUM | Revert to client-side filtering. Remove query params from useItems. May need to clear stale React Query cache entries with different keys. |
|
||||||
| Currency as float | MEDIUM | Multiply all price values by 100, change column type to integer (cents). Rounding during conversion may lose sub-cent precision. |
|
| Candidate status without transitions | MEDIUM | Add transition validation to update endpoint. Audit existing candidates for invalid states. Write cleanup migration if needed. |
|
||||||
|
| Unit preference inconsistently applied | LOW | Audit all weight display points. Ensure all use formatWeight with unit parameter. No data changes needed. |
|
||||||
|
|
||||||
## Pitfall-to-Phase Mapping
|
## Pitfall-to-Phase Mapping
|
||||||
|
|
||||||
@@ -222,28 +296,27 @@ How roadmap phases should address these pitfalls.
|
|||||||
|
|
||||||
| Pitfall | Prevention Phase | Verification |
|
| Pitfall | Prevention Phase | Verification |
|
||||||
|---------|------------------|--------------|
|
|---------|------------------|--------------|
|
||||||
| Unit handling | Phase 1: Data model | Schema stores canonical grams + original unit. Conversion utility exists with tests. |
|
| Rounding accumulation | Phase 1: Weight unit selection | `formatWeight` converts grams to display unit. Edit forms load grams from API, not from displayed value. Write test: edit an item 10 times without changes, weight stays identical. |
|
||||||
| Category rigidity | Phase 1: Data model | Items have a tags array/join table. No hierarchical category table exists. |
|
| Classification at wrong level | Phase 2: Weight classification | `classification` column exists on `setup_items`, not `items`. Test: same item in two setups has different classifications. |
|
||||||
| Image storage | Phase 1: Core CRUD | Images stored in `data/images/` with relative paths. Thumbnails generated on upload. Cleanup on delete. |
|
| Server-side search for client data | Phase 1: Search/filter | No new API parameters on `GET /api/items`. Filter logic lives in `CollectionView` component. Test: search works instantly without network requests. |
|
||||||
| Currency precision | Phase 1: Data model | Price stored as integer cents. Display layer formats to dollars/euros. |
|
| Status without transition validation | Phase 3: Candidate status | Zod enum validates status values. Service rejects invalid transitions. Test: updating "arrived" to "researching" returns 400 error. |
|
||||||
| Thread state machine | Phase 2: Planning threads | State transitions documented in code. Invalid transitions throw errors. Resolution is transactional. |
|
| Chart/totals divergence | Phase 3: Weight visualization | Chart data and totals bar use same computation path. Test: sum of chart segment values equals displayed total. |
|
||||||
| Comparison usefulness | Phase 2: Planning threads | Comparison view shows deltas. Thread can link to "item being replaced." Setup impact visible. |
|
| Test helper desync | Every schema-changing phase | Each phase's PR includes updated test helper. CI test suite catches column mismatches. |
|
||||||
| Setup integrity | Phase 3: Setups | Totals computed from live data. Item deletion warns about setup membership. Soft-delete or archive for removed items. |
|
| Unit preference inconsistency | Phase 1: Weight unit selection | All weight displays use `formatWeight(grams, unit)`. Test: change unit preference, verify all visible weights update without refresh. |
|
||||||
| Data loss / no backup | Phase 1: Infrastructure | Automatic DB backup on a schedule. Manual export button on dashboard. |
|
|
||||||
| Bulk import | Phase 1: Core CRUD | CSV import available from collection view. Handles unit variations in weight column. |
|
|
||||||
|
|
||||||
## Sources
|
## Sources
|
||||||
|
|
||||||
- [Ultralight: The Gear Tracking App I'm Leaving LighterPack For](https://trailsmag.net/blogs/hiker-box/ultralight-the-gear-tracking-app-i-m-leaving-lighterpack-for) -- LighterPack limitations and community complaints
|
- [Weight conversion precision and rounding best practices](https://explore.st-aug.edu/exp/from-ounces-to-pounds-the-precision-behind-weight-conversions-heres-how-many-grams-equal-a-practical-pound) -- authoritative source on conversion factor precision
|
||||||
- [SQLite Internal vs External BLOBs](https://sqlite.org/intern-v-extern-blob.html) -- official SQLite guidance on image storage tradeoffs
|
- [Base weight classification definitions and community debates](https://thetrek.co/continental-divide-trail/how-to-easily-lower-your-base-weight-calculate-it-differently/) -- real-world examples of classification ambiguity
|
||||||
- [35% Faster Than The Filesystem](https://sqlite.org/fasterthanfs.html) -- SQLite BLOB performance data
|
- [LighterPack user classification errors](https://www.99boulders.com/lighterpack-tutorial) -- LighterPack's approach to base/worn/consumable
|
||||||
- [Comparison Tables for Products, Services, and Features - NN/g](https://www.nngroup.com/articles/comparison-tables/) -- comparison UX best practices
|
- [Avoiding common mistakes with TanStack Query](https://www.buncolak.com/posts/avoiding-common-mistakes-with-tanstack-query-part-1/) -- anti-patterns with React Query caching
|
||||||
- [Designing The Perfect Feature Comparison Table - Smashing Magazine](https://www.smashingmagazine.com/2017/08/designing-perfect-feature-comparison-table/) -- comparison table design patterns
|
- [TanStack Query discussions on filtering with cache](https://github.com/TanStack/query/discussions/1113) -- community patterns for client-side vs server-side filtering
|
||||||
- [Comparing products: UX design best practices - Contentsquare](https://contentsquare.com/blog/comparing-products-design-practices-to-help-your-users-avoid-fragmented-comparison-7/) -- product comparison UX pitfalls
|
- [Recharts performance and limitations](https://blog.logrocket.com/best-react-chart-libraries-2025/) -- SVG rendering pitfalls, ResponsiveContainer requirement
|
||||||
- [Common Unit Conversion Mistakes That Break Applications](https://helppdev.com/en/blog/common-unit-conversion-mistakes-that-break-applications) -- unit conversion antipatterns
|
- [Drizzle ORM SQLite migration pitfalls](https://github.com/drizzle-team/drizzle-orm/issues/1313) -- data loss bug with push + add column
|
||||||
- [Inventory App Design - UXPin](https://www.uxpin.com/studio/blog/inventory-app-design/) -- inventory app UX patterns
|
- [State machine anti-patterns](https://rclayton.silvrback.com/use-state-machines) -- importance of explicit transition validation
|
||||||
- [Designing better file organization around tags, not hierarchies](https://www.nayuki.io/page/designing-better-file-organization-around-tags-not-hierarchies) -- tags vs hierarchy tradeoffs
|
- [Ultralight gear tracker leaving LighterPack](https://trailsmag.net/blogs/hiker-box/ultralight-the-gear-tracking-app-i-m-leaving-lighterpack-for) -- community frustrations with existing tools
|
||||||
|
- Direct codebase analysis of GearBox v1.1 (schema.ts, services, hooks, routes) -- existing patterns and integration points
|
||||||
|
|
||||||
---
|
---
|
||||||
*Pitfalls research for: GearBox -- gear management and purchase planning app*
|
*Pitfalls research for: GearBox v1.2 -- Collection Power-Ups (search/filter, weight classification, charts, candidate status, unit selection)*
|
||||||
*Researched: 2026-03-14*
|
*Researched: 2026-03-16*
|
||||||
|
|||||||
@@ -1,191 +1,179 @@
|
|||||||
# Stack Research
|
# Technology Stack -- v1.2 Collection Power-Ups
|
||||||
|
|
||||||
**Domain:** Single-user gear management and purchase planning web app
|
**Project:** GearBox
|
||||||
**Researched:** 2026-03-14
|
**Researched:** 2026-03-16
|
||||||
|
**Scope:** Stack additions for search/filter, weight classification, weight distribution charts, candidate status tracking, weight unit selection
|
||||||
**Confidence:** HIGH
|
**Confidence:** HIGH
|
||||||
|
|
||||||
## Recommended Stack
|
## Key Finding: Minimal New Dependencies
|
||||||
|
|
||||||
### Core Technologies
|
Four of five v1.2 features require **zero new libraries**. They are pure application logic built on top of the existing stack (Drizzle ORM filters, Zod schema extensions, Zustand state, React Query invalidation). The only decision point is whether to add a charting library for weight distribution visualization.
|
||||||
|
|
||||||
| Technology | Version | Purpose | Why Recommended |
|
## New Dependency
|
||||||
|------------|---------|---------|-----------------|
|
|
||||||
| Bun | 1.3.x | Runtime, package manager, bundler | User constraint. Built-in SQLite, fast installs, native TS support. Eliminates need for separate runtime/bundler/pkg manager. |
|
|
||||||
| React | 19.2.x | UI framework | Industry standard, massive ecosystem, stable. Server Components not needed for this SPA -- stick with client-side React. |
|
|
||||||
| Vite | 8.0.x | Dev server, production builds | Rolldown-based builds (5-30x faster than Vite 7). Zero-config React support. Bun-compatible. HMR out of the box. |
|
|
||||||
| Hono | 4.12.x | Backend API framework | Built on Web Standards, first-class Bun support, zero dependencies, tiny (~12kB). Perfect for a lightweight REST API. Faster than Express on Bun benchmarks. |
|
|
||||||
| SQLite (bun:sqlite) | Built-in | Database | Zero-dependency, built into Bun runtime. 3-6x faster than better-sqlite3. Single file database -- perfect for single-user app. No server process to manage. |
|
|
||||||
| Drizzle ORM | 0.45.x | Database ORM, migrations | Type-safe SQL, ~7.4kB, zero dependencies. Native bun:sqlite driver support. SQL-like query API (not abstracting SQL away). Built-in migration tooling via drizzle-kit. |
|
|
||||||
| Tailwind CSS | 4.2.x | Styling | CSS-native configuration (no JS config file). Auto content detection. Microsecond incremental builds. Perfect for "light, airy, minimalist" design constraint. |
|
|
||||||
| TanStack Router | 1.167.x | Client-side routing | Full type-safe routing with typed params and search params. File-based route generation. Better SPA experience than React Router v7 (whose best features require framework mode). |
|
|
||||||
| TanStack Query | 5.93.x | Server state management | Handles API data fetching, caching, and synchronization. Eliminates manual loading/error state management. Automatic cache invalidation on mutations. |
|
|
||||||
| Zustand | 5.0.x | Client state management | Minimal boilerplate, ~1kB. For UI state like active filters, modal state, theme. TanStack Query handles server state; Zustand handles the rest. |
|
|
||||||
| Zod | 4.3.x | Schema validation | Validates API inputs on the server, form data on the client, and shares types between both. Single source of truth for data shapes. |
|
|
||||||
| TypeScript | 5.x (Bun built-in) | Type safety | Bun transpiles TS natively -- no tsc needed at runtime. Catches bugs at dev time. Required by Drizzle and TanStack Router for type-safe queries and routes. |
|
|
||||||
|
|
||||||
### Supporting Libraries
|
### Charting: react-minimal-pie-chart
|
||||||
|
|
||||||
| Library | Version | Purpose | When to Use |
|
| Technology | Version | Purpose | Why |
|
||||||
|---------|---------|---------|-------------|
|
|------------|---------|---------|-----|
|
||||||
| @tanstack/react-query-devtools | 5.x | Query debugging | Development only. Inspect cache state, refetch timing, query status. |
|
| react-minimal-pie-chart | ^9.1.2 | Weight distribution donut/pie charts | Under 2kB gzipped. Supports pie, donut, loading, and completion chart types. SVG-based with CSS animations, hover/click interactions, custom label rendering. React 19 compatible (peerDeps explicitly include `^19`). Zero external dependencies. TypeScript native. |
|
||||||
| drizzle-kit | latest | DB migrations CLI | Run `drizzle-kit generate` and `drizzle-kit migrate` for schema changes. |
|
|
||||||
| @hono/zod-validator | latest | Request validation middleware | Validate API request bodies/params using Zod schemas in Hono routes. |
|
|
||||||
| clsx | 2.x | Conditional class names | When building components with variant styles. Pairs with Tailwind. |
|
|
||||||
| @tanstack/react-router-devtools | latest | Router debugging | Development only. Inspect route matches, params, search params. |
|
|
||||||
|
|
||||||
### Development Tools
|
**Why this over alternatives:**
|
||||||
|
|
||||||
| Tool | Purpose | Notes |
|
| Criterion | react-minimal-pie-chart | Recharts | Custom SVG | Chart.js |
|
||||||
|------|---------|-------|
|
|-----------|------------------------|----------|------------|----------|
|
||||||
| Bun | Test runner | `bun test` -- built-in, Jest-compatible API. No need for Vitest or Jest. |
|
| Bundle size | ~2kB gzipped | ~97kB gzipped | 0kB | ~60kB gzipped |
|
||||||
| Biome | Linter + formatter | Single tool replacing ESLint + Prettier. Fast (Rust-based), minimal config. `biome check --write` does both. |
|
| Chart types needed | Pie + donut (exactly what we need) | Overkill (line, bar, area, scatter, etc.) | Manual math | Overkill |
|
||||||
| Vite React plugin | React HMR/JSX | `@vitejs/plugin-react` for Fast Refresh during development. |
|
| React 19 support | Explicit in peerDeps | Isolated rendering issues reported with 19.2.x | N/A | Wrapper has open React 19 issues |
|
||||||
|
| Interactivity | Click, hover, focus, keyboard events per segment | Full but heavy | Must implement from scratch | Canvas-based (harder to style) |
|
||||||
|
| Labels | Render prop for custom labels (percentage, value, SVG) | Built-in | Must implement | Built-in |
|
||||||
|
| Animation | CSS-based, configurable duration/easing, reveal effect | D3-based, heavier | Must implement | Canvas animation |
|
||||||
|
| Learning curve | Minimal -- one component, straightforward props | Moderate -- many components | High -- SVG arc math | Moderate |
|
||||||
|
| Maintenance risk | Low -- tiny surface area, stable API | Low -- large community | Zero | Medium -- Canvas abstraction |
|
||||||
|
|
||||||
|
**Why not custom SVG:** The SVG `<circle>` + `stroke-dasharray` approach works for static charts but breaks interactivity (stacked circles mean only the last segment is clickable). The `<path>` arc approach gives full interactivity but requires implementing arc math, animation, labels, hover states, and accessibility from scratch. At ~2kB, react-minimal-pie-chart costs less than the custom code would and handles all edge cases.
|
||||||
|
|
||||||
|
**Why not Recharts:** GearBox needs exactly one chart type (donut/pie). Recharts adds ~97kB of unused capability. It also had isolated rendering issues reported with React 19.2.x, and pulls in D3 submodules. Significant overkill for this use case.
|
||||||
|
|
||||||
|
## Existing Stack Usage for Each Feature
|
||||||
|
|
||||||
|
### 1. Search/Filter Items
|
||||||
|
|
||||||
|
**No new dependencies.** Uses existing Drizzle ORM operators and React state.
|
||||||
|
|
||||||
|
| Existing Tech | How It Is Used |
|
||||||
|
|---------------|----------------|
|
||||||
|
| Drizzle ORM `like()` | Server-side text search on `items.name` column. SQLite LIKE is case-insensitive by default, so no need for `ilike()`. |
|
||||||
|
| Drizzle ORM `eq()`, `and()` | Category filter: `eq(items.categoryId, selectedId)`. Combine with search: `and(like(...), eq(...))`. |
|
||||||
|
| TanStack Query | New query key pattern: `["items", { search, categoryId }]` for filtered results. Server-side filtering preferred over client-side to establish the pattern early (collections grow). |
|
||||||
|
| Zustand or URL search params | Store active filter state. URL search params preferred (already used for tab state) so filter state is shareable/bookmarkable. |
|
||||||
|
| Zod | Validate query params on the Hono route: `z.object({ search: z.string().optional(), categoryId: z.number().optional() })`. |
|
||||||
|
|
||||||
|
**Implementation approach:** Add query parameters to `GET /api/items` rather than client-side filtering. Drizzle's conditional filter pattern handles optional params cleanly:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { like, eq, and } from "drizzle-orm";
|
||||||
|
|
||||||
|
const conditions = [];
|
||||||
|
if (search) conditions.push(like(items.name, `%${search}%`));
|
||||||
|
if (categoryId) conditions.push(eq(items.categoryId, categoryId));
|
||||||
|
|
||||||
|
db.select().from(items).where(and(...conditions));
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Weight Classification (Base/Worn/Consumable)
|
||||||
|
|
||||||
|
**No new dependencies.** Schema change + UI state.
|
||||||
|
|
||||||
|
| Existing Tech | How It Is Used |
|
||||||
|
|---------------|----------------|
|
||||||
|
| Drizzle ORM | Add `weightClass` column to `setup_items` table: `text("weight_class").notNull().default("base")`. Classification is per-setup-item, not per-item globally (a sleeping bag is "base" in a bikepacking setup but might be categorized differently elsewhere). |
|
||||||
|
| Zod | Extend `syncSetupItemsSchema` to include classification: `z.enum(["base", "worn", "consumable"])`. |
|
||||||
|
| drizzle-kit | Generate migration for the new column: `bun run db:generate`. |
|
||||||
|
| SQL aggregates | Compute base/worn/consumable weight subtotals server-side, same pattern as existing category totals in `useTotals`. |
|
||||||
|
|
||||||
|
**Key design decision:** Weight classification belongs on `setup_items` (the join table), not on `items` directly. An item's classification depends on context -- hiking poles are "worn" if you always use them, "base" if they pitch your tent. LighterPack follows this same model. This means the `syncSetupItemsSchema` changes from `{ itemIds: number[] }` to `{ items: Array<{ itemId: number, weightClass: "base" | "worn" | "consumable" }> }`.
|
||||||
|
|
||||||
|
### 3. Weight Distribution Charts
|
||||||
|
|
||||||
|
**One new dependency:** `react-minimal-pie-chart` (documented above).
|
||||||
|
|
||||||
|
| Existing Tech | How It Is Used |
|
||||||
|
|---------------|----------------|
|
||||||
|
| TanStack Query (`useTotals`) | Already returns per-category weight totals. Extend to also return per-weight-class totals for a given setup. |
|
||||||
|
| Tailwind CSS | Style chart container, legend, responsive layout. Chart labels use Tailwind color tokens for consistency. |
|
||||||
|
| Lucide React | Category icons in the chart legend, consistent with existing CategoryHeader component. |
|
||||||
|
|
||||||
|
**Chart data sources:**
|
||||||
|
- **By category:** Already available from `GET /api/totals` response (`categories` array with `totalWeight` per category). No new endpoint needed.
|
||||||
|
- **By weight classification:** New endpoint `GET /api/setups/:id/breakdown` returning `{ base: number, worn: number, consumable: number }` computed from the `weight_class` column on `setup_items`.
|
||||||
|
|
||||||
|
### 4. Candidate Status Tracking
|
||||||
|
|
||||||
|
**No new dependencies.** Schema change + UI update.
|
||||||
|
|
||||||
|
| Existing Tech | How It Is Used |
|
||||||
|
|---------------|----------------|
|
||||||
|
| Drizzle ORM | Add `status` column to `thread_candidates` table: `text("status").notNull().default("researching")`. Values: `"researching"`, `"ordered"`, `"arrived"`. |
|
||||||
|
| Zod | Add to `createCandidateSchema` and `updateCandidateSchema`: `status: z.enum(["researching", "ordered", "arrived"]).default("researching")`. |
|
||||||
|
| Tailwind CSS | Status badge colors on CandidateCard (gray for researching, amber for ordered, green for arrived). Same badge pattern used for thread status already. |
|
||||||
|
| Lucide React | Status icons: `search` for researching, `truck` for ordered, `check-circle` for arrived. Already in the curated icon set. |
|
||||||
|
|
||||||
|
### 5. Weight Unit Selection
|
||||||
|
|
||||||
|
**No new dependencies.** Settings storage + formatter change.
|
||||||
|
|
||||||
|
| Existing Tech | How It Is Used |
|
||||||
|
|---------------|----------------|
|
||||||
|
| SQLite `settings` table | Store preferred unit: `{ key: "weightUnit", value: "g" }`. Same pattern as existing onboarding settings. |
|
||||||
|
| React Query (`useSettings`) | Already exists. Fetch and cache the weight unit preference. |
|
||||||
|
| `formatWeight()` in `lib/formatters.ts` | Extend to accept a unit parameter and convert from grams (the canonical storage format). |
|
||||||
|
| Zustand (optional) | Could cache the unit preference in UI store for synchronous access in formatters. Alternatively, pass it through React context or as a parameter. |
|
||||||
|
|
||||||
|
**Conversion constants (stored weights are always grams):**
|
||||||
|
|
||||||
|
| Unit | From Grams | Display Format |
|
||||||
|
|------|-----------|----------------|
|
||||||
|
| g (grams) | `x` | `${Math.round(x)}g` |
|
||||||
|
| oz (ounces) | `x / 28.3495` | `${(x / 28.3495).toFixed(1)}oz` |
|
||||||
|
| lb (pounds) | `x / 453.592` | `${(x / 453.592).toFixed(2)}lb` |
|
||||||
|
| kg (kilograms) | `x / 1000` | `${(x / 1000).toFixed(2)}kg` |
|
||||||
|
|
||||||
|
**Key decision:** Store weights in grams always. Convert on display only. This avoids precision loss from repeated conversions and keeps the database canonical. The `formatWeight` function becomes the single conversion point.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Initialize project
|
# Only new dependency for v1.2
|
||||||
bun init
|
bun add react-minimal-pie-chart
|
||||||
|
|
||||||
# Core frontend
|
|
||||||
bun add react react-dom @tanstack/react-router @tanstack/react-query zustand zod clsx
|
|
||||||
|
|
||||||
# Core backend
|
|
||||||
bun add hono @hono/zod-validator drizzle-orm
|
|
||||||
|
|
||||||
# Styling
|
|
||||||
bun add tailwindcss @tailwindcss/vite
|
|
||||||
|
|
||||||
# Build tooling
|
|
||||||
bun add -d vite @vitejs/plugin-react typescript @types/react @types/react-dom
|
|
||||||
|
|
||||||
# Database tooling
|
|
||||||
bun add -d drizzle-kit
|
|
||||||
|
|
||||||
# Linting + formatting
|
|
||||||
bun add -d @biomejs/biome
|
|
||||||
|
|
||||||
# Dev tools (optional but recommended)
|
|
||||||
bun add -d @tanstack/react-query-devtools @tanstack/react-router-devtools
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Architecture Pattern
|
That is it. One package, under 2kB gzipped.
|
||||||
|
|
||||||
**Monorepo-lite (single package, split directories):**
|
## Schema Changes Summary
|
||||||
|
|
||||||
```
|
These are the Drizzle schema modifications needed (no new tables, just column additions):
|
||||||
/src
|
|
||||||
/client -- React SPA (Vite entry point)
|
|
||||||
/routes -- TanStack Router file-based routes
|
|
||||||
/components -- Shared UI components
|
|
||||||
/stores -- Zustand stores
|
|
||||||
/api -- TanStack Query hooks (fetch wrappers)
|
|
||||||
/server -- Hono API server
|
|
||||||
/routes -- API route handlers
|
|
||||||
/db -- Drizzle schema, migrations
|
|
||||||
/shared -- Zod schemas shared between client and server
|
|
||||||
/public -- Static assets, uploaded images
|
|
||||||
```
|
|
||||||
|
|
||||||
Bun runs the Hono server, which also serves the Vite-built SPA in production. In development, Vite dev server proxies API calls to the Hono backend.
|
| Table | Change | Migration |
|
||||||
|
|-------|--------|-----------|
|
||||||
|
| `setup_items` | Add `weightClass: text("weight_class").notNull().default("base")` | `bun run db:generate && bun run db:push` |
|
||||||
|
| `thread_candidates` | Add `status: text("status").notNull().default("researching")` | `bun run db:generate && bun run db:push` |
|
||||||
|
| `settings` | No schema change (already key-value). Insert `weightUnit` row. | Seed via service or onboarding. |
|
||||||
|
|
||||||
## Alternatives Considered
|
## What NOT to Add
|
||||||
|
|
||||||
| Recommended | Alternative | When to Use Alternative |
|
|
||||||
|-------------|-------------|-------------------------|
|
|
||||||
| Hono | Elysia | If you want end-to-end type safety with Eden Treaty. Elysia is Bun-native but heavier, more opinionated, and has a smaller ecosystem than Hono. |
|
|
||||||
| Hono | Express | Never for new Bun projects. Express is Node-centric, not built on Web Standards, slower on Bun. |
|
|
||||||
| TanStack Router | React Router v7 | If you want the simplest possible routing with minimal type safety. React Router v7's best features (loaders, type safety) require framework mode which adds complexity. |
|
|
||||||
| Drizzle ORM | Prisma | If you have a complex relational model and want auto-generated migrations. But Prisma is heavy (~8MB), generates a query engine binary, and has weaker SQLite support. |
|
|
||||||
| Drizzle ORM | Kysely | If you want a pure query builder without ORM features. Kysely is lighter but lacks built-in migration tooling. |
|
|
||||||
| Zustand | Jotai | If you prefer atomic state (bottom-up). Zustand is simpler for this app's needs -- a few global stores, not many independent atoms. |
|
|
||||||
| Tailwind CSS | Vanilla CSS / CSS Modules | If you strongly prefer writing plain CSS. But Tailwind accelerates building consistent minimalist UIs and requires less design system setup. |
|
|
||||||
| bun:sqlite | PostgreSQL | If you later need multi-user with concurrent writes. Overkill for single-user. Adds a database server dependency. |
|
|
||||||
| Biome | ESLint + Prettier | If you need specific ESLint plugins not yet in Biome. But Biome covers 95% of use cases with zero config. |
|
|
||||||
| Vite | Bun's built-in bundler | Bun can serve HTML directly as of 1.3, but Vite's ecosystem (plugins, HMR, proxy) is far more mature for SPA development. |
|
|
||||||
|
|
||||||
## What NOT to Use
|
|
||||||
|
|
||||||
| Avoid | Why | Use Instead |
|
| Avoid | Why | Use Instead |
|
||||||
|-------|-----|-------------|
|
|-------|-----|-------------|
|
||||||
| Next.js | Server-centric framework. Massive overhead for a single-user SPA. Forces Node.js patterns. No benefit without SSR/SSG needs. | Vite + React + Hono |
|
| Recharts | 97kB for one chart type. React 19 edge-case issues. D3 dependency chain. | react-minimal-pie-chart (2kB) |
|
||||||
| Remix / React Router framework mode | Adds server framework complexity. This is a simple SPA with a separate API -- framework routing is unnecessary overhead. | TanStack Router (SPA mode) |
|
| Chart.js / react-chartjs-2 | Canvas-based (harder to style with Tailwind). Open React 19 peer dep issues. Overkill. | react-minimal-pie-chart |
|
||||||
| better-sqlite3 | Requires native compilation, compatibility issues with Bun. bun:sqlite is built-in and 3-6x faster. | bun:sqlite (built into Bun) |
|
| visx | Low-level D3 primitives. Steep learning curve. Have to build chart from scratch. Great for custom viz, overkill for a donut chart. | react-minimal-pie-chart |
|
||||||
| Redux / Redux Toolkit | Massive boilerplate for a small app. Actions, reducers, slices -- all unnecessary when Zustand does the same in 10 lines. | Zustand |
|
| Fuse.js or similar search library | Client-side fuzzy search adds bundle weight and complexity. SQLite LIKE is sufficient for name search on a single-user collection (hundreds of items, not millions). | Drizzle `like()` operator |
|
||||||
| Mongoose / MongoDB | Document DB is wrong fit. Gear items have relational structure (items belong to setups, threads reference items). SQL is the right model. | Drizzle + SQLite |
|
| Full-text search (FTS5) | SQLite FTS5 is powerful but requires virtual tables and different query syntax. Overkill for simple name matching on small collections. | Drizzle `like()` operator |
|
||||||
| Axios | Unnecessary abstraction over fetch. Bun and browsers both have native fetch. TanStack Query wraps fetch already. | Native fetch |
|
| i18n library for unit conversion | This is not internationalization. It is four conversion constants and a formatter function. A library would be absurd. | Custom `formatWeight()` function |
|
||||||
| styled-components / Emotion | CSS-in-JS adds runtime overhead and bundle size. Tailwind is faster (zero runtime) and better for consistent minimalist design. | Tailwind CSS |
|
| State machine library (XState) | Candidate status is a simple enum, not a complex state machine. Three values with no guards or side effects. | Zod enum + Drizzle text column |
|
||||||
| Jest / Vitest | Bun has a built-in test runner with Jest-compatible API. No need for external test frameworks. | bun test |
|
| New Zustand store for filters | Filter state should live in URL search params for shareability/bookmarkability. The collection page already uses this pattern for tabs. | TanStack Router search params |
|
||||||
| ESLint + Prettier | Two tools, complex configuration, slow (JS-based). Biome does both in one tool, faster. | Biome |
|
|
||||||
|
|
||||||
## Version Compatibility
|
## Existing Stack Version Compatibility
|
||||||
|
|
||||||
| Package A | Compatible With | Notes |
|
All existing dependencies remain unchanged. The only version consideration:
|
||||||
|-----------|-----------------|-------|
|
|
||||||
| Bun 1.3.x | bun:sqlite (built-in) | SQLite driver is part of the runtime, always compatible. |
|
|
||||||
| Drizzle ORM 0.45.x | bun:sqlite via `drizzle-orm/bun-sqlite` | Official driver. Import from `drizzle-orm/bun-sqlite`. |
|
|
||||||
| Drizzle ORM 0.45.x | drizzle-kit (latest) | drizzle-kit handles migration generation/execution. Must match major drizzle-orm version. |
|
|
||||||
| React 19.2.x | TanStack Router 1.x | TanStack Router 1.x supports React 18+ and 19.x. |
|
|
||||||
| React 19.2.x | TanStack Query 5.x | TanStack Query 5.x supports React 18+ and 19.x. |
|
|
||||||
| React 19.2.x | Zustand 5.x | Zustand 5.x supports React 18+ and 19.x. |
|
|
||||||
| Vite 8.x | @vitejs/plugin-react | Check plugin version matches Vite major. Use latest plugin for Vite 8. |
|
|
||||||
| Tailwind CSS 4.2.x | @tailwindcss/vite | v4 uses Vite plugin instead of PostCSS. Import as `@tailwindcss/vite` in vite config. |
|
|
||||||
| Zod 4.x | @hono/zod-validator | Verify @hono/zod-validator supports Zod 4. If not, pin Zod 3.23.x until updated. |
|
|
||||||
|
|
||||||
## Key Configuration Notes
|
| New Package | Compatible With | Verified |
|
||||||
|
|-------------|-----------------|----------|
|
||||||
### Bun + Vite Setup
|
| react-minimal-pie-chart ^9.1.2 | React 19 (`peerDeps: "^16.8.0 \|\| ^17 \|\| ^18 \|\| ^19"`) | YES -- package.json on GitHub confirms. Dev deps test against React 19.0.0. |
|
||||||
Vite runs as the dev server for the frontend. The Hono API server runs separately. Use Vite's `server.proxy` to forward `/api/*` requests to the Hono backend during development.
|
| react-minimal-pie-chart ^9.1.2 | TypeScript 5.x | YES -- library is TypeScript native (built with TS 3.8+). |
|
||||||
|
| react-minimal-pie-chart ^9.1.2 | Bun bundler / Vite | YES -- pure ESM, no native dependencies, standard npm package. |
|
||||||
### SQLite WAL Mode
|
|
||||||
Enable WAL mode on database initialization for better performance:
|
|
||||||
```typescript
|
|
||||||
import { Database } from "bun:sqlite";
|
|
||||||
const db = new Database("gearbox.db");
|
|
||||||
db.run("PRAGMA journal_mode = WAL");
|
|
||||||
db.run("PRAGMA foreign_keys = ON");
|
|
||||||
```
|
|
||||||
|
|
||||||
### Tailwind v4 (No Config File)
|
|
||||||
Tailwind v4 uses CSS-native configuration. No `tailwind.config.js` needed:
|
|
||||||
```css
|
|
||||||
@import "tailwindcss";
|
|
||||||
@theme {
|
|
||||||
--color-primary: #2563eb;
|
|
||||||
--font-sans: "Inter", sans-serif;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Drizzle Schema Example (bun:sqlite)
|
|
||||||
```typescript
|
|
||||||
import { sqliteTable, text, integer, real } from "drizzle-orm/sqlite-core";
|
|
||||||
|
|
||||||
export const gearItems = sqliteTable("gear_items", {
|
|
||||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
|
||||||
name: text("name").notNull(),
|
|
||||||
category: text("category").notNull(),
|
|
||||||
weightGrams: real("weight_grams"),
|
|
||||||
priceCents: integer("price_cents"),
|
|
||||||
source: text("source"),
|
|
||||||
notes: text("notes"),
|
|
||||||
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
## Sources
|
## Sources
|
||||||
|
|
||||||
- [Bun official docs](https://bun.com/docs) -- bun:sqlite features, runtime capabilities (HIGH confidence)
|
- [Drizzle ORM Filter Operators](https://orm.drizzle.team/docs/operators) -- `like`, `eq`, `and`, `or` operators for search/filter (HIGH confidence)
|
||||||
- [Hono official docs](https://hono.dev/docs) -- Bun integration, static serving (HIGH confidence)
|
- [Drizzle ORM Conditional Filters Guide](https://orm.drizzle.team/docs/guides/conditional-filters-in-query) -- dynamic filter composition pattern (HIGH confidence)
|
||||||
- [Drizzle ORM docs - Bun SQLite](https://orm.drizzle.team/docs/connect-bun-sqlite) -- driver support verified (HIGH confidence)
|
- [react-minimal-pie-chart GitHub](https://github.com/toomuchdesign/react-minimal-pie-chart) -- version 9.1.2, React 19 peerDeps confirmed (HIGH confidence)
|
||||||
- [Vite releases](https://vite.dev/releases) -- v8.0 with Rolldown confirmed (HIGH confidence)
|
- [react-minimal-pie-chart package.json](https://github.com/toomuchdesign/react-minimal-pie-chart/blob/master/package.json) -- React 19 in peerDependencies and devDependencies (HIGH confidence)
|
||||||
- [Tailwind CSS v4.2 blog](https://tailwindcss.com/blog/tailwindcss-v4) -- CSS-native config, Vite plugin (HIGH confidence)
|
- [Recharts npm](https://www.npmjs.com/package/recharts) -- v3.8.0, ~97kB bundle (HIGH confidence)
|
||||||
- [TanStack Router docs](https://tanstack.com/router/latest) -- v1.167.x confirmed (HIGH confidence)
|
- [Recharts React 19 issue #6857](https://github.com/recharts/recharts/issues/6857) -- rendering issues reported with React 19.2.3 (MEDIUM confidence -- may be project-specific)
|
||||||
- [TanStack Query docs](https://tanstack.com/query/latest) -- v5.93.x for React (HIGH confidence)
|
- [LighterPack weight classification model](https://lighterpack.com) -- base/worn/consumable terminology is industry standard for gear management (HIGH confidence)
|
||||||
- [Zustand npm](https://www.npmjs.com/package/zustand) -- v5.0.x confirmed (HIGH confidence)
|
- [Pack Weight Calculator Guide](https://backpackpeek.com/blog/pack-weight-calculator-base-weight-guide) -- weight classification definitions (HIGH confidence)
|
||||||
- [Zod v4 release notes](https://zod.dev/v4) -- v4.3.x confirmed (MEDIUM confidence -- verify @hono/zod-validator compatibility)
|
- [SQLite LIKE case sensitivity note](https://github.com/drizzle-team/drizzle-orm-docs/issues/239) -- LIKE is case-insensitive in SQLite, no need for ilike (MEDIUM confidence)
|
||||||
- [React versions](https://react.dev/versions) -- v19.2.x confirmed (HIGH confidence)
|
|
||||||
- [Bun SQLite vs better-sqlite3 benchmarks](https://bun.com/docs/runtime/sqlite) -- 3-6x performance advantage (HIGH confidence)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
*Stack research for: GearBox -- gear management and purchase planning web app*
|
*Stack research for: GearBox v1.2 -- Collection Power-Ups*
|
||||||
*Researched: 2026-03-14*
|
*Researched: 2026-03-16*
|
||||||
|
|||||||
@@ -1,243 +1,208 @@
|
|||||||
# Project Research Summary
|
# Project Research Summary
|
||||||
|
|
||||||
**Project:** GearBox
|
**Project:** GearBox v1.2 -- Collection Power-Ups
|
||||||
**Domain:** Single-user gear management and purchase planning web app
|
**Domain:** Gear management (bikepacking, sim racing, etc.) -- feature enhancement milestone
|
||||||
**Researched:** 2026-03-14
|
**Researched:** 2026-03-16
|
||||||
**Confidence:** HIGH
|
**Confidence:** HIGH
|
||||||
|
|
||||||
## Executive Summary
|
## Executive Summary
|
||||||
|
|
||||||
GearBox is a single-user personal gear management app with a critical differentiator: purchase planning threads. Every competitor (LighterPack, GearGrams, Packstack, Hikt) is a post-purchase inventory tool — they help you track what you own. GearBox closes the loop by adding a structured pre-purchase research workflow where users compare candidates, track research status, and resolve threads by promoting winners into their collection. This is the entire reason to build the product; the collection management side is table stakes, and the purchase planning threads are the moat. Research strongly recommends building both together in the v1 scope, not sequencing them separately, because the thread resolution workflow only becomes compelling once a real collection exists to reference.
|
GearBox v1.2 adds six features to the existing gear management app: item search/filter, weight classification (base/worn/consumable), weight distribution charts, candidate status tracking, weight unit selection, and a planning category filter upgrade. Research confirms that four of six features require zero new dependencies -- they are pure application logic built on the existing stack (Drizzle ORM, React Query, Zod, Tailwind). The sole new dependency is `react-minimal-pie-chart` (~2kB gzipped) for donut chart visualization. The codebase is well-positioned for these additions: the settings table already supports key-value preferences, the `setup_items` join table is the correct place for weight classification, and the client-side data model is small enough for in-memory filtering.
|
||||||
|
|
||||||
The recommended architecture is a single-process Bun fullstack monolith: Hono for the API layer, React 19 + Vite 8 for the frontend, Drizzle ORM + bun:sqlite for the database, TanStack Router + TanStack Query for client navigation and server state, and Tailwind CSS v4 for styling. This stack is purpose-built for the constraints: Bun is a project requirement, SQLite is optimal for single-user, and every tool in the list has zero or near-zero runtime overhead. Zustand handles the small amount of client-only UI state. The entire stack is type-safe end-to-end through Zod schemas shared between client and server.
|
The recommended approach is to build weight unit selection first because it refactors the `formatWeight` function that every subsequent feature depends on for display. Search/filter and candidate status tracking are independent and low-risk. Weight classification is the most architecturally significant change -- it adds a column to the `setup_items` join table and changes the sync API shape from `{ itemIds: number[] }` to `{ items: Array<{ itemId, weightClass }> }`. Weight distribution charts come last because they depend on both the unit formatter and the classification data. The two schema changes (columns on `setup_items` and `thread_candidates`) should be batched into a single Drizzle migration.
|
||||||
|
|
||||||
The biggest risks are front-loaded in Phase 1: unit handling (weights must be canonicalized to grams from day one), currency precision (prices must be stored as integer cents), category flexibility (must use user-defined tags, not a hardcoded hierarchy), and image storage strategy (relative paths to a local directory, never BLOBs for full-size, never absolute paths). Getting these wrong requires painful data migrations later. The second major risk is the thread state machine in Phase 2 — the combination of candidate status, thread lifecycle, and "move winner to collection" creates a stateful flow that must be modeled as an explicit state machine with transactional resolution, not assembled incrementally.
|
The primary risks are: (1) weight unit conversion rounding drift from bidirectional conversion in edit forms, (2) accidentally placing weight classification on the `items` table instead of the `setup_items` join table, and (3) chart data diverging from displayed totals due to separate computation paths. All three are preventable with clear architectural rules established in the first phase: store grams canonically, convert only at the display boundary, and use a single source of truth for weight computations.
|
||||||
|
|
||||||
## Key Findings
|
## Key Findings
|
||||||
|
|
||||||
### Recommended Stack
|
### Recommended Stack
|
||||||
|
|
||||||
The stack is a tightly integrated Bun-native toolchain with no redundant tools. Bun serves as runtime, package manager, test runner, and provides built-in SQLite — eliminating entire categories of infrastructure. Vite 8 (Rolldown-based, 5-30x faster than Vite 7) handles the dev server and production frontend builds. The client-server boundary is clean: Hono serves the API, React handles the UI, and Zod schemas in a `shared/` directory provide a single source of truth for data shapes on both sides.
|
The existing stack (React 19, Hono, Drizzle ORM, SQLite, Bun) handles all v1.2 features without modification. One small library addition is needed.
|
||||||
|
|
||||||
The architecture note in STACK.md suggests Bun's fullstack HTML-based routing (not Vite's dev server proxy pattern). This differs slightly from the standard Vite proxy setup: each page is a separate HTML entrypoint imported into `Bun.serve()`, and TanStack Router handles in-page client-side navigation only. This simplifies the development setup to a single `bun run` command with no proxy configuration.
|
**Core technologies (all existing, no changes):**
|
||||||
|
- **Drizzle ORM `like()`, `eq()`, `and()`**: Available for server-side filtering if needed in the future, but client-side filtering is preferred at this scale
|
||||||
|
- **Zod `z.enum()`**: Validates weight classification (`"base" | "worn" | "consumable"`) and candidate status (`"researching" | "ordered" | "arrived"`) with compile-time type safety
|
||||||
|
- **React Query `useSetting()`**: Reactive settings caching ensures unit preference changes propagate to all weight displays without page refresh
|
||||||
|
- **Existing `settings` table**: Key-value store supports weight unit preference with no schema change
|
||||||
|
|
||||||
**Core technologies:**
|
**New dependency:**
|
||||||
- Bun 1.3.x: Runtime, package manager, test runner, bundler — eliminates Node.js and npm
|
- **react-minimal-pie-chart ^9.1.2**: Donut/pie charts at ~2kB gzipped. React 19 compatible (explicit in peerDeps). Zero external dependencies. TypeScript native. Chosen over Recharts (~97kB, React 19 rendering issues reported) and Chart.js (~60kB, canvas-based, harder to style with Tailwind).
|
||||||
- React 19.2.x + Vite 8.x: SPA framework + dev server — stable, large ecosystem, HMR out of the box
|
|
||||||
- Hono 4.12.x: API layer — Web Standards based, first-class Bun support, ~12kB, faster than Express on Bun
|
|
||||||
- SQLite (bun:sqlite) + Drizzle ORM 0.45.x: Database — zero-dependency, built into Bun, type-safe queries and migrations
|
|
||||||
- TanStack Router 1.167.x + TanStack Query 5.93.x: Routing + server state — full type-safe routing, automatic cache invalidation
|
|
||||||
- Tailwind CSS 4.2.x: Styling — CSS-native config, no JS file, microsecond incremental builds
|
|
||||||
- Zustand 5.x: Client UI state — minimal boilerplate for filter state, modals, theme
|
|
||||||
- Zod 4.3.x: Schema validation — shared between client and server as single source of truth for types
|
|
||||||
- Biome: Linting + formatting — replaces ESLint + Prettier, Rust-based, near-zero config
|
|
||||||
|
|
||||||
**Version flag:** Verify that `@hono/zod-validator` supports Zod 4.x before starting. If not, pin Zod 3.23.x until the validator is updated.
|
**What NOT to add:**
|
||||||
|
- Recharts, Chart.js, or visx (massive overkill for one chart type)
|
||||||
|
- Fuse.js or FTS5 (overkill for name search on sub-1000 item collections)
|
||||||
|
- XState (candidate status is a simple enum, not a complex state machine)
|
||||||
|
- i18n library for unit conversion (four constants and a formatter function)
|
||||||
|
|
||||||
### Expected Features
|
### Expected Features
|
||||||
|
|
||||||
The feature research distinguishes cleanly between what every gear app does (table stakes) and what GearBox uniquely does (purchase planning threads). No competitor has threads, candidate comparison, or thread resolution. This is the entire competitive surface. Everything else is hygiene.
|
**Must have (table stakes):**
|
||||||
|
- **Search items by name** -- every competitor with an inventory has search; LighterPack notably lacks it and users complain
|
||||||
|
- **Filter items by category** -- partially exists in planning view, missing from collection view
|
||||||
|
- **Weight unit selection (g/oz/lb/kg)** -- universal across all competitors; gear specs come in mixed units
|
||||||
|
- **Weight classification (base/worn/consumable)** -- pioneered by LighterPack, now industry standard; "base weight" is the core metric of the ultralight community
|
||||||
|
|
||||||
**Must have (table stakes) — v1 launch:**
|
**Should have (differentiators):**
|
||||||
- Item CRUD with weight, price, category, notes, product URL — minimum unit of value
|
- **Weight distribution donut chart** -- LighterPack's pie chart is cited as its best feature; GearBox can uniquely combine category and classification breakdown
|
||||||
- User-defined categories/tags — must be flexible, not a hardcoded hierarchy
|
- **Candidate status tracking (researching/ordered/arrived)** -- entirely unique to GearBox's planning thread concept; no competitor has purchase lifecycle tracking
|
||||||
- Weight unit support (g, oz, lb, kg) — gear community requires this; store canonical grams internally
|
- **Per-setup classification** -- architecturally superior to competitors; the same item can be classified differently across setups
|
||||||
- Automatic weight/cost totals by category and setup — the reason to use an app over a text file
|
|
||||||
- Named setups composed from collection items — compose loadouts, get aggregate totals
|
|
||||||
- Planning threads with candidate items — the core differentiator
|
|
||||||
- Side-by-side candidate comparison with deltas (not just raw values) — the payoff of threads
|
|
||||||
- Thread resolution: pick winner, move to collection — closes the purchase research loop
|
|
||||||
- Search and filter on collection — essential at 30+ items
|
|
||||||
- Dashboard home page — clean entry point per project constraints
|
|
||||||
|
|
||||||
**Should have (competitive) — v1.x after validation:**
|
**Defer (v2+):**
|
||||||
- Impact preview: how a thread candidate changes a specific setup's weight and cost
|
- Per-item weight input in multiple units (parsing complexity)
|
||||||
- Status tracking on thread items (researching / ordered / arrived)
|
- Interactive chart drill-down (click to zoom into categories)
|
||||||
- Priority/ranking within threads
|
- Weight goals/targets (opinionated norms conflict with hobby-agnostic design)
|
||||||
- Photos per item (one photo per item initially)
|
- Custom weight classification labels beyond base/worn/consumable
|
||||||
- CSV import/export — migration path from spreadsheets, data portability
|
- Server-side full-text search (premature for single-user scale)
|
||||||
- Weight distribution visualization (pie/bar chart by category)
|
- Status change timestamps on candidates (useful but not essential now)
|
||||||
|
|
||||||
**Defer — v2+:**
|
|
||||||
- Multi-photo gallery per item
|
|
||||||
- Shareable read-only links for setups
|
|
||||||
- Drag-and-drop reordering
|
|
||||||
- Bulk operations (multi-select, bulk delete)
|
|
||||||
- Dark mode
|
|
||||||
- Item history/changelog
|
|
||||||
|
|
||||||
### Architecture Approach
|
### Architecture Approach
|
||||||
|
|
||||||
The architecture is a monolithic Bun process with a clear 4-layer structure: API routes (HTTP concerns), service layer (business logic and calculations), Drizzle ORM (type-safe data access), and bun:sqlite (embedded storage). There are no microservices, no Docker, no external database server. The client is a React SPA served as static files by the same Bun process. Internal communication is REST + JSON; no WebSockets needed. The data model has three primary entities — items, threads (with candidates), and setups — connected by explicit foreign keys and a junction table for the many-to-many setup-to-items relationship.
|
All v1.2 features integrate into the existing three-layer architecture (client/server/database) with minimal structural changes. The client layer gains 5 new files (SearchBar, WeightChart, UnitSelector components; useFormatWeight hook; migration SQL) and modifies 15 existing files. The server layer changes are limited to the setup service (weight classification PATCH endpoint, updated sync function) and thread service (candidate status field passthrough). No new route registrations are needed in `src/server/index.ts`. The API layer (`lib/api.ts`) and UI state store (`uiStore.ts`) require no changes.
|
||||||
|
|
||||||
**Major components:**
|
**Major components:**
|
||||||
1. Collection (items): Core entity. Source of truth for owned gear. Every other feature references items.
|
1. **`useFormatWeight` hook** -- single source of truth for unit-aware weight formatting; wraps `useSetting("weightUnit")` and `formatWeight(grams, unit)` so all weight displays stay consistent
|
||||||
2. Planning Threads (threads + candidates): Pre-purchase research. Thread lifecycle is a state machine; resolution is transactional.
|
2. **`WeightChart` component** -- reusable donut chart wrapper; used in collection page (weight by category) and setup detail page (weight by classification)
|
||||||
3. Setups: Named loadouts composed from collection items. Totals are always computed live from item data, never cached.
|
3. **`SearchBar` component** -- reusable search input with clear button; collection page filters via `useMemo` over the cached `useItems()` data
|
||||||
4. Service Layer: Business logic isolated from HTTP concerns. Enables testing without HTTP mocking. Key: `calculateSetupTotals()`, `computeCandidateImpact()`.
|
4. **Updated `syncSetupItems`** -- breaking API change from `{ itemIds: number[] }` to `{ items: Array<{ itemId, weightClass }> }`; single call site (ItemPicker.tsx) makes this safe
|
||||||
5. Dashboard: Read-only aggregation. Built last since it reads from all other entities.
|
5. **`PATCH /api/setups/:id/items/:itemId`** -- new endpoint for updating weight classification without triggering full sync (which would destroy classification data)
|
||||||
6. Image Storage: Filesystem (`./uploads/` or `data/images/{item-id}/`) with relative paths in DB. Thumbnails on upload.
|
|
||||||
|
|
||||||
**Build order from ARCHITECTURE.md (follow this):**
|
|
||||||
1. Database schema (Drizzle) — everything depends on this
|
|
||||||
2. Items API (CRUD) — the core entity
|
|
||||||
3. Collection UI — first visible feature, validates end-to-end
|
|
||||||
4. Threads + candidates API and UI — depends on items for resolution
|
|
||||||
5. Setups API and UI — depends on items for composition
|
|
||||||
6. Dashboard — aggregates from all entities, build last
|
|
||||||
7. Polish: image upload, impact calculations, status tracking
|
|
||||||
|
|
||||||
### Critical Pitfalls
|
### Critical Pitfalls
|
||||||
|
|
||||||
1. **Unit handling treated as display-only** — Store all weights as canonical grams at write time. Accept any unit as input, convert on save. Build a `weightToGrams(value, unit)` utility on day one. A bare number field with no unit tracking will silently corrupt all aggregates when users paste specs in mixed units.
|
1. **Weight unit conversion rounding drift** -- bidirectional conversion in edit forms causes grams to drift over multiple edit cycles. Always load stored grams from the API, convert for display, and convert user input back to grams once on save. Never re-convert from a previously displayed value.
|
||||||
|
|
||||||
2. **Rigid category hierarchy** — Use user-defined flat tags, not a hardcoded category tree. A `categories` table with `parent_id` foreign keys will fail the moment a user tries to track sim racing gear or photography equipment. Tags allow many-to-many, support any hobby, and do not require schema changes to add a new domain.
|
2. **Weight classification at the wrong level** -- placing `classification` on the `items` table instead of `setup_items` prevents per-setup classification. A rain jacket is "worn" in summer but "base weight" in winter. This is the single most important schema decision in v1.2 and is costly to reverse.
|
||||||
|
|
||||||
3. **Thread state machine complexity** — Model the thread lifecycle as an explicit state machine before writing any code. Document valid transitions. The "resolve thread" action must be a single atomic transaction: validate winner exists, create collection item, mark thread resolved, update candidate statuses. Without this, impossible states (resolved thread with active candidates, ghost items in collection) accumulate silently.
|
3. **Chart data diverging from displayed totals** -- the codebase already has two computation paths (SQL aggregates in `totals.service.ts` vs. JavaScript reduce in `$setupId.tsx`). Adding charts creates a third. Use a shared utility for weight summation and convert units only at the final display step.
|
||||||
|
|
||||||
4. **Setup totals cached in the database** — Never store `totalWeight` or `totalCost` on a setup record. Always compute from live item data via `SUM()`. Cached totals go stale the moment any member item is edited, and the bugs are subtle (the UI shows a total that doesn't match the items).
|
4. **Server-side search for client-side data** -- adding search API parameters creates React Query cache fragmentation and unnecessary latency. Keep filtering client-side with `useMemo` over the cached items array.
|
||||||
|
|
||||||
5. **Comparison view that displays data but doesn't aid decisions** — The comparison view must show deltas between candidates and against the item being replaced from the collection, not just raw values side by side. Color-code lighter/heavier, cheaper/more expensive. A comparison table with no computed differences is worse than a spreadsheet.
|
5. **Test helper desync with schema** -- the manual `createTestDb()` in `tests/helpers/db.ts` duplicates schema in raw SQL. Every column addition must be mirrored there or tests pass against the wrong schema.
|
||||||
|
|
||||||
**Additional high-priority pitfalls to address per phase:**
|
|
||||||
- Currency stored as floats (use integer cents always)
|
|
||||||
- Image paths stored as absolute paths or as BLOBs for full-size images
|
|
||||||
- Thread resolution is destructive (archive threads, don't delete them — users need to reference why they chose X over Y)
|
|
||||||
- Item deletion without setup impact warning
|
|
||||||
|
|
||||||
## Implications for Roadmap
|
## Implications for Roadmap
|
||||||
|
|
||||||
Based on the combined research, a 5-phase structure is recommended. Phases 1-3 deliver the v1 MVP; Phases 4-5 deliver the v1.x feature set.
|
Based on combined research, a 5-phase structure is recommended:
|
||||||
|
|
||||||
### Phase 1: Foundation — Data Model, Infrastructure, Core Item CRUD
|
### Phase 1: Weight Unit Selection
|
||||||
|
|
||||||
**Rationale:** Everything depends on getting the data model right. Unit handling, currency precision, category flexibility, image storage strategy, and the items schema are all Phase 1 decisions. Getting these wrong requires expensive data migrations. The architecture research explicitly states: "Database schema + Drizzle setup — Everything depends on the data model." The pitfalls research agrees: 6 of 9 pitfalls have "Phase 1" as their prevention phase.
|
**Rationale:** Foundational infrastructure. The `formatWeight` refactor touches every component that displays weight (~8 call sites). All subsequent features depend on this formatter working correctly with unit awareness. Building this first means classification totals, chart labels, and setup breakdowns automatically display in the user's preferred unit.
|
||||||
|
|
||||||
**Delivers:** Working gear catalog — users can add, edit, delete, and browse their collection. Item CRUD with all core fields. Weight unit conversion. User-defined categories. Image upload with thumbnail generation and cleanup on delete. SQLite database with WAL mode enabled, automatic backup mechanism, and all schemas finalized.
|
**Delivers:** Global weight unit preference (g/oz/lb/kg) stored in settings, `useFormatWeight` hook, updated `formatWeight` function, UnitSelector component in TotalsBar, correct unit display across all existing weight surfaces (ItemCard, CandidateCard, CategoryHeader, TotalsBar, setup detail), correct unit handling in ItemForm and CandidateForm weight inputs.
|
||||||
|
|
||||||
**Features from FEATURES.md:** Item CRUD with core fields, user-defined categories, weight unit support (g/oz/lb/kg), notes and product URL fields, search and filter.
|
**Addresses:** Weight unit selection (table stakes from FEATURES.md)
|
||||||
|
|
||||||
**Pitfalls to prevent:** Unit handling (canonical grams), currency precision (integer cents), category flexibility (user-defined tags, no hierarchy), image storage (relative paths, thumbnails), data loss prevention (WAL mode, auto-backup mechanism).
|
**Avoids:** Rounding drift (Pitfall 1), inconsistent unit application (Pitfall 7), flash of unconverted weights on load
|
||||||
|
|
||||||
**Research flag:** Standard patterns. Schema design for inventory apps is well-documented. No research phase needed.
|
**Schema changes:** None (uses existing settings table key-value store)
|
||||||
|
|
||||||
---
|
### Phase 2: Search, Filter, and Planning Category Filter
|
||||||
|
|
||||||
### Phase 2: Planning Threads — The Core Differentiator
|
**Rationale:** Pure client-side addition with no schema changes, no API changes, and no dependencies on other v1.2 features. Immediately useful as collections grow. The planning category filter upgrade fits naturally here since both involve filter UX and the icon-aware dropdown is a shared component.
|
||||||
|
|
||||||
**Rationale:** Threads are why GearBox exists. The feature dependency graph in FEATURES.md shows threads require items to exist (to resolve candidates into the collection), which is why Phase 1 must complete first. The thread state machine is the most complex feature in the product and gets its own phase to ensure the state transitions are modeled correctly before any UI is built.
|
**Delivers:** Search input in collection view, icon-aware category filter dropdown (reused in gear and planning tabs), filtered item display with count ("showing 12 of 47 items"), URL search param persistence, empty state for no results, result count display.
|
||||||
|
|
||||||
**Delivers:** Complete purchase planning workflow — create threads, add candidates with weight/price/notes, compare candidates side-by-side with weight/cost deltas (not just raw values), resolve threads by selecting a winner and moving it to the collection, archive resolved threads.
|
**Addresses:** Search items by name (table stakes), filter by category (table stakes), planning category filter upgrade (differentiator)
|
||||||
|
|
||||||
**Features from FEATURES.md:** Planning threads, side-by-side candidate comparison (with deltas), thread resolution workflow. Does not include status tracking (researching/ordered/arrived) or priority/ranking — those are v1.x.
|
**Avoids:** Server-side search anti-pattern (Pitfall 3), search state lost on tab switch (UX pitfall), category groups disappearing incorrectly during filtering
|
||||||
|
|
||||||
**Pitfalls to prevent:** Thread state machine complexity (model transitions explicitly, transactional resolution), comparison usefulness (show deltas and impact, not just raw data), thread archiving (never destructive resolution).
|
**Schema changes:** None
|
||||||
|
|
||||||
**Research flag:** Needs careful design work before coding. The state machine for thread lifecycle (open -> in-progress -> resolved/cancelled) combined with candidate status (researching / ordered / arrived) and the resolution side-effect (create collection item) has no off-the-shelf reference implementation. Design the state diagram first.
|
### Phase 3: Candidate Status Tracking
|
||||||
|
|
||||||
---
|
**Rationale:** Simple schema change on `thread_candidates` with minimal integration surface. Independent of other features. Low complexity but requires awareness of the existing thread resolution flow. Schema change should be batched with Phase 4 into one Drizzle migration.
|
||||||
|
|
||||||
### Phase 3: Setups — Named Loadouts and Composition
|
**Delivers:** Status column on candidates (researching/ordered/arrived), status badge on CandidateCard with click-to-cycle, status field in CandidateForm, Zod enum validation, status transition validation in service layer (researching -> ordered -> arrived, no backward transitions).
|
||||||
|
|
||||||
**Rationale:** Setups require items to exist (Phase 1) and benefit from threads being stable (Phase 2) because thread resolution can affect setup membership (the replaced item should be updatable in setups). The many-to-many setup-items relationship and the setup integrity pitfall require careful foreign key design.
|
**Addresses:** Candidate status tracking (differentiator -- unique to GearBox)
|
||||||
|
|
||||||
**Delivers:** Named setups composed from collection items. Weight and cost totals computed live (never cached). Base/worn/consumable weight classification per item per setup. Category weight breakdown. Item deletion warns about setup membership. Visual indicator when a setup item is no longer in the collection.
|
**Avoids:** Status without transition validation (Pitfall 4), test helper desync (Pitfall 6), not handling candidate status during thread resolution
|
||||||
|
|
||||||
**Features from FEATURES.md:** Named setups with item selection and totals, setup weight/cost breakdown by category, automatic totals.
|
**Schema changes:** Add `status TEXT NOT NULL DEFAULT 'researching'` to `thread_candidates`
|
||||||
|
|
||||||
**Pitfalls to prevent:** Setup totals cached in DB (always compute live), setup composition breaks on collection changes (explicit `ON DELETE` behavior, visual indicators for missing items, no silent CASCADE).
|
### Phase 4: Weight Classification
|
||||||
|
|
||||||
**Research flag:** Standard patterns for junction table composition. No research phase needed for the setup-items relationship. The weight classification (base/worn/consumable) per setup entry is worth a design session — this is per-setup metadata on the junction, not a property of the item itself.
|
**Rationale:** Most architecturally significant change in v1.2. Changes the sync API shape (breaking change, single call site). Requires Phase 1 to be complete so classification totals display in the correct unit. Schema migration should be batched with Phase 3.
|
||||||
|
|
||||||
---
|
**Delivers:** `weightClass` column on `setup_items`, updated sync endpoint accepting `{ items: Array<{ itemId, weightClass }> }`, new `PATCH /api/setups/:id/items/:itemId` endpoint, three-segment classification toggle per item in setup detail view, base/worn/consumable weight subtotals.
|
||||||
|
|
||||||
### Phase 4: Dashboard and Polish
|
**Addresses:** Weight classification base/worn/consumable (table stakes), per-setup classification (differentiator)
|
||||||
|
|
||||||
**Rationale:** The architecture research explicitly states "Dashboard — aggregates stats from all other entities. Build last since it reads from everything." Dashboard requires all prior phases to be stable since it reads from items, threads, and setups simultaneously. This phase also adds the weight visualization chart that requires a full dataset to be meaningful.
|
**Avoids:** Classification on items table (Pitfall 2), test helper desync (Pitfall 6), losing classification data on sync
|
||||||
|
|
||||||
**Delivers:** Dashboard home page with summary cards (item count, active threads, setup count, collection value). Weight distribution visualization (pie/bar chart by category). Dashboard stats endpoint (`/api/stats`) as a read-only aggregation. General UI polish for the "light, airy, minimalist" aesthetic.
|
**Schema changes:** Add `weight_class TEXT NOT NULL DEFAULT 'base'` to `setup_items`
|
||||||
|
|
||||||
**Features from FEATURES.md:** Dashboard home page, weight distribution visualization.
|
### Phase 5: Weight Distribution Charts
|
||||||
|
|
||||||
**Research flag:** Standard patterns. Dashboard aggregation is a straightforward read-only endpoint. Charting is well-documented. No research phase needed.
|
**Rationale:** Depends on Phase 1 (unit-aware labels) and Phase 4 (classification data for setup breakdown). Only phase requiring a new npm dependency. Highest UI complexity but lowest architectural risk -- read-only visualization of existing data.
|
||||||
|
|
||||||
---
|
**Delivers:** `react-minimal-pie-chart` integration, `WeightChart` component, collection-level donut chart (weight by category from `useTotals()`), setup-level donut chart (weight by classification), chart legend with consistent colors, hover tooltips with formatted weights.
|
||||||
|
|
||||||
### Phase 5: v1.x Enhancements
|
**Addresses:** Weight distribution visualization (differentiator)
|
||||||
|
|
||||||
**Rationale:** These features add significant value but depend on the core (Phases 1-3) being proven out. Impact preview requires both stable setups and stable threads. CSV import/export validates the data model is clean (if import is buggy, the model has problems). Photos add storage complexity that is easier to handle once the core CRUD flow is solid.
|
**Avoids:** Chart/totals divergence (Pitfall 5), chart crashing on null-weight items, unnecessary chart re-renders on unrelated state changes
|
||||||
|
|
||||||
**Delivers:** Impact preview (how a thread candidate changes a specific setup's weight/cost). Thread item status tracking (researching / ordered / arrived). Priority/ranking within threads. Photos per item (upload, display, cleanup). CSV import/export with unit detection.
|
**Schema changes:** None (npm dependency: `bun add react-minimal-pie-chart`)
|
||||||
|
|
||||||
**Features from FEATURES.md:** Impact preview, status tracking, priority/ranking, photos per item, CSV import/export.
|
|
||||||
|
|
||||||
**Pitfalls to prevent:** CSV import missing unit conversion (must detect and convert oz/lb/kg to grams on import). Image uploads without size/type validation. Product URLs not sanitized (validate http/https protocol, render with `rel="noopener noreferrer"`).
|
|
||||||
|
|
||||||
**Research flag:** CSV import with unit detection may need a design pass — handling "5 oz", "142g", "0.3 lb" in the same weight column requires a parsing strategy. Worth a short research spike before implementation.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Phase Ordering Rationale
|
### Phase Ordering Rationale
|
||||||
|
|
||||||
- **Data model first:** Six of nine pitfalls identified are Phase 1 prevention items. The schema is the hardest thing to change later and the most consequential.
|
- **Phase 1 first** because `formatWeight` is called by every weight-displaying component. Refactoring it after other features are built means touching the same files twice.
|
||||||
- **Threads before setups:** Thread resolution creates collection items; setup composition consumes them. But more importantly, threads are the differentiating feature — proving the thread workflow works is more valuable than setups.
|
- **Phase 2 is independent** and could be built in any order, but sequencing it second allows the team to ship a quick win while Phase 3/4 schema changes are designed.
|
||||||
- **Dashboard last:** Explicitly recommended by architecture research. Aggregating from incomplete entities produces misleading data and masks bugs.
|
- **Batch Phase 3 + Phase 4 schema migrations** into one `bun run db:generate` run. Both add columns to existing tables; a single migration simplifies deployment.
|
||||||
- **Impact preview in Phase 5:** This feature requires both stable setups (Phase 3) and stable threads (Phase 2). Building it before both are solid means rebuilding it when either changes.
|
- **Phase 4 after Phase 1** because classification totals need the unit-aware formatter.
|
||||||
- **Photos deferred to Phase 5:** The core value proposition is weight/cost tracking and purchase planning, not a photo gallery. Adding photo infrastructure in Phase 1 increases scope without validating the core concept.
|
- **Phase 5 last** because it is pure visualization depending on data from Phases 1 and 4, and introduces the only external dependency.
|
||||||
|
|
||||||
### Research Flags
|
### Research Flags
|
||||||
|
|
||||||
**Needs design/research before coding:**
|
Phases likely needing deeper research during planning:
|
||||||
- **Phase 2 (Thread State Machine):** Design the state diagram for thread lifecycle x candidate status before writing any code. Define all valid transitions and invalid states explicitly. This is the most stateful feature in the product and has no off-the-shelf pattern to follow.
|
- **Phase 4 (Weight Classification):** The sync API shape change is breaking. The existing delete-all/re-insert pattern destroys classification data. Needs careful design of the PATCH endpoint and how ItemPicker interacts with classification preservation during item add/remove. Worth a `/gsd:research-phase`.
|
||||||
- **Phase 5 (CSV Import):** Design the column-mapping and unit-detection strategy before implementation. The spreadsheet-to-app migration workflow is critical for the target audience (users migrating from gear spreadsheets).
|
- **Phase 5 (Weight Distribution Charts):** react-minimal-pie-chart API specifics (label rendering, responsive sizing, animation control) should be validated with a quick prototype. Consider a short research spike.
|
||||||
|
|
||||||
**Standard patterns — no research phase needed:**
|
Phases with standard patterns (skip research-phase):
|
||||||
- **Phase 1 (Data model + CRUD):** Schema design for inventory apps is well-documented. Drizzle + bun:sqlite patterns are covered in official docs.
|
- **Phase 1 (Weight Unit Selection):** Well-documented pattern. Extend `formatWeight`, add a `useSetting` wrapper, propagate through components. No unknowns.
|
||||||
- **Phase 3 (Setups):** Junction table composition is a standard relational pattern. Foreign key behavior for integrity is documented.
|
- **Phase 2 (Search/Filter):** Textbook client-side filtering with `useMemo`. No API changes. Standard React pattern.
|
||||||
- **Phase 4 (Dashboard):** Aggregation endpoints and charting are standard. No novel patterns.
|
- **Phase 3 (Candidate Status):** Simple column addition with Zod enum validation. Existing `useUpdateCandidate` mutation already handles partial updates.
|
||||||
|
|
||||||
## Confidence Assessment
|
## Confidence Assessment
|
||||||
|
|
||||||
| Area | Confidence | Notes |
|
| Area | Confidence | Notes |
|
||||||
|------|------------|-------|
|
|------|------------|-------|
|
||||||
| Stack | HIGH | All technologies verified against official docs. Version compatibility confirmed. One flag: verify `@hono/zod-validator` supports Zod 4.x before starting. |
|
| Stack | HIGH | Only one new dependency (react-minimal-pie-chart). React 19 compatibility verified via package.json peerDeps. All other features use existing stack with no changes. |
|
||||||
| Features | HIGH | Competitor analysis is thorough (LighterPack, GearGrams, Packstack, Hikt all compared). Feature gaps and differentiators are clearly identified. |
|
| Features | HIGH | Feature set derived from analysis of 8+ competing tools (LighterPack, Hikt, PackLight, Packstack, HikeLite, Packrat, OutPack, BPL Calculator). Clear consensus on table stakes vs. differentiators. |
|
||||||
| Architecture | HIGH | Bun fullstack monolith pattern is official and well-documented. Service layer and data flow patterns are standard. |
|
| Architecture | HIGH | Based on direct codebase analysis with integration points mapped to specific files. The 5 new / 15 modified file inventory is concrete and verified against the existing codebase. |
|
||||||
| Pitfalls | HIGH | Pitfalls are domain-specific and well-sourced. SQLite BLOB guidance from official SQLite docs. Comparison UX from NN/g. Unit conversion antipatterns documented. |
|
| Pitfalls | HIGH | Derived from codebase-specific patterns (test helper duplication, dual computation paths) combined with domain risks (unit conversion rounding, classification scope). Not generic warnings. |
|
||||||
|
|
||||||
**Overall confidence: HIGH**
|
**Overall confidence:** HIGH
|
||||||
|
|
||||||
### Gaps to Address
|
### Gaps to Address
|
||||||
|
|
||||||
- **Zod 4 / @hono/zod-validator compatibility:** STACK.md flags this explicitly. Verify before starting. If incompatible, pin Zod 3.23.x. This is a quick check, not a blocker.
|
- **`lb` display format:** FEATURES.md suggests "2 lb 3 oz" (pounds + remainder ounces) while STACK.md suggests simpler decimal format. The traditional "lb + oz" format is more useful to American users but adds formatting complexity. Decide during Phase 1 implementation.
|
||||||
|
- **Status change timestamps:** PITFALLS.md recommends storing `statusChangedAt` alongside `status` for staleness detection ("ordered 30 days ago -- still waiting?"). Low effort to add during the schema migration. Decide during Phase 3 planning.
|
||||||
- **Bun fullstack vs. Vite proxy setup:** STACK.md describes the Vite dev server proxy pattern (standard approach), while ARCHITECTURE.md describes Bun's HTML-based routing with `Bun.serve()` (newer approach). These are two valid patterns. The architecture file's approach (Bun fullstack) is simpler for production deployment. Confirm which pattern to follow before project setup — they require different `vite.config.ts` and entry point structures.
|
- **Sync API backward compatibility:** The sync endpoint shape changes from `{ itemIds: number[] }` to `{ items: [...] }`. Single call site (ItemPicker.tsx), but verify no external consumers exist before shipping.
|
||||||
|
- **react-minimal-pie-chart responsive behavior:** SVG-based and should handle responsive sizing, but exact approach (CSS width vs. explicit size prop) should be validated in Phase 5. Not a risk, just a detail to confirm.
|
||||||
- **Weight classification (base/worn/consumable) data model:** Where does this live? On the `setup_items` junction table (per-setup classification, same item can be "base" in one setup and "worn" in another) or on the item itself (one classification for all setups)? The per-setup model is more flexible but more complex. Decide in Phase 1 schema design, not Phase 3 when setups are built.
|
|
||||||
|
|
||||||
- **Tag vs. single-category field:** PITFALLS.md recommends a flat tag system. FEATURES.md implies a single "category" field. The right answer is probably a single optional category field (for broad grouping, e.g., "clothing") plus user-defined tags for fine-grained organization. Confirm the data model in Phase 1.
|
|
||||||
|
|
||||||
## Sources
|
## Sources
|
||||||
|
|
||||||
### Primary (HIGH confidence)
|
### Primary (HIGH confidence)
|
||||||
- [Bun official docs](https://bun.com/docs) — bun:sqlite, fullstack dev server, Bun.serve() routing
|
- [Drizzle ORM Filter Operators](https://orm.drizzle.team/docs/operators) -- like, eq, and operators for search/filter
|
||||||
- [Hono official docs](https://hono.dev/docs) — Bun integration, middleware patterns
|
- [Drizzle ORM Conditional Filters Guide](https://orm.drizzle.team/docs/guides/conditional-filters-in-query) -- dynamic filter composition
|
||||||
- [Drizzle ORM docs - Bun SQLite](https://orm.drizzle.team/docs/connect-bun-sqlite) — driver support, schema patterns
|
- [react-minimal-pie-chart GitHub](https://github.com/toomuchdesign/react-minimal-pie-chart) -- v9.1.2, React 19 peerDeps verified in package.json
|
||||||
- [Vite releases](https://vite.dev/releases) — v8.0 with Rolldown confirmed
|
- [LighterPack](https://lighterpack.com/) -- base/worn/consumable classification standard, pie chart visualization pattern
|
||||||
- [Tailwind CSS v4.2 blog](https://tailwindcss.com/blog/tailwindcss-v4) — CSS-native config, Vite plugin
|
- [99Boulders LighterPack Tutorial](https://www.99boulders.com/lighterpack-tutorial) -- classification definitions and feature walkthrough
|
||||||
- [TanStack Router docs](https://tanstack.com/router/latest) — file-based routing, typed params
|
- [BackpackPeek Pack Weight Calculator Guide](https://backpackpeek.com/blog/pack-weight-calculator-base-weight-guide) -- weight classification methodology
|
||||||
- [TanStack Query docs](https://tanstack.com/query/latest) — cache invalidation, mutations
|
- Direct codebase analysis of GearBox v1.1 -- schema.ts, services, hooks, routes, test helpers
|
||||||
- [SQLite Internal vs External BLOBs](https://sqlite.org/intern-v-extern-blob.html) — image storage guidance
|
|
||||||
- [Comparison Tables — NN/g](https://www.nngroup.com/articles/comparison-tables/) — comparison UX best practices
|
|
||||||
|
|
||||||
### Secondary (MEDIUM confidence)
|
### Secondary (MEDIUM confidence)
|
||||||
- [Hikt Blog: Best Backpacking Gear Apps 2026](https://hikt.app/blog/best-backpacking-gear-apps-2026/) — competitor feature analysis
|
- [Hikt](https://hikt.app/) -- searchable gear closet, base vs worn weight display
|
||||||
- [Building Full-Stack App with Bun.js, React and Drizzle ORM](https://awplife.com/building-full-stack-app-with-bun-js-react-drizzle/) — project structure reference
|
- [PackLight (iOS)](https://apps.apple.com/us/app/packlight-for-backpacking/id1054845207) -- search, categories, bar graph visualization
|
||||||
- [Designing better file organization around tags, not hierarchies](https://www.nayuki.io/page/designing-better-file-organization-around-tags-not-hierarchies) — tags vs hierarchy rationale
|
- [Packstack](https://www.packstack.io/) -- base/worn/consumable weight separation
|
||||||
|
- [Packrat](https://www.packrat.app/) -- flexible weight unit input and display conversion
|
||||||
|
- [Recharts React 19 issue #6857](https://github.com/recharts/recharts/issues/6857) -- rendering issues with React 19.2.3
|
||||||
|
- [TanStack Query filtering discussions](https://github.com/TanStack/query/discussions/1113) -- client-side vs server-side filtering patterns
|
||||||
|
- [LogRocket Best React Chart Libraries 2025](https://blog.logrocket.com/best-react-chart-libraries-2025/) -- chart library comparison
|
||||||
|
|
||||||
### Tertiary (LOW confidence / needs validation)
|
### Tertiary (LOW confidence)
|
||||||
- [Zod v4 release notes](https://zod.dev/v4) — @hono/zod-validator compatibility with Zod 4 unconfirmed, verify before use
|
- [SQLite LIKE case sensitivity](https://github.com/drizzle-team/drizzle-orm-docs/issues/239) -- LIKE is case-insensitive in SQLite (relevant only if search moves server-side)
|
||||||
|
- [Drizzle ORM SQLite migration pitfalls #1313](https://github.com/drizzle-team/drizzle-orm/issues/1313) -- data loss bug with push + add column (monitor during migration)
|
||||||
|
|
||||||
---
|
---
|
||||||
*Research completed: 2026-03-14*
|
*Research completed: 2026-03-16*
|
||||||
*Ready for roadmap: yes*
|
*Ready for roadmap: yes*
|
||||||
|
|||||||
Reference in New Issue
Block a user