docs: complete project research
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -1,244 +1,262 @@
|
||||
# Feature Research: v1.2 Collection Power-Ups
|
||||
# Feature Research
|
||||
|
||||
**Domain:** Gear management -- search/filter, weight classification, weight visualization, candidate status tracking, weight unit selection
|
||||
**Domain:** Gear management — candidate comparison, setup impact preview, and candidate ranking
|
||||
**Researched:** 2026-03-16
|
||||
**Confidence:** HIGH
|
||||
**Scope:** New features only. v1.0/v1.1 features (item CRUD, categories, threads, setups, dashboard, onboarding, images, icons) are already shipped.
|
||||
**Confidence:** HIGH (existing codebase fully understood; UX patterns verified via multiple sources)
|
||||
|
||||
## Table Stakes
|
||||
---
|
||||
|
||||
Features that gear management users expect. Missing these makes the app feel incomplete for collections beyond ~20 items.
|
||||
## Context
|
||||
|
||||
| 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. |
|
||||
This is a subsequent milestone research file for **v1.3 Research & Decision Tools**.
|
||||
The features below are **additive** to v1.2. All three features operate within the existing
|
||||
`threads/$threadId` page and its data model.
|
||||
|
||||
## Differentiators
|
||||
**Existing data model relevant to this milestone:**
|
||||
- `threadCandidates`: id, threadId, name, weightGrams, priceCents, categoryId, notes, productUrl, imageFilename, status — no rank, pros, or cons columns yet
|
||||
- `setups` + `setupItems`: stores weight/cost per setup item with classification (base/worn/consumable)
|
||||
- `getSetupWithItems` already returns `classification` per item — available for impact preview
|
||||
|
||||
Features that set GearBox apart or add meaningful value beyond what competitors offer.
|
||||
---
|
||||
|
||||
| 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 Landscape
|
||||
|
||||
## Anti-Features
|
||||
### Table Stakes (Users Expect These)
|
||||
|
||||
Features to explicitly NOT build in this milestone.
|
||||
Features users assume exist in any comparison or decision tool. Missing these makes the thread
|
||||
detail page feel incomplete as a decision workspace.
|
||||
|
||||
| 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 Expected | Complexity | Notes |
|
||||
|---------|--------------|------------|-------|
|
||||
| Side-by-side comparison view | Any comparison tool in any domain shows attributes aligned per-column. Card grid (current) forces mental juggling between candidates. E-commerce, spec sheets, gear apps — all use tabular layout for comparison. | MEDIUM | Rows = attributes (image, name, weight, price, status, notes, link), columns = candidates. Sticky attribute-label column during horizontal scroll. Max 3–4 candidates usable on desktop; 2 on mobile. Toggle between grid view (current) and table view. |
|
||||
| Weight delta per candidate | Gear apps (LighterPack, GearGrams) display weight totals prominently. Users replacing an item need the delta, not just the raw weight of the candidate. | LOW | Pure client-side computation: `candidate.weightGrams - existingItemWeight`. No API call needed if setup data already loaded via `useSetup`. |
|
||||
| Cost delta per candidate | Same reasoning as weight delta. A purchase decision is always the weight vs. cost tradeoff. | LOW | Same pattern as weight delta. Color-coded: green for savings/lighter, red for more expensive/heavier. |
|
||||
| Setup selector for impact preview | User needs to pick which setup to compute deltas against — not all setups contain the same category of item being replaced. | MEDIUM | Dropdown of setup names populated from `useSetups()`. When selected, loads setup via `useSetup(id)`. "No setup selected" state shows raw candidate values only, no delta. |
|
||||
|
||||
## Feature Details
|
||||
### Differentiators (Competitive Advantage)
|
||||
|
||||
### 1. Search and Filter
|
||||
Features not found in LighterPack, GearGrams, or any other gear app. Directly serve the
|
||||
"decide between candidates" workflow that is unique to GearBox.
|
||||
|
||||
**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).
|
||||
| Feature | Value Proposition | Complexity | Notes |
|
||||
|---------|-------------------|------------|-------|
|
||||
| Drag-to-rank ordering | Makes priority explicit without a numeric input. Ranking communicates "this is my current top pick." Maps to how users mentally stack-rank options during research. No competitor has this in the gear domain. | MEDIUM | `@dnd-kit/sortable` is the current standard (actively maintained; `react-beautiful-dnd` is abandoned as of 2025). Requires new `rank` integer column on `threadCandidates`. Persist order via PATCH endpoint. |
|
||||
| Per-candidate pros/cons fields | Freeform text capturing the reasoning behind ranking. LighterPack and GearGrams have notes per item but no structured decision rationale. Differentiates GearBox as a decision tool, not just a list tracker. | LOW | Two textarea fields per candidate. New `pros` and `cons` text columns on `threadCandidates`. Visible in comparison view rows and candidate edit panel. |
|
||||
| Impact preview with category-matched delta | Setup items have a category. The most meaningful delta is weight saved within the same category (e.g., comparing sleeping pads, subtract current sleeping pad weight from setup total). More actionable than comparing against the entire setup total. | MEDIUM | Use `candidate.categoryId` to find matching setup items and compute delta. Edge case: no item of that category in the setup → show "not in setup." Data already available from `getSetupWithItems`. |
|
||||
|
||||
**Domain patterns observed:**
|
||||
- Hikt: Searchable gear closet with category and specification filters
|
||||
- PackLight: Inventory search (premium feature) with category organization
|
||||
- Backpacking Light Calculator: Search filter in gear locker and within packs
|
||||
- LighterPack: No text search -- widely considered a gap
|
||||
### Anti-Features (Commonly Requested, Often Problematic)
|
||||
|
||||
**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")
|
||||
| Feature | Why Requested | Why Problematic | Alternative |
|
||||
|---------|---------------|-----------------|-------------|
|
||||
| Custom comparison attributes | "I want to compare battery life, durability, color..." | PROJECT.md explicitly rejects this as a complexity trap. Custom attributes require schema generalization, dynamic rendering, and data entry friction for every candidate. | Notes field and pros/cons fields cover the remaining use cases. |
|
||||
| Score/rating calculation | Automatically rank candidates by computed score | Score algorithms require encoding the user's weight-vs-price preference — personalization complexity. Users distrust opaque scores. | Manual drag-to-rank expresses the user's own weighting without encoding it in an algorithm. |
|
||||
| Side-by-side comparison across threads | Compare candidates from different research threads | Candidates belong to different purchase decisions — mixing them is conceptually incoherent. Different categories are never apples-to-apples. | Thread remains the scope boundary. Cross-thread planning is what setups are for. |
|
||||
| Comparison permalink/share | Share a comparison view URL | GearBox is single-user, no auth for v1. Sharing requires auth, user management, public/private visibility. | Out of scope for v1 per PROJECT.md. Future feature. |
|
||||
| Classification-aware impact preview as MVP requirement | Show delta broken down by base/worn/consumable | While data is available, the classification breakdown adds significant UI complexity. The flat delta answers "will this make my setup lighter?" which is 90% of the use case. | Flat delta for MVP. Classification-aware breakdown as a follow-up enhancement (P2). |
|
||||
|
||||
**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
|
||||
|
||||
```
|
||||
[Weight Unit Selection] --independent-- (affects all displays, no schema changes)
|
||||
|
|
||||
+-- should ship first (all other features benefit from correct unit display)
|
||||
[Side-by-side comparison view]
|
||||
└──requires──> [All candidate fields visible in UI]
|
||||
(weightGrams, priceCents, notes, productUrl already in schema)
|
||||
└──enhances──> [Pros/cons fields] (displayed as comparison rows)
|
||||
└──enhances──> [Drag-to-rank] (rank number shown as position in comparison columns)
|
||||
└──enhances──> [Impact preview] (delta displayed per-column inline)
|
||||
|
||||
[Search & Filter] --independent-- (pure client-side, no schema changes)
|
||||
|
|
||||
+-- no dependencies on other v1.2 features
|
||||
[Impact preview (weight + cost delta)]
|
||||
└──requires──> [Setup selector] (user picks which setup to compute delta against)
|
||||
└──requires──> [Setup data client-side] (useSetup hook already exists, no new API)
|
||||
└──requires──> [Candidate weight/price data] (already in threadCandidates schema)
|
||||
|
||||
[Candidate Status Tracking] --independent-- (schema change on thread_candidates only)
|
||||
|
|
||||
+-- no dependencies on other v1.2 features
|
||||
[Setup selector]
|
||||
└──requires──> [useSetups() hook] (already exists in src/client/hooks/useSetups.ts)
|
||||
└──requires──> [useSetup(id) hook] (already exists, loads items with classification)
|
||||
|
||||
[Weight Classification] --depends-on--> [existing setup_items table]
|
||||
|
|
||||
+-- schema migration on setup_items
|
||||
+-- enables [Weight Distribution Visualization]
|
||||
[Drag-to-rank]
|
||||
└──requires──> [rank INTEGER column on threadCandidates] (new — schema migration)
|
||||
└──requires──> [PATCH /api/threads/:id/candidates/rank endpoint] (new API endpoint)
|
||||
└──enhances──> [Side-by-side comparison] (rank visible as position indicator)
|
||||
└──enhances──> [Card grid view] (rank badge on each CandidateCard)
|
||||
|
||||
[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
|
||||
[Pros/cons fields]
|
||||
└──requires──> [pros TEXT column on threadCandidates] (new — schema migration)
|
||||
└──requires──> [cons TEXT column on threadCandidates] (new — schema migration)
|
||||
└──requires──> [updateCandidateSchema extended] (add pros/cons to Zod schema)
|
||||
└──enhances──> [CandidateForm edit panel] (new textarea fields)
|
||||
└──enhances──> [Side-by-side comparison] (pros/cons rows in comparison table)
|
||||
```
|
||||
|
||||
### Implementation Order Rationale
|
||||
### Dependency Notes
|
||||
|
||||
1. **Weight Unit Selection** first -- touches formatting everywhere, foundational for all subsequent weight displays
|
||||
2. **Search & Filter** second -- standalone, immediately useful, low risk
|
||||
3. **Candidate Status Tracking** third -- standalone schema change, simple
|
||||
4. **Planning Category Filter** fourth -- quick UI polish
|
||||
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
|
||||
- **Side-by-side comparison is independent of schema changes.** It can be built using
|
||||
existing candidate data. No migrations required. Delivers value immediately.
|
||||
- **Impact preview is independent of schema changes.** Uses existing `useSetups` and
|
||||
`useSetup` hooks client-side. Delta computation is pure math in the component.
|
||||
No new API endpoint needed for MVP.
|
||||
- **Drag-to-rank requires schema migration.** `rank` column must be added to
|
||||
`threadCandidates`. Default ordering on migration = `createdAt` ascending.
|
||||
- **Pros/cons requires schema migration.** Two nullable `text` columns on
|
||||
`threadCandidates`. Low risk — nullable, backwards compatible.
|
||||
- **Comparison view enhances everything.** Best delivered after rank and pros/cons
|
||||
schema work is done so the full table is useful from day one.
|
||||
|
||||
## Complexity Summary
|
||||
---
|
||||
|
||||
| Feature | Schema Change | API Change | New Dependency | UI Scope | Overall |
|
||||
|---------|---------------|------------|----------------|----------|---------|
|
||||
| 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 |
|
||||
| Candidate Status Tracking | `thread_candidates.status` column | Update candidate CRUD | None | CandidateCard, CandidateForm | LOW |
|
||||
| Planning Category Filter | None | None | None | PlanningView dropdown | LOW |
|
||||
| Weight Classification | `setup_items.classification` column | Update setup sync + detail endpoints | None | Setup detail view | MEDIUM |
|
||||
| Weight Distribution Chart | None | Possibly new totals endpoint | react-minimal-pie-chart (~2kB) | New chart component | MEDIUM |
|
||||
## MVP Definition
|
||||
|
||||
### Launch With (v1.3 milestone)
|
||||
|
||||
- [ ] **Side-by-side comparison view** — Core deliverable. Replace mental juggling of the card
|
||||
grid with a scannable table. No schema changes. Highest ROI, lowest risk.
|
||||
- [ ] **Impact preview: flat weight + cost delta per candidate** — Shows `+/- X g` and
|
||||
`+/- $Y` vs. the selected setup. Pure client-side math. No schema changes.
|
||||
- [ ] **Setup selector** — Dropdown of user's setups. Required for impact preview. One
|
||||
interaction: pick a setup, see deltas update.
|
||||
- [ ] **Drag-to-rank** — Requires `rank` column migration. `@dnd-kit/sortable` handles
|
||||
the drag UX. Persist via new PATCH endpoint.
|
||||
- [ ] **Pros/cons text fields** — Requires `pros` + `cons` column migration. Trivially low
|
||||
implementation complexity once schema is in place.
|
||||
|
||||
### Add After Validation (v1.x)
|
||||
|
||||
- [ ] **Classification-aware impact preview** — Delta broken down by base/worn/consumable.
|
||||
Higher complexity UI. Add once flat delta is validated as useful.
|
||||
Trigger: user feedback requests "which classification does this affect?"
|
||||
- [ ] **Rank indicator on card grid** — Small "1st", "2nd" badge on CandidateCard.
|
||||
Trigger: users express confusion about which candidate is ranked first without entering
|
||||
comparison view.
|
||||
- [ ] **Comparison view on mobile** — Horizontal scroll works but is not ideal. Consider
|
||||
attribute-focus swipe view. Trigger: usage data shows mobile traffic on thread pages.
|
||||
|
||||
### Future Consideration (v2+)
|
||||
|
||||
- [ ] **Comparison permalink** — Requires auth/multi-user work first.
|
||||
- [ ] **Auto-fill from product URL** — Fragile scraping, rejected in PROJECT.md.
|
||||
- [ ] **Custom comparison attributes** — Explicitly rejected in PROJECT.md.
|
||||
|
||||
---
|
||||
|
||||
## Feature Prioritization Matrix
|
||||
|
||||
| Feature | User Value | Implementation Cost | Priority |
|
||||
|---------|------------|---------------------|----------|
|
||||
| Side-by-side comparison view | HIGH | MEDIUM | P1 |
|
||||
| Setup impact preview (flat delta) | HIGH | LOW | P1 |
|
||||
| Setup selector for impact preview | HIGH | LOW | P1 |
|
||||
| Drag-to-rank ordering | MEDIUM | MEDIUM | P1 |
|
||||
| Pros/cons text fields | MEDIUM | LOW | P1 |
|
||||
| Classification-aware impact preview | MEDIUM | HIGH | P2 |
|
||||
| Rank indicator on card grid | LOW | LOW | P2 |
|
||||
| Mobile-optimized comparison view | LOW | MEDIUM | P3 |
|
||||
|
||||
**Priority key:**
|
||||
- P1: Must have for this milestone launch
|
||||
- P2: Should have, add when possible
|
||||
- P3: Nice to have, future consideration
|
||||
|
||||
---
|
||||
|
||||
## Competitor Feature Analysis
|
||||
|
||||
| Feature | LighterPack | GearGrams | OutPack | Our Approach |
|
||||
|---------|-------------|-----------|---------|--------------|
|
||||
| Side-by-side candidate comparison | None (list only) | None (library + trip list) | None | Inline comparison table on thread detail page, toggle from grid view |
|
||||
| Impact preview / weight delta | None (duplicate lists manually to compare) | None (no delta concept) | None | Per-candidate delta vs. selected setup, computed client-side |
|
||||
| Candidate ranking | None | None | None | Drag-to-rank with persisted `rank` column |
|
||||
| Pros/cons annotation | None (notes field only) | None (notes field only) | None | Dedicated `pros` and `cons` fields separate from general notes |
|
||||
| Status tracking | None | "wish list" item flag only | None | Already built in v1.2 (researching/ordered/arrived) |
|
||||
|
||||
**Key insight:** No existing gear management tool has a comparison view, delta preview, or
|
||||
ranking system for candidates within a research thread. This is an unmet-need gap.
|
||||
The features are adapted from general product comparison UX (e-commerce) to the gear domain.
|
||||
|
||||
---
|
||||
|
||||
## Implementation Notes by Feature
|
||||
|
||||
### Side-by-side Comparison View
|
||||
|
||||
- Rendered as a transposed table: rows = attribute labels, columns = candidates.
|
||||
- Rows: Image (thumbnail), Name, Weight, Price, Status, Notes, Link, Pros, Cons, Rank, Impact Delta (weight), Impact Delta (cost).
|
||||
- Sticky first column (attribute label) while candidate columns scroll horizontally for 3+.
|
||||
- Candidate images at reduced aspect ratio (square thumbnail ~80px).
|
||||
- Weight/price cells use existing `formatWeight` / `formatPrice` formatters with the user's preferred unit.
|
||||
- Status cell reuses existing `StatusBadge` component.
|
||||
- "Pick as winner" action available per column (reuses existing `openResolveDialog`).
|
||||
- Toggle between grid view (current) and table view. Preserve both modes. Default to grid;
|
||||
user activates comparison mode explicitly.
|
||||
- Comparison mode is a UI state only (Zustand or local component state) — no URL change needed.
|
||||
|
||||
### Impact Preview
|
||||
|
||||
- Setup selector: `<select>` or custom dropdown populated from `useSetups()`.
|
||||
- On selection: load setup via `useSetup(id)`. Compute delta per candidate:
|
||||
`candidate.weightGrams - matchingCategoryWeight` where `matchingCategoryWeight` is the
|
||||
sum of setup item weights in the same category as the thread.
|
||||
- Delta display: colored pill on each candidate column in comparison view:
|
||||
- Negative delta (lighter) = green, prefixed with "−"
|
||||
- Positive delta (heavier) = red, prefixed with "+"
|
||||
- Zero = neutral gray
|
||||
- Same pattern for cost delta.
|
||||
- "No setup selected" state = no delta row shown.
|
||||
- "Category not in setup" state = "not in setup" label instead of delta.
|
||||
- No new API endpoints required. All data is client-side once setups are loaded.
|
||||
|
||||
### Drag-to-Rank
|
||||
|
||||
- `@dnd-kit/sortable` with `SortableContext` wrapping the candidate list.
|
||||
- `useSortable` hook per candidate with a drag handle (Lucide `grip-vertical` icon).
|
||||
- Drag handle visible always (not hover-only) so the affordance is clear.
|
||||
- On `onDragEnd`: recompute ranks using `arrayMove()`, call
|
||||
`PATCH /api/threads/:threadId/candidates/rank` with `{ orderedIds: number[] }`.
|
||||
- Server endpoint: bulk update `rank` for each candidate ID in the thread atomically.
|
||||
- `rank` column: `INTEGER` nullable. Null = unranked (treated as lowest rank). Default to
|
||||
`createdAt` order on first explicit rank save.
|
||||
- Rank number badge: displayed on each CandidateCard corner (small gray circle, "1", "2", "3").
|
||||
- Works in both grid view and comparison view.
|
||||
|
||||
### Pros/Cons Fields
|
||||
|
||||
- Two `textarea` inputs added to the existing `CandidateForm` (slide-out panel).
|
||||
- Labels: "Pros" and "Cons" — plain text, no icons.
|
||||
- Displayed below the existing Notes field in the form.
|
||||
- Extend `updateCandidateSchema` with `pros: z.string().optional()` and `cons: z.string().optional()`.
|
||||
- In comparison table: pros and cons rows display as plain text, line-wrapped.
|
||||
- In card grid: pros/cons not shown on card surface (too much density). Visible only in edit
|
||||
panel and comparison view.
|
||||
|
||||
### Schema Changes Required
|
||||
|
||||
Two schema migrations needed for this milestone:
|
||||
|
||||
```sql
|
||||
-- Migration 1: Candidate rank
|
||||
ALTER TABLE thread_candidates ADD COLUMN rank INTEGER;
|
||||
|
||||
-- Migration 2: Candidate pros/cons
|
||||
ALTER TABLE thread_candidates ADD COLUMN pros TEXT;
|
||||
ALTER TABLE thread_candidates ADD COLUMN cons TEXT;
|
||||
```
|
||||
|
||||
Both columns are nullable and backwards compatible. Existing candidates get `NULL` values.
|
||||
UI treats `NULL` rank as unranked, `NULL` pros/cons as empty string.
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- [LighterPack](https://lighterpack.com/) -- weight classification and pie chart visualization patterns
|
||||
- [LighterPack Tutorial (99Boulders)](https://www.99boulders.com/lighterpack-tutorial) -- detailed feature walkthrough
|
||||
- [LighterPack Tutorial (Backpackers.com)](https://backpackers.com/blog/how-to-calculate-backpack-weight-with-lighterpack/) -- base/worn/consumable definitions
|
||||
- [Hikt](https://hikt.app/) -- searchable gear closet, base vs worn weight display
|
||||
- [PackLight (iOS)](https://apps.apple.com/us/app/packlight-for-backpacking/id1054845207) -- search, custom categories, bar graph visualization
|
||||
- [Packstack](https://www.packstack.io/) -- base/worn/consumable weight separation
|
||||
- [HikeLite](https://hikeliteapp.com/) -- worn weight marking, CSV import format
|
||||
- [Packrat](https://www.packrat.app/) -- flexible weight unit input and display conversion
|
||||
- [BPL Calculator Forum Discussion](https://backpackinglight.com/forums/topic/new-backpacking-hiking-weight-calculator-app/) -- unit conversion UX, search filter 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
|
||||
- [Designing The Perfect Feature Comparison Table — Smashing Magazine](https://www.smashingmagazine.com/2017/08/designing-perfect-feature-comparison-table/) — table layout patterns, sticky headers, progressive disclosure (HIGH confidence)
|
||||
- [Comparison Tables for Products, Services, and Features — Nielsen Norman Group](https://www.nngroup.com/articles/comparison-tables/) — information architecture for comparison, anti-patterns (HIGH confidence)
|
||||
- [The Ultimate Drag-and-Drop Toolkit for React: @dnd-kit — BrightCoding (2025)](https://www.blog.brightcoding.dev/2025/08/21/the-ultimate-drag-and-drop-toolkit-for-react-a-deep-dive-into-dnd-kit/) — confirmed dnd-kit as current standard, react-beautiful-dnd abandoned (HIGH confidence)
|
||||
- [dnd-kit Sortable Docs](https://docs.dndkit.com/presets/sortable) — SortableContext, useSortable, arrayMove patterns (HIGH confidence)
|
||||
- [Ultralight: The Gear Tracking App I'm Leaving LighterPack For — TrailsMag](https://trailsmag.net/blogs/hiker-box/ultralight-the-gear-tracking-app-i-m-leaving-lighterpack-for) — LighterPack feature gap analysis (MEDIUM confidence)
|
||||
- [Comparing products: UX design best practices — Contentsquare](https://contentsquare.com/blog/comparing-products-design-practices-to-help-your-users-avoid-fragmented-comparison-7/) — fragmented comparison UX pitfalls (HIGH confidence)
|
||||
- [Drag and drop UI examples and UX tips — Eleken](https://www.eleken.co/blog-posts/drag-and-drop-ui) — drag affordance and visual feedback patterns (MEDIUM confidence)
|
||||
- GearBox codebase analysis (src/db/schema.ts, src/server/services/, src/client/hooks/) — confirmed existing data model, no rank/pros/cons columns present (HIGH confidence)
|
||||
|
||||
---
|
||||
*Feature research for: v1.2 Collection Power-Ups (search/filter, weight classification, visualization, candidate status, weight units)*
|
||||
*Feature research for: GearBox v1.3 — candidate comparison, setup impact preview, candidate ranking*
|
||||
*Researched: 2026-03-16*
|
||||
|
||||
@@ -1,202 +1,230 @@
|
||||
# Pitfalls Research
|
||||
|
||||
**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)
|
||||
**Domain:** Adding side-by-side candidate comparison, setup impact preview, and drag-to-reorder ranking to an existing gear management app (GearBox v1.3)
|
||||
**Researched:** 2026-03-16
|
||||
**Confidence:** HIGH (pitfalls derived from direct codebase analysis + domain-specific patterns from gear tracking community + React/SQLite ecosystem knowledge)
|
||||
**Confidence:** HIGH (derived from direct codebase analysis of v1.2 + verified with dnd-kit GitHub issues, TanStack Query docs, and Baymard comparison UX research)
|
||||
|
||||
---
|
||||
|
||||
## Critical Pitfalls
|
||||
|
||||
### Pitfall 1: Weight Unit Conversion Rounding Accumulation
|
||||
### Pitfall 1: dnd-kit + React Query Cache Produces Visible Flicker on Drop
|
||||
|
||||
**What goes wrong:**
|
||||
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.
|
||||
When ranking candidates via drag-to-reorder, the naive approach is to call `mutate()` in `onDragEnd` and apply an optimistic update with `setQueryData` in the `onMutate` callback. Despite this, the item visibly snaps back to its original position for a split second before settling in the new position. The user sees a "jump" on every successful drop, which makes the ranking feature feel broken even though the data is correct.
|
||||
|
||||
**Why it happens:**
|
||||
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.
|
||||
dnd-kit's `SortableContext` derives its order from React state. When the order is stored in React Query's cache rather than local React state, there is a timing mismatch: dnd-kit reads the list order from the cache after the drop animation, but the cache update triggers a React re-render cycle that arrives one or two frames late. The drop animation briefly shows the item at its original position before the re-render reflects the new order. This is a known, documented issue in dnd-kit (GitHub Discussion #1522, Issue #921) that specifically affects React Query integrations.
|
||||
|
||||
**How to avoid:**
|
||||
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.
|
||||
Use a `tempItems` local state (`useState<Candidate[] | null>(null)`) alongside React Query. On `onDragEnd`, immediately set `tempItems` to the reordered array before calling `mutate()`. Render the candidate list from `tempItems ?? queryData.candidates`. In mutation `onSettled`, set `tempItems` to `null` to hand back control to React Query. This approach:
|
||||
- Prevents the flicker because the component re-renders from synchronous local state immediately
|
||||
- Avoids `useEffect` syncing (which adds extra renders and is error-prone)
|
||||
- Stays consistent with the existing React Query + Zustand pattern in the codebase
|
||||
- Handles drag cancellation cleanly (reset `tempItems` on `onDragCancel`)
|
||||
|
||||
Do not store the rank column data in the React Query `["threads", threadId]` cache key in a way that requires invalidation and refetch after reorder — this causes a round-trip delay that amplifies the flicker.
|
||||
|
||||
**Warning signs:**
|
||||
- Edit form pre-fills with a converted value and saves by reconverting that value
|
||||
- `formatWeight` is called before summation rather than after
|
||||
- Unit conversion is done in multiple places (client and server) with different rounding
|
||||
- Tests compare floating-point totals with `===` instead of tolerance-based comparison
|
||||
- Item visibly snaps back to original position for ~1 frame on drop
|
||||
- `onDragEnd` calls `mutate()` but uses no local state bridge
|
||||
- `setQueryData` is the only state update on drag end
|
||||
|
||||
**Phase to address:**
|
||||
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).
|
||||
Candidate ranking phase — the `tempItems` pattern must be designed before building the drag UI, not retrofitted after noticing the flicker.
|
||||
|
||||
---
|
||||
|
||||
### Pitfall 2: Weight Classification Stored at Wrong Level
|
||||
### Pitfall 2: Rank Storage Using Integer Offsets Requires Bulk Writes
|
||||
|
||||
**What goes wrong:**
|
||||
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.
|
||||
The most obvious approach for storing candidate rank order is adding a `sortOrder INTEGER` column to `thread_candidates` and storing 1, 2, 3... When the user drags candidate #2 to position #1, the naive fix is to update all subsequent candidates' `sortOrder` values to maintain contiguous integers. With 5 candidates, this is 5 UPDATE statements per drop. With rapid dragging, this creates a burst of writes where each intermediate position during the drag fires updates. If the app ever has threads with 10+ candidates (not uncommon for a serious gear decision), this becomes visible latency on every drag.
|
||||
|
||||
**Why it happens:**
|
||||
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."
|
||||
Integer rank storage feels natural and maps directly to how arrays work. The developer adds `ORDER BY sort_order ASC` to the candidate query and calls it done. The performance problem is only discovered when testing with a realistic number of candidates and a fast drag gesture.
|
||||
|
||||
**How to avoid:**
|
||||
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)`
|
||||
Use a `sortOrder REAL` column (floating-point) with fractional indexing — when inserting between positions A and B, assign `(A + B) / 2`. This means a drag requires only a single UPDATE for the moved item. Only trigger a full renumber (resetting all candidates to integers 1000, 2000, 3000... or similar spaced values) when the float precision degrades (approximately after 50+ nested insertions, unlikely in practice for this app). Start values at 1000, 5000 increments to give ample room.
|
||||
|
||||
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`.
|
||||
For GearBox's use case (typically 2-8 candidates per thread), integer storage is workable, but the fractional approach is cleaner and avoids the bulk-write problem entirely. The added complexity is minimal: one line of math in the service layer.
|
||||
|
||||
Regardless of storage strategy, add an index: `CREATE INDEX ON thread_candidates (thread_id, sort_order)`.
|
||||
|
||||
**Warning signs:**
|
||||
- `classification` column added to `items` table
|
||||
- Setup detail view shows classification but cannot be different per setup
|
||||
- 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
|
||||
- `sortOrder` column uses `integer()` type in Drizzle schema
|
||||
- Reorder service function issues multiple UPDATE statements in a loop
|
||||
- No transaction wrapping the bulk update
|
||||
- Each drag event (not just the final drop) triggers a service call
|
||||
|
||||
**Phase to address:**
|
||||
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.
|
||||
Schema and service design phase for candidate ranking — the storage strategy must be chosen before building the sort UI, as changing from integer to fractional later requires a migration.
|
||||
|
||||
---
|
||||
|
||||
### Pitfall 3: Search/Filter Implemented Server-Side for a Client-Side Dataset
|
||||
### Pitfall 3: Impact Preview Reads Stale Candidate Data
|
||||
|
||||
**What goes wrong:**
|
||||
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
|
||||
The impact preview shows "+450g / +$89" next to each candidate — what this candidate would add to the selected setup. The calculation is: `(candidate.weightGrams - null) + setup.totalWeight`. But the candidate card data comes from the `["threads", threadId]` query cache, while the setup totals come from a separate `["setups", setupId]` query cache. These caches can be out of sync: the user edits a candidate's weight in one tab, invalidating the threads cache, but if the setup was fetched earlier and has not been refetched, the "current setup weight" baseline in the delta is stale. The preview shows a delta calculated against the wrong baseline.
|
||||
|
||||
The second failure mode: if `candidate.weightGrams` is `null` (not yet entered), displaying `+-- / +$89` is confusing. Users see "null delta" and assume the comparison is broken rather than understanding that the candidate has no weight data.
|
||||
|
||||
**Why it happens:**
|
||||
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.
|
||||
Impact preview feels like pure computation — "just subtract two numbers." The developer writes it as a derived value from two props and does not think about cache coherence. The null case is often overlooked because the developer tests with complete candidate data.
|
||||
|
||||
**How to avoid:**
|
||||
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.
|
||||
1. Derive the delta from data already co-located in one cache entry where possible. The thread detail query (`["threads", threadId]`) returns all candidates; the setup query (`["setups", setupId]`) returns items with weight. Compute the delta in the component using both: `delta = candidate.weightGrams - replacedItemWeight` where `replacedItemWeight` is taken from the currently loaded setup data.
|
||||
2. Use `useQuery` for setup data with the setup selector in the same component that renders the comparison, so both data sources are reactive.
|
||||
3. Handle null weight explicitly: show "-- (no weight data)" not "--g" for candidates without weights. Make the null state visually distinct from a zero delta.
|
||||
4. Do NOT make a server-side `/api/threads/:id/impact?setupId=:sid` endpoint that computes delta server-side — this creates a third cache entry to invalidate and adds network latency to what should be a purely client-side calculation.
|
||||
|
||||
**Warning signs:**
|
||||
- New query parameters added to `GET /api/items` endpoint
|
||||
- `useItems` hook accepts filter params, creating multiple cache entries
|
||||
- Search input has a debounce delay
|
||||
- Filtered view totals disagree with dashboard totals
|
||||
- Impact delta shows stale values after editing a candidate's weight
|
||||
- Null weight candidates show a numerical delta (treating null as 0)
|
||||
- Delta calculation is in a server route rather than a client-side derived value
|
||||
- Setup data is fetched via a different hook than the one used for candidate data, with no shared staleness boundary
|
||||
|
||||
**Phase to address:**
|
||||
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.
|
||||
Impact preview phase — establish the data flow (client-side derived from two existing queries) before building the UI so the stale-cache problem cannot arise.
|
||||
|
||||
---
|
||||
|
||||
### Pitfall 4: Candidate Status Transition Without Validation
|
||||
### Pitfall 4: Side-by-Side Comparison Breaks at Narrow Widths
|
||||
|
||||
**What goes wrong:**
|
||||
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).
|
||||
The comparison view is built with a fixed two-or-three-column grid for the candidate cards. On a laptop at 1280px it looks great. On a narrower viewport or when the browser window is partially shrunk, the columns collapse to ~200px each, making the candidate name truncated, the weight/price badges unreadable, and the notes text invisible. The user cannot actually compare the candidates — the view that was supposed to help them decide becomes unusable.
|
||||
|
||||
GearBox's existing design philosophy is mobile-responsive, but comparison tables are inherently wide. The tension is real: side-by-side requires horizontal space that mobile cannot provide.
|
||||
|
||||
**Why it happens:**
|
||||
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.
|
||||
Comparison views are usually mocked at full desktop width. Responsiveness is added as an afterthought, and the "fix" is often to stack columns vertically on mobile — which defeats the entire purpose of side-by-side comparison.
|
||||
|
||||
**How to avoid:**
|
||||
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)
|
||||
1. Build the comparison view as a horizontally scrollable container on mobile (`overflow-x: auto`). Do not collapse to vertical stack — comparing stacked items is cognitively equivalent to switching between detail pages.
|
||||
2. Limit the number of simultaneously compared candidates to 3 (or at most 4). Comparing 8 candidates side-by-side is unusable regardless of screen size.
|
||||
3. Use a minimum column width (e.g., `min-width: 200px`) so the container scrolls horizontally before the column content becomes illegible.
|
||||
4. Sticky first column for candidate names when scrolling horizontally, so the user always knows which column they are reading.
|
||||
5. Test at 768px viewport width before considering the feature done.
|
||||
|
||||
**Warning signs:**
|
||||
- Candidate status is a plain `text()` column with no Zod enum validation
|
||||
- No transition validation in the update candidate service
|
||||
- `resolveThread` does not update non-winner candidate statuses
|
||||
- UI allows arbitrary status changes via a dropdown with no constraints
|
||||
- Comparison grid uses percentage widths that collapse below 150px
|
||||
- No horizontal scroll on the comparison container
|
||||
- Mobile viewport shows columns stacked vertically
|
||||
- Candidate name or weight badges are truncated without tooltip
|
||||
|
||||
**Phase to address:**
|
||||
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.
|
||||
Side-by-side comparison UI phase — responsive behavior must be designed in, not retrofitted. The minimum column width and scroll container decision shapes the entire component structure.
|
||||
|
||||
---
|
||||
|
||||
### Pitfall 5: Weight Distribution Chart Diverges from Displayed Totals
|
||||
### Pitfall 5: Pros/Cons Fields Stored as Free Text in Column, Not Structured
|
||||
|
||||
**What goes wrong:**
|
||||
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.
|
||||
Pros and cons per candidate are stored as two free-text columns: `pros TEXT` and `cons TEXT` on `thread_candidates`. The user types a multi-line blob of text into each field. The comparison view renders them as raw text blocks next to each other. Two problems emerge:
|
||||
- Formatting: the comparison view cannot render individual pro/con bullet points because the data is unstructured blobs
|
||||
- Length: one candidate has a 500-word "pros" essay; another has two words. The comparison columns have wildly unequal heights, making the side-by-side comparison visually chaotic and hard to scan
|
||||
|
||||
The deeper problem: free text in a comparison context produces noise, not signal. Users write "it's really lightweight and packable and the color options are nice" when what the comparison view needs is scannable bullet points.
|
||||
|
||||
**Why it happens:**
|
||||
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.
|
||||
Adding two text columns to `thread_candidates` is the simplest possible implementation. The developer tests it with neat, short text and it looks fine. The UX failure is only visible when a real user writes the way real users write.
|
||||
|
||||
**How to avoid:**
|
||||
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.
|
||||
1. Store pros/cons as newline-delimited strings, not markdown or JSON. The UI splits on newlines and renders each line as a bullet. Simple, no parsing, no migration complexity.
|
||||
2. In the form, use a `<textarea>` with a placeholder of "one item per line." Show a character count.
|
||||
3. In the comparison view, render each newline-delimited entry as its own row, so columns stay scannable. Use a max of 5 bullet points per field; truncate with "show more" if longer.
|
||||
4. Cap `pros` and `cons` field length at 500 characters in the Zod schema to prevent essay-length blobs.
|
||||
5. The comparison view should truncate to the first 3 bullets when in compact comparison mode, with expand option.
|
||||
|
||||
**Warning signs:**
|
||||
- Chart component does its own `reduce()` on item data instead of using the same data as the totals display
|
||||
- Two different API endpoints return weight totals for the same scope and the values differ by small amounts
|
||||
- Chart labels show different precision than text displays (chart: "2.4 kg", header: "2,451 g")
|
||||
- No shared utility function for weight summation
|
||||
- `pros TEXT` and `cons TEXT` added to schema with no length constraint
|
||||
- Comparison view renders `{candidate.pros}` as a raw string in a `<p>` tag
|
||||
- One candidate's pros column is 3x taller than another's, making row alignment impossible
|
||||
- Form shows a full-height textarea with no guidance on format
|
||||
|
||||
**Phase to address:**
|
||||
Phase 3 (Weight distribution visualization) -- but the single-source-of-truth pattern should be established in Phase 1 when refactoring formatters for unit selection.
|
||||
Both the ranking schema phase (when pros/cons columns are added) and the comparison UI phase (when the rendering decision is made). The newline-delimited format must be decided at schema design time.
|
||||
|
||||
---
|
||||
|
||||
### Pitfall 6: Schema Migration Breaks Test Helper
|
||||
### Pitfall 6: Impact Preview Compares Against Wrong Setup Total When Item Would Be Replaced
|
||||
|
||||
**What goes wrong:**
|
||||
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.
|
||||
The impact preview shows the delta for each candidate as if the candidate would be *added* to the setup. But the real use case is: "I want to replace my current tent with one of these candidates — which one saves the most weight?" The user expects the delta to reflect `candidateWeight - currentItemWeight`, not just `+candidateWeight`.
|
||||
|
||||
When the delta is calculated as a pure addition (no replacement), a 500g candidate looks like "+500g" even though the item it replaces weighs 800g, meaning it would actually save 300g. The user sees a positive delta and dismisses the candidate when they should pick it.
|
||||
|
||||
**Why it happens:**
|
||||
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.
|
||||
"Impact" is ambiguous. The developer defaults to "how much weight does this add?" because that calculation is simpler (no need to identify which existing item is being replaced). The replacement case requires the user to specify which item in the setup would be swapped out, which feels like additional UX complexity.
|
||||
|
||||
**How to avoid:**
|
||||
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.
|
||||
1. Support both modes: "add to setup" (+delta) and "replace item" (delta = candidate - replaced item). Make the mode selection explicit in the UI.
|
||||
2. Default to "add" mode if no item in the setup shares the same category as the thread. Default to "replace" mode if an item with the same category exists — offer it as a pre-populated suggestion ("Replaces: Big Agnes Copper Spur 2? Change").
|
||||
3. The replacement item selector should be a dropdown filtered to setup items in the same category, defaulting to the most likely match.
|
||||
4. If no setup is selected, show raw candidate weight rather than a delta — do not calculate a delta against zero.
|
||||
|
||||
**Warning signs:**
|
||||
- Schema column added to `schema.ts` but not to `tests/helpers/db.ts`
|
||||
- Tests pass locally but queries fail at runtime
|
||||
- New service function works in the app but throws in tests
|
||||
- Test database has fewer columns than production database
|
||||
- Delta is always positive (never shows weight savings)
|
||||
- No replacement item selector in the impact preview UI
|
||||
- Thread category is not used to suggest a candidate's likely replacement item
|
||||
- Delta is calculated as `candidate.weightGrams` with no baseline
|
||||
|
||||
**Phase to address:**
|
||||
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.
|
||||
Impact preview design phase — the "add vs replace" distinction must be designed before building the service layer, because "add" and "replace" produce fundamentally different calculations and different UI affordances.
|
||||
|
||||
---
|
||||
|
||||
### Pitfall 7: Weight Unit Preference Stored Wrong, Applied Wrong
|
||||
### Pitfall 7: Schema Change Adds Columns Without Updating Test Helper
|
||||
|
||||
**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.
|
||||
v1.3 requires adding `sortOrder`, `pros`, and `cons` to `thread_candidates`. The developer updates `src/db/schema.ts`, runs `bun run db:push`, and builds the feature. Tests fail with cryptic "no such column" errors — or worse, tests pass silently because they do not exercise the new columns, while the real database has them.
|
||||
|
||||
This pitfall already existed in v1.2 (documented in the previous PITFALLS.md) and the test helper (`tests/helpers/db.ts`) uses raw CREATE TABLE SQL that must be manually kept in sync.
|
||||
|
||||
**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.
|
||||
Under time pressure, the developer focuses on the feature and forgets the test helper update. The error only surfaces when the new service function is called in a test. The CLAUDE.md documents this requirement, but it is easy to miss in the flow of development.
|
||||
|
||||
**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.
|
||||
For every schema change in v1.3, update `tests/helpers/db.ts` in the same commit:
|
||||
- `thread_candidates`: add `sort_order REAL DEFAULT 0`, `pros TEXT`, `cons TEXT`
|
||||
- Run `bun test` immediately after schema + helper update, before writing any other code
|
||||
|
||||
Consider writing a schema-parity test: compare the columns returned by `PRAGMA table_info(thread_candidates)` against a known expected list, failing if they differ. This catches the test-helper-out-of-sync problem automatically.
|
||||
|
||||
**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
|
||||
- Tests failing with `SqliteError: no such column`
|
||||
- New service function works in the running app but throws in `bun test`
|
||||
- `bun run db:push` was run but `bun test` was not run afterward
|
||||
- `tests/helpers/db.ts` has fewer columns than `src/db/schema.ts`
|
||||
|
||||
**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.
|
||||
Every schema-touching phase of v1.3. The candidate ranking schema phase (sortOrder, pros, cons) is the primary risk. Check test helper parity as an explicit completion criterion.
|
||||
|
||||
---
|
||||
|
||||
### Pitfall 8: Comparison View Includes Resolved Candidates
|
||||
|
||||
**What goes wrong:**
|
||||
After a thread is resolved (winner picked), the thread's candidates still exist in the database. The comparison view, if it loads candidates from the existing `getThreadWithCandidates` response without filtering, will display the resolved winner alongside all losers — including the now-irrelevant candidates. A user revisiting a resolved thread to check why they picked Option A sees all candidates re-listed in the comparison view with no indication of which was selected, creating confusion.
|
||||
|
||||
The secondary problem: if the app allows drag-to-reorder ranking on a resolved thread, a user could accidentally fire rank-update mutations on a thread that should be read-only.
|
||||
|
||||
**Why it happens:**
|
||||
The comparison view and ranking components are built for active threads and tested only with active threads. Resolved thread behavior is not considered during design.
|
||||
|
||||
**How to avoid:**
|
||||
1. Check `thread.status === "resolved"` before rendering the comparison/ranking UI. For resolved threads, render a read-only summary: "You chose [winner name]" with the winning candidate highlighted and others shown as non-interactive.
|
||||
2. Disable drag-to-reorder on resolved threads entirely — don't render the drag handles.
|
||||
3. In the impact preview, disable the "Impact on Setup" panel for resolved threads and instead show "Added to collection on [date]" for the winning candidate.
|
||||
4. The API route for rank updates should reject requests for resolved threads (return 400 with "Thread is resolved").
|
||||
|
||||
**Warning signs:**
|
||||
- Comparison/ranking UI renders identically for active and resolved threads
|
||||
- Drag handles are visible on resolved thread candidates
|
||||
- No `thread.status` check in the comparison view component
|
||||
- Resolved threads accept rank update mutations
|
||||
|
||||
**Phase to address:**
|
||||
Comparison UI phase and ranking phase — both must include a resolved-thread guard. This is a correctness issue, not just a UX issue, because drag mutations on resolved threads corrupt state.
|
||||
|
||||
---
|
||||
|
||||
@@ -206,24 +234,29 @@ Shortcuts that seem reasonable but create long-term problems.
|
||||
|
||||
| Shortcut | Immediate Benefit | Long-term Cost | When Acceptable |
|
||||
|----------|-------------------|----------------|-----------------|
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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 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 |
|
||||
| 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) |
|
||||
| Integer `sortOrder` instead of fractional | Simple schema | Bulk UPDATE on every reorder; bulk write latency with 10+ candidates | Acceptable only if max candidates per thread is enforced at 5 or fewer |
|
||||
| Server-side delta calculation endpoint | Simpler client code | Third cache entry to invalidate; network round-trip on every setup selection change | Never — the calculation is two subtractions using data already in client cache |
|
||||
| Pros/cons as unstructured free-text blobs | Zero schema complexity | Comparison view cannot render bullets; columns misalign | Never for comparison display — use newline-delimited format from day one |
|
||||
| Comparison grid with `overflow: hidden` on narrow viewports | Avoids horizontal scroll complexity | Comparison becomes unreadable on laptop with panels open; critical feature breaks | Never — horizontal scroll is the correct behavior for comparison tables |
|
||||
| Rendering comparison for resolved threads without guard | Simpler component logic | Users can drag-reorder resolved threads, corrupting state | Never — the resolved-thread guard is a correctness requirement |
|
||||
| `DragOverlay` using same component as `useSortable` | Less component code | ID collision in dnd-kit causes undefined behavior during drag | Never — dnd-kit explicitly requires a separate presentational component for DragOverlay |
|
||||
|
||||
---
|
||||
|
||||
## Integration Gotchas
|
||||
|
||||
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.
|
||||
Common mistakes when connecting new v1.3 features to existing v1.2 systems.
|
||||
|
||||
| Integration Point | Common Mistake | Correct Approach |
|
||||
|-------------------|----------------|------------------|
|
||||
| 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." |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| Ranking + React Query | Using `setQueryData` alone for optimistic reorder, causing flicker | Maintain `tempItems` local state in the drag component; render from `tempItems ?? queryData.candidates`; clear on `onSettled` |
|
||||
| Impact preview + weight unit | Computing delta in grams but displaying with `formatWeight` that expects the stored unit | Delta is always computed in grams (raw stored values); apply `formatWeight(delta, unit)` once at display time, same pattern as all other weight displays |
|
||||
| Impact preview + null weights | Treating `null` weightGrams as 0 in delta calculation | Show "-- (no weight data)" explicitly; never pass null to arithmetic; guard with `candidate.weightGrams != null && setup.totalWeight != null` |
|
||||
| Pros/cons + thread resolution | Pros/cons text copied to collection item on resolve | Do NOT copy pros/cons to the items table — these are planning notes, not collection metadata. `resolveThread` in `thread.service.ts` should remain unchanged |
|
||||
| Rank order + existing `getThreadWithCandidates` | Adding `ORDER BY sort_order` to `getThreadWithCandidates` changes the order of an existing query used by other components | Add `sort_order` to the SELECT and ORDER BY in `getThreadWithCandidates`. Audit all consumers of this query to verify they are unaffected by ordering change (the candidate cards already render in whatever order the query returns) |
|
||||
| Comparison view + `isActive` prop | `CandidateCard.tsx` uses `isActive` to show/hide the "Winner" button. Comparison view must not show "Winner" button inline if comparison has its own resolve affordance | Pass `isActive={false}` to `CandidateCard` when rendering inside comparison view, or create a separate `CandidateComparisonCard` presentational component that omits action buttons |
|
||||
|
||||
---
|
||||
|
||||
## Performance Traps
|
||||
|
||||
@@ -231,11 +264,12 @@ Patterns that work at small scale but fail as usage grows.
|
||||
|
||||
| Trap | Symptoms | Prevention | When It Breaks |
|
||||
|------|----------|------------|----------------|
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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) |
|
||||
| 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) |
|
||||
| Bulk integer rank updates on every drag | Visible latency after each drop; multiple UPDATE statements per drag; SQLite write lock held | Use fractional `sortOrder REAL` so only the moved item requires an UPDATE | 8+ candidates per thread with rapid dragging |
|
||||
| Comparison view fetching all candidates for all threads | Slow initial load; excessive memory for large thread lists | Comparison view uses the already-loaded `["threads", threadId]` query; never fetches candidates outside the active thread's query | 20+ threads with 5+ candidates each |
|
||||
| Sync rank updates on every `dragOver` event (not just `dragEnd`) | Thousands of UPDATE mutations during a single drag; server overwhelmed; UI lags | Persist rank only on `onDragEnd` (drop), never on `onDragOver` (in-flight hover) | Any usage — `onDragOver` fires on every cursor pixel moved |
|
||||
| `useQuery` for setups list inside impact preview component | N+1 query pattern: each candidate card fetches its own setup list | Lift setup list query to the thread detail page level; pass selected setup as prop or context | 3+ candidates in comparison view |
|
||||
|
||||
---
|
||||
|
||||
## Security Mistakes
|
||||
|
||||
@@ -243,9 +277,11 @@ Domain-specific security issues beyond general web security.
|
||||
|
||||
| Mistake | Risk | Prevention |
|
||||
|---------|------|------------|
|
||||
| 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"])`. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| `sortOrder` accepts any float value | Malformed values like `NaN`, `Infinity`, or extremely large floats stored in `sort_order` column, corrupting order | Validate `sortOrder` as a finite number in Zod schema: `z.number().finite()`. Reject `NaN` and `Infinity` at API boundary |
|
||||
| Pros/cons fields with no length limit | Users or automated input can store multi-kilobyte text blobs, inflating the database and slowing candidate queries | Cap at 500 characters per field in Zod: `z.string().max(500).optional()` |
|
||||
| Rank update endpoint accepts any candidateId | A crafted request can reorder candidates from a different thread by passing a candidateId that belongs to another thread | In the rank update service, verify `candidate.threadId === threadId` before applying the update — same pattern as existing `resolveThread` validation |
|
||||
|
||||
---
|
||||
|
||||
## UX Pitfalls
|
||||
|
||||
@@ -253,28 +289,33 @@ Common user experience mistakes in this domain.
|
||||
|
||||
| Pitfall | User Impact | Better Approach |
|
||||
|---------|-------------|-----------------|
|
||||
| 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. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| 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?"). |
|
||||
| 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. |
|
||||
| Comparison table loses column headers on scroll | User scrolls down to see notes/pros/cons and forgets which column is which candidate | Sticky column headers with candidate name, image thumbnail, and weight. Use `position: sticky; top: 0` on the header row |
|
||||
| Delta shows raw gram values when user prefers oz | Impact preview shows "+450g" to a user who has set their unit to oz | Apply `formatWeight(delta, unit)` using the `useWeightUnit()` hook, same as all other weight displays in the app |
|
||||
| Drag-to-reorder with no visual rank indicator | After ranking, it is unclear that the order matters or that #1 is the "top pick" | Show rank numbers (1, 2, 3...) as badges on each candidate card when in ranking mode. Update numbers live during drag |
|
||||
| Pros/cons fields empty by default in comparison view | Comparison table shows empty cells next to populated ones, making the comparison feel sparse and incomplete | Show a subtle "Add pros/cons" prompt in empty cells when the thread is active. In read-only resolved view, hide the pros/cons section entirely if no candidate has data |
|
||||
| Impact preview setup selector defaults to no setup | User arrives at comparison view and sees no impact numbers because no setup is pre-selected | Default the setup selector to the most recently viewed/modified setup. Persist the last-selected setup in `sessionStorage` or a URL param |
|
||||
| Removing a candidate clears comparison selection | User has candidates A, B, C in comparison; deletes C; comparison resets entirely | Comparison state (which candidates are selected) should be stored in local component state keyed by candidate ID. On delete, simply remove that ID from the selection |
|
||||
|
||||
---
|
||||
|
||||
## "Looks Done But Isn't" Checklist
|
||||
|
||||
Things that appear complete but are missing critical pieces.
|
||||
|
||||
- [ ] **Search/filter:** Often missing keyboard shortcut (Cmd/Ctrl+K to focus search) -- verify search is easily accessible without mouse
|
||||
- [ ] **Search/filter:** Often missing empty state for "no results" -- verify a helpful message appears when search matches nothing, distinct from "collection is empty"
|
||||
- [ ] **Weight classification:** Often missing the per-setup model -- verify the same item can have different classifications in different setups
|
||||
- [ ] **Weight classification:** Often missing "unclassified" handling -- verify items with no classification default to "base" in all computations
|
||||
- [ ] **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
|
||||
- [ ] **Weight chart:** Often missing responsiveness -- verify chart renders correctly on mobile widths (Recharts needs `ResponsiveContainer` wrapper)
|
||||
- [ ] **Candidate status:** Often missing transition validation -- verify a candidate cannot go from "arrived" back to "researching"
|
||||
- [ ] **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
|
||||
- [ ] **Drag-to-reorder:** Often missing drag handles — verify the drag affordance is visually distinct (grip icon), not just "drag anywhere on the card" which conflicts with the existing click-to-edit behavior
|
||||
- [ ] **Drag-to-reorder:** Often missing keyboard reorder fallback — verify candidates can be moved with arrow keys for accessibility (dnd-kit's `KeyboardSensor` must be added to `DndContext`)
|
||||
- [ ] **Drag-to-reorder:** Often missing flicker fix — verify dropping a candidate does not briefly snap back to original position (requires `tempItems` local state, not just `setQueryData`)
|
||||
- [ ] **Drag-to-reorder:** Often missing resolved-thread guard — verify drag handles are hidden and mutations are blocked on resolved threads
|
||||
- [ ] **Impact preview:** Often missing the null weight case — verify candidates with no weight show "-- (no weight data)" not "NaNg" or "+0g"
|
||||
- [ ] **Impact preview:** Often missing the replace-vs-add distinction — verify the user can specify which existing item would be replaced, not just see a pure addition delta
|
||||
- [ ] **Impact preview:** Often missing unit conversion — verify the delta respects `useWeightUnit()` and `useCurrency()`, not hardcoded to grams/USD
|
||||
- [ ] **Side-by-side comparison:** Often missing horizontal scroll on narrow viewports — verify the view is usable at 768px without column collapsing
|
||||
- [ ] **Side-by-side comparison:** Often missing sticky headers — verify candidate names remain visible when scrolling the comparison rows
|
||||
- [ ] **Pros/cons fields:** Often missing length validation — verify Zod schema caps the field and the textarea shows a character counter
|
||||
- [ ] **Pros/cons display:** Often missing newline-to-bullet rendering — verify newlines in the stored text render as bullet points in the comparison view, not as `\n` characters
|
||||
- [ ] **Schema changes:** Often missing test helper update — verify `tests/helpers/db.ts` includes `sort_order`, `pros`, and `cons` columns after the schema migration
|
||||
|
||||
---
|
||||
|
||||
## Recovery Strategies
|
||||
|
||||
@@ -282,13 +323,15 @@ When pitfalls occur despite prevention, how to recover.
|
||||
|
||||
| Pitfall | Recovery Cost | Recovery Steps |
|
||||
|---------|---------------|----------------|
|
||||
| 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. |
|
||||
| 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. |
|
||||
| Chart data disagrees with totals | LOW | Refactor chart to use the same data source as totals. Create shared utility. No data migration needed. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| Drag flicker due to no `tempItems` local state | LOW | Add `tempItems` state to the ranking component. Render from `tempItems ?? queryData.candidates`. No data migration needed. |
|
||||
| Integer `sortOrder` causing bulk updates | MEDIUM | Add Drizzle migration to change `sort_order` column type from INTEGER to REAL. Update existing rows to spaced values (1000, 2000, 3000...). Update service layer to use fractional logic. |
|
||||
| Delta treats null weight as 0 | LOW | Add null guards in the delta calculation component. No data changes needed. |
|
||||
| Pros/cons stored as unformatted blobs | LOW | No migration needed — the data is still correct. Update the rendering component to split on newlines. Add length validation to the Zod schema for new input. |
|
||||
| Comparison view visible on resolved threads | LOW | Add `if (thread.status === 'resolved') return <ResolvedView />` before rendering the comparison/ranking UI. Add 400 check in the rank update API route. |
|
||||
| Test helper out of sync with schema | LOW | Update CREATE TABLE statements in `tests/helpers/db.ts`. Run `bun test`. Fix any test that relied on the old column count. |
|
||||
| Rank update accepts cross-thread candidateId | LOW | Add `candidate.threadId !== threadId` guard in rank update service (same pattern as existing `resolveThread` guard). |
|
||||
|
||||
---
|
||||
|
||||
## Pitfall-to-Phase Mapping
|
||||
|
||||
@@ -296,27 +339,30 @@ How roadmap phases should address these pitfalls.
|
||||
|
||||
| Pitfall | Prevention Phase | Verification |
|
||||
|---------|------------------|--------------|
|
||||
| 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. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
| Test helper desync | Every schema-changing phase | Each phase's PR includes updated test helper. CI test suite catches column mismatches. |
|
||||
| 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. |
|
||||
| dnd-kit + React Query flicker | Candidate ranking phase | Drop a candidate, verify no snap-back. Add automated test: mock drag end, verify list order reflects drop position immediately. |
|
||||
| Bulk integer rank writes | Schema design for ranking | `sortOrder` column is `REAL` type in Drizzle schema. Service layer issues exactly one UPDATE per reorder. Test: reorder 5 candidates, verify only 1 DB write. |
|
||||
| Stale data in impact preview | Impact preview phase | Change a candidate's weight, verify delta updates immediately. Select a different setup, verify delta recalculates from new baseline. |
|
||||
| Comparison broken at narrow width | Comparison UI phase | Test at 768px viewport. Verify horizontal scroll is present and content is readable. No vertical stack of comparison columns. |
|
||||
| Pros/cons as unstructured blobs | Ranking schema phase (when columns added) | Verify Zod schema caps at 500 chars. Verify comparison view renders newlines as bullets. Test: enter 3-line pros text, verify 3 bullets rendered. |
|
||||
| Impact preview add vs replace | Impact preview design phase | Thread with same-category item in setup defaults to replace mode. Pure-add mode available as alternative. Test: replace mode shows negative delta when candidate is lighter. |
|
||||
| Comparison/rank on resolved threads | Both comparison and ranking phases | Verify drag handles are absent on resolved threads. Verify rank update API returns 400 for resolved thread. |
|
||||
| Test helper schema drift | Every schema-touching phase of v1.3 | After schema change, run `bun test` immediately. Zero test failures from column-not-found errors. |
|
||||
|
||||
---
|
||||
|
||||
## Sources
|
||||
|
||||
- [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
|
||||
- [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
|
||||
- [LighterPack user classification errors](https://www.99boulders.com/lighterpack-tutorial) -- LighterPack's approach to base/worn/consumable
|
||||
- [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
|
||||
- [TanStack Query discussions on filtering with cache](https://github.com/TanStack/query/discussions/1113) -- community patterns for client-side vs server-side filtering
|
||||
- [Recharts performance and limitations](https://blog.logrocket.com/best-react-chart-libraries-2025/) -- SVG rendering pitfalls, ResponsiveContainer requirement
|
||||
- [Drizzle ORM SQLite migration pitfalls](https://github.com/drizzle-team/drizzle-orm/issues/1313) -- data loss bug with push + add column
|
||||
- [State machine anti-patterns](https://rclayton.silvrback.com/use-state-machines) -- importance of explicit transition validation
|
||||
- [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
|
||||
- [dnd-kit Discussion #1522: React Query + DnD flicker](https://github.com/clauderic/dnd-kit/discussions/1522) — `tempItems` solution for React Query cache flicker
|
||||
- [dnd-kit Issue #921: Sorting not working with React Query](https://github.com/clauderic/dnd-kit/issues/921) — Root cause of the state lifecycle mismatch
|
||||
- [dnd-kit Sortable Docs: OptimisticSortingPlugin](https://dndkit.com/concepts/sortable) — New API for handling optimistic reorder
|
||||
- [TanStack Query: Optimistic Updates guide](https://tanstack.com/query/v4/docs/react/guides/optimistic-updates) — `onMutate`/`onSettled` rollback patterns
|
||||
- [Fractional Indexing: Steveruiz.me](https://www.steveruiz.me/posts/reordering-fractional-indices) — Why fractional keys beat integer reorder for databases
|
||||
- [Fractional Indexing SQLite library](https://github.com/sqliteai/fractional-indexing) — Implementation reference for base62 lexicographic sort keys
|
||||
- [Baymard Institute: Comparison Tool Design](https://baymard.com/blog/user-friendly-comparison-tools) — Sticky headers, horizontal scroll, minimum column width for product comparison UX
|
||||
- [NN/G: Comparison Tables](https://www.nngroup.com/articles/comparison-tables/) — Avoid prose in comparison cells; use scannable structured values
|
||||
- [LogRocket: When comparison charts hurt UX](https://blog.logrocket.com/ux-design/feature-comparison-tips-when-not-to-use/) — Comparison table anti-patterns
|
||||
- Direct codebase analysis of GearBox v1.2 (schema.ts, thread.service.ts, setup.service.ts, CandidateCard.tsx, useSetups.ts, useCandidates.ts, tests/) — existing patterns, integration points, and established conventions
|
||||
|
||||
---
|
||||
*Pitfalls research for: GearBox v1.2 -- Collection Power-Ups (search/filter, weight classification, charts, candidate status, unit selection)*
|
||||
*Pitfalls research for: GearBox v1.3 — Research & Decision Tools (side-by-side comparison, impact preview, candidate ranking)*
|
||||
*Researched: 2026-03-16*
|
||||
|
||||
@@ -1,179 +1,198 @@
|
||||
# Technology Stack -- v1.2 Collection Power-Ups
|
||||
# Stack Research -- v1.3 Research & Decision Tools
|
||||
|
||||
**Project:** GearBox
|
||||
**Researched:** 2026-03-16
|
||||
**Scope:** Stack additions for search/filter, weight classification, weight distribution charts, candidate status tracking, weight unit selection
|
||||
**Scope:** Stack additions for side-by-side candidate comparison, setup impact preview, and drag-to-reorder candidate ranking with pros/cons
|
||||
**Confidence:** HIGH
|
||||
|
||||
## Key Finding: Minimal New Dependencies
|
||||
## Key Finding: Zero New Dependencies
|
||||
|
||||
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.
|
||||
All three v1.3 features are achievable with the existing stack. The drag-to-reorder feature, which would normally require a dedicated DnD library, is covered by `framer-motion`'s built-in `Reorder` component — already installed at v12.37.0 with React 19 support confirmed.
|
||||
|
||||
## New Dependency
|
||||
## Recommended Stack: Existing Technologies Only
|
||||
|
||||
### Charting: react-minimal-pie-chart
|
||||
### No New Dependencies Required
|
||||
|
||||
| Technology | Version | Purpose | Why |
|
||||
|------------|---------|---------|-----|
|
||||
| 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. |
|
||||
| Feature | Library Needed | Status |
|
||||
|---------|---------------|--------|
|
||||
| Side-by-side comparison view | None — pure layout/UI | Existing Tailwind CSS |
|
||||
| Setup impact preview | None — SQL delta calculation | Existing Drizzle ORM + TanStack Query |
|
||||
| Drag-to-reorder candidates | `Reorder` component | Already in `framer-motion@12.37.0` |
|
||||
| Pros/cons text fields | None — schema + form | Existing Drizzle + Zod + React |
|
||||
|
||||
**Why this over alternatives:**
|
||||
### How Each Feature Uses the Existing Stack
|
||||
|
||||
| Criterion | react-minimal-pie-chart | Recharts | Custom SVG | Chart.js |
|
||||
|-----------|------------------------|----------|------------|----------|
|
||||
| Bundle size | ~2kB gzipped | ~97kB gzipped | 0kB | ~60kB gzipped |
|
||||
| Chart types needed | Pie + donut (exactly what we need) | Overkill (line, bar, area, scatter, etc.) | Manual math | Overkill |
|
||||
| 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 |
|
||||
#### 1. Side-by-Side Candidate Comparison
|
||||
|
||||
**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.
|
||||
**No schema changes. No new dependencies.**
|
||||
|
||||
| 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() })`. |
|
||||
| Tailwind CSS v4 | Responsive comparison table layout. Horizontal scroll on mobile with `overflow-x-auto`. Fixed first column (row labels) using `sticky left-0`. |
|
||||
| TanStack Query (`useThread`) | Thread detail already fetches all candidates in one query. Comparison view reads from the same cached data — no new API endpoint. |
|
||||
| Lucide React | Comparison row icons (weight, price, status, link). Already in the curated icon set. |
|
||||
| `formatWeight` / `formatPrice` | Existing formatters handle display with selected unit/currency. No changes needed. |
|
||||
| `useWeightUnit` / `useCurrency` | Existing hooks provide formatting context. Comparison view uses them identically to `CandidateCard`. |
|
||||
|
||||
**Implementation approach:** Add query parameters to `GET /api/items` rather than client-side filtering. Drizzle's conditional filter pattern handles optional params cleanly:
|
||||
**Implementation approach:** Add a view toggle (grid vs. comparison table) to the thread detail page. The comparison view is a `<table>` or CSS grid with candidates as columns and attributes as rows. Data already lives in `useThread` response — no API changes.
|
||||
|
||||
#### 2. Setup Impact Preview
|
||||
|
||||
**No new dependencies. Requires one new API endpoint.**
|
||||
|
||||
| Existing Tech | How It Is Used |
|
||||
|---------------|----------------|
|
||||
| Drizzle ORM | New query: for a given setup, sum `weight_grams` and `price_cents` of its items. Then compute delta against each candidate's `weight_grams` and `price_cents`. Pure arithmetic in the service layer. |
|
||||
| TanStack Query | New `useSetupImpact(threadId, setupId)` hook fetching `GET /api/threads/:threadId/impact?setupId=X`. Returns array of `{ candidateId, weightDelta, costDelta }`. |
|
||||
| Hono + Zod validator | New route validates `setupId` query param. Delegates to service function. |
|
||||
| `formatWeight` / `formatPrice` | Format deltas with `+` prefix for positive values (candidate adds weight/cost) and `-` for negative (candidate is lighter/cheaper than what's already in setup). |
|
||||
| `useSetups` hook | Existing `useSetups()` provides the setup list for the picker dropdown. |
|
||||
|
||||
**Delta calculation logic (server-side service):**
|
||||
|
||||
```typescript
|
||||
import { like, eq, and } from "drizzle-orm";
|
||||
// For each candidate in thread:
|
||||
// weightDelta = candidate.weightGrams - (matching item in setup).weightGrams
|
||||
// If no matching item in setup (it would be added, not replaced): delta = candidate.weightGrams
|
||||
|
||||
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));
|
||||
// A "matching item" means: item in setup with same categoryId as the thread.
|
||||
// This is the intended semantic: "how does picking this candidate affect my setup?"
|
||||
```
|
||||
|
||||
### 2. Weight Classification (Base/Worn/Consumable)
|
||||
**Key decision:** Impact preview is read-only and derived. It does not mutate any data. It computes what *would* happen if the candidate were picked, without modifying the setup. The delta is displayed inline on each candidate card or in the comparison view.
|
||||
|
||||
**No new dependencies.** Schema change + UI state.
|
||||
#### 3. Drag-to-Reorder Candidate Ranking with Pros/Cons
|
||||
|
||||
**No new DnD library. Requires schema changes.**
|
||||
|
||||
| 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`. |
|
||||
| `framer-motion@12.37.0` `Reorder` | `Reorder.Group` wraps the candidate list. `Reorder.Item` wraps each candidate card. `onReorder` updates local order state. `onDragEnd` fires the persist mutation. |
|
||||
| Drizzle ORM | Two new columns on `thread_candidates`: `sortOrder integer` (default 0, lower = higher rank) and `pros text` / `cons text` (nullable). |
|
||||
| TanStack Query mutation | `usePatchCandidate` for pros/cons text updates. `useReorderCandidates` for bulk sort order update after drag-end. |
|
||||
| Hono + Zod validator | `PATCH /api/threads/:threadId/candidates/reorder` accepts `{ candidates: Array<{ id, sortOrder }> }`. `PATCH /api/candidates/:id` accepts `{ pros?, cons? }`. |
|
||||
| Zod | Extend `updateCandidateSchema` with `pros: z.string().nullable().optional()`, `cons: z.string().nullable().optional()`, `sortOrder: z.number().int().optional()`. |
|
||||
|
||||
**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" }> }`.
|
||||
**Framer Motion `Reorder` API pattern:**
|
||||
|
||||
### 3. Weight Distribution Charts
|
||||
```typescript
|
||||
import { Reorder } from "framer-motion";
|
||||
|
||||
**One new dependency:** `react-minimal-pie-chart` (documented above).
|
||||
// State holds candidates sorted by sortOrder
|
||||
const [orderedCandidates, setOrderedCandidates] = useState(
|
||||
[...candidates].sort((a, b) => a.sortOrder - b.sortOrder)
|
||||
);
|
||||
|
||||
| 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. |
|
||||
// onReorder fires continuously during drag — update local state only
|
||||
// onDragEnd fires once on drop — persist to DB
|
||||
<Reorder.Group
|
||||
axis="y"
|
||||
values={orderedCandidates}
|
||||
onReorder={setOrderedCandidates}
|
||||
>
|
||||
{orderedCandidates.map((candidate) => (
|
||||
<Reorder.Item
|
||||
key={candidate.id}
|
||||
value={candidate}
|
||||
onDragEnd={() => persistOrder(orderedCandidates)}
|
||||
>
|
||||
<CandidateCard ... />
|
||||
</Reorder.Item>
|
||||
))}
|
||||
</Reorder.Group>
|
||||
```
|
||||
|
||||
**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`.
|
||||
**Schema changes required:**
|
||||
|
||||
### 4. Candidate Status Tracking
|
||||
| Table | Column | Type | Default | Purpose |
|
||||
|-------|--------|------|---------|---------|
|
||||
| `thread_candidates` | `sort_order` | `integer NOT NULL` | `0` | Rank position (lower = higher rank) |
|
||||
| `thread_candidates` | `pros` | `text` | `NULL` | Free-text pros annotation |
|
||||
| `thread_candidates` | `cons` | `text` | `NULL` | Free-text cons annotation |
|
||||
|
||||
**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.
|
||||
**Sort order persistence pattern:** On drag-end, send the full reordered array with new `sortOrder` values (0-based index positions). Backend replaces existing `sort_order` values atomically. This is the same delete-all + re-insert pattern used for `setupItems` but as an UPDATE instead.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# Only new dependency for v1.2
|
||||
bun add react-minimal-pie-chart
|
||||
# No new packages. Zero.
|
||||
```
|
||||
|
||||
That is it. One package, under 2kB gzipped.
|
||||
All required capabilities are already installed.
|
||||
|
||||
## Schema Changes Summary
|
||||
## Alternatives Considered
|
||||
|
||||
These are the Drizzle schema modifications needed (no new tables, just column additions):
|
||||
### Drag and Drop: Why Not Add a Dedicated Library?
|
||||
|
||||
| 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. |
|
||||
| Option | Version | React 19 Status | Verdict |
|
||||
|--------|---------|-----------------|---------|
|
||||
| `framer-motion` Reorder (already installed) | 12.37.0 | React 19 explicit peerDep (`^18.0.0 || ^19.0.0`) | USE THIS |
|
||||
| `@dnd-kit/core` + `@dnd-kit/sortable` | 6.3.1 | No React 19 support (stale ~1yr, open GitHub issue #1511) | AVOID |
|
||||
| `@dnd-kit/react` (new rewrite) | 0.3.2 | React 19 compatible | Pre-1.0, no maintainer ETA on stable |
|
||||
| `@hello-pangea/dnd` | 18.0.1 | No React 19 (stale ~1yr, peerDep `^18.0.0` only) | AVOID |
|
||||
| `pragmatic-drag-and-drop` | latest | Core is React-agnostic but some sub-packages missing React 19 | Overkill for a single sortable list |
|
||||
| Custom HTML5 DnD | N/A | N/A | 200+ lines of boilerplate, worse accessibility |
|
||||
|
||||
**Why framer-motion `Reorder` wins:** Already in the bundle. React 19 peer dep confirmed in lockfile. Handles the single use case (vertical sortable list) with 10 lines of code. Provides smooth layout animations at zero additional cost. The limitation (no cross-container drag, no multi-row grid) does not apply — candidate ranking is a single vertical list.
|
||||
|
||||
**Why not `@dnd-kit`:** The legacy `@dnd-kit/core@6.3.1` has no official React 19 support and has been unmaintained for ~1 year. The new `@dnd-kit/react@0.3.2` does support React 19 but is pre-1.0 with zero maintainer response on stability/roadmap questions (GitHub Discussion #1842 has 0 replies). Adding a pre-1.0 library when the project already has a working solution is unjustifiable.
|
||||
|
||||
### Setup Impact: Why Not Client-Side Calculation?
|
||||
|
||||
Client-side delta calculation (using cached React Query data) is simpler to implement but:
|
||||
- Requires loading both the full setup items list AND all candidates into the client
|
||||
- Introduces staleness bugs if setup items change in another tab
|
||||
- Is harder to test (service test vs. component test)
|
||||
|
||||
Server-side calculation in a service function is testable, authoritative, and consistent with the existing architecture (services compute aggregates, not components).
|
||||
|
||||
## What NOT to Add
|
||||
|
||||
| Avoid | Why | Use Instead |
|
||||
|-------|-----|-------------|
|
||||
| Recharts | 97kB for one chart type. React 19 edge-case issues. D3 dependency chain. | react-minimal-pie-chart (2kB) |
|
||||
| Chart.js / react-chartjs-2 | Canvas-based (harder to style with Tailwind). Open React 19 peer dep issues. Overkill. | react-minimal-pie-chart |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
| `@dnd-kit/core` + `@dnd-kit/sortable` | No React 19 support, stale for ~1 year (latest 6.3.1 from 2024) | `framer-motion` Reorder (already installed) |
|
||||
| `@hello-pangea/dnd` | No React 19 support, peerDep `react: "^18.0.0"` only, stale | `framer-motion` Reorder |
|
||||
| `react-comparison-table` or similar component packages | Fragile third-party layouts for a simple table. Custom Tailwind table is trivial and design-consistent. | Custom Tailwind CSS table layout |
|
||||
| Modal/dialog library (Radix, Headless UI) | The project already has a hand-rolled modal pattern (`SlideOutPanel`, `ConfirmDialog`). Adding a library for one more dialog adds inconsistency. | Extend existing modal patterns |
|
||||
| Rich text editor for pros/cons | Markdown editors are overkill for a single-line annotation field. Users want a quick note, not a document. | Plain `<textarea>` with Tailwind styling |
|
||||
|
||||
## Existing Stack Version Compatibility
|
||||
## Stack Patterns by Variant
|
||||
|
||||
All existing dependencies remain unchanged. The only version consideration:
|
||||
**If the comparison view needs mobile scroll:**
|
||||
- Wrap comparison table in `overflow-x-auto`
|
||||
- Freeze the first column (attribute labels) with `sticky left-0 bg-white z-10`
|
||||
- This is pure CSS, no JavaScript or library needed
|
||||
|
||||
| New Package | Compatible With | Verified |
|
||||
|-------------|-----------------|----------|
|
||||
| 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. |
|
||||
| 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. |
|
||||
**If the setup impact preview needs a setup picker:**
|
||||
- Use `useSetups()` (already exists) to populate a `<select>` dropdown
|
||||
- Store selected setup ID in local component state (not URL params — this is transient UI)
|
||||
- No new state management needed
|
||||
|
||||
**If pros/cons fields need to auto-save:**
|
||||
- Use a debounced mutation (300-500ms) that fires on `onChange`
|
||||
- Or save on `onBlur` (simpler, adequate for this use case)
|
||||
- Existing `useUpdateCandidate` hook already handles candidate mutations — extend schema only
|
||||
|
||||
## Version Compatibility
|
||||
|
||||
| Package | Version in Project | React 19 Compatible | Notes |
|
||||
|---------|-------------------|---------------------|-------|
|
||||
| `framer-motion` | 12.37.0 | YES — peerDeps `"^18.0.0 || ^19.0.0"` confirmed in lockfile | `Reorder` component available since v5 |
|
||||
| `drizzle-orm` | 0.45.1 | N/A (server-side) | ALTER TABLE or migration for new columns |
|
||||
| `zod` | 4.3.6 | N/A | Extend existing schemas |
|
||||
| `@tanstack/react-query` | 5.90.21 | YES | New hooks follow existing patterns |
|
||||
|
||||
## Sources
|
||||
|
||||
- [Drizzle ORM Filter Operators](https://orm.drizzle.team/docs/operators) -- `like`, `eq`, `and`, `or` operators for search/filter (HIGH confidence)
|
||||
- [Drizzle ORM Conditional Filters Guide](https://orm.drizzle.team/docs/guides/conditional-filters-in-query) -- dynamic filter composition pattern (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)
|
||||
- [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)
|
||||
- [Recharts npm](https://www.npmjs.com/package/recharts) -- v3.8.0, ~97kB bundle (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)
|
||||
- [LighterPack weight classification model](https://lighterpack.com) -- base/worn/consumable terminology is industry standard for gear management (HIGH confidence)
|
||||
- [Pack Weight Calculator Guide](https://backpackpeek.com/blog/pack-weight-calculator-base-weight-guide) -- weight classification definitions (HIGH confidence)
|
||||
- [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)
|
||||
- [framer-motion package lockfile entry] — peerDeps `react: "^18.0.0 || ^19.0.0"` confirmed (HIGH confidence, from project's `bun.lock`)
|
||||
- [Motion Reorder docs](https://motion.dev/docs/react-reorder) — `Reorder.Group`, `Reorder.Item`, `useDragControls` API, `onDragEnd` pattern for persisting order (HIGH confidence)
|
||||
- [Motion Changelog](https://motion.dev/changelog) — v12.37.0 actively maintained through Feb 2026 (HIGH confidence)
|
||||
- [@dnd-kit/core npm](https://www.npmjs.com/package/@dnd-kit/core) — v6.3.1, last published ~1 year ago, no React 19 support (HIGH confidence)
|
||||
- [dnd-kit React 19 issue #1511](https://github.com/clauderic/dnd-kit/issues/1511) — CLOSED but React 19 TypeScript issues confirmed (MEDIUM confidence)
|
||||
- [@dnd-kit/react roadmap discussion #1842](https://github.com/clauderic/dnd-kit/discussions/1842) — 0 maintainer replies on stability question (HIGH confidence — signals pre-1.0 risk)
|
||||
- [hello-pangea/dnd React 19 issue #864](https://github.com/hello-pangea/dnd/issues/864) — React 19 support still open as of Jan 2026 (HIGH confidence)
|
||||
- [Top 5 Drag-and-Drop Libraries for React 2026](https://puckeditor.com/blog/top-5-drag-and-drop-libraries-for-react) — ecosystem overview confirming dnd-kit and hello-pangea/dnd limitations (MEDIUM confidence)
|
||||
|
||||
---
|
||||
*Stack research for: GearBox v1.2 -- Collection Power-Ups*
|
||||
*Stack research for: GearBox v1.3 -- Research & Decision Tools*
|
||||
*Researched: 2026-03-16*
|
||||
|
||||
@@ -1,207 +1,181 @@
|
||||
# Project Research Summary
|
||||
|
||||
**Project:** GearBox v1.2 -- Collection Power-Ups
|
||||
**Domain:** Gear management (bikepacking, sim racing, etc.) -- feature enhancement milestone
|
||||
**Project:** GearBox v1.3 — Research & Decision Tools
|
||||
**Domain:** Gear management — candidate comparison, setup impact preview, drag-to-reorder ranking with pros/cons
|
||||
**Researched:** 2026-03-16
|
||||
**Confidence:** HIGH
|
||||
|
||||
## Executive Summary
|
||||
|
||||
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.
|
||||
GearBox v1.3 adds three decision-support features to the existing thread detail page: side-by-side candidate comparison, setup impact preview (weight/cost delta), and drag-to-reorder candidate ranking with pros/cons annotation. All four research areas converge on the same conclusion — the existing stack is sufficient and no new dependencies are required. `framer-motion@12.37.0` (already installed) provides the `Reorder` component for drag-to-reorder, eliminating the need for `@dnd-kit` (which lacks React 19 support) or any other library. Two of the three features (comparison view and impact preview) require zero schema changes and can be built as pure client-side derived views using data already cached by `useThread()` and `useSetup()`.
|
||||
|
||||
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 recommended build sequence is dependency-driven: schema migration first (adds `sort_order`, `pros`, `cons` to `thread_candidates`), then ranking UI (uses the new columns), then comparison view and impact preview in parallel (both are schema-independent client additions). This order eliminates the risk of mid-feature migrations and ensures the comparison table can display rank, pros, and cons from day one rather than being retrofitted. The entire milestone touches 3 new files and 10 modified files — a contained, low-blast-radius changeset.
|
||||
|
||||
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.
|
||||
The primary risks are implementation-level rather than architectural. Three patterns require deliberate design before coding: (1) use `tempItems` local state alongside React Query for drag reorder to prevent the well-documented flicker bug, (2) use `sortOrder REAL` (fractional) instead of `INTEGER` to avoid bulk UPDATE writes on every drag, and (3) treat impact preview as an "add vs replace" decision — not just a pure addition — since users comparing gear are almost always replacing an existing item, not stacking one on top. All three are avoidable with upfront design; recovery cost is low but retrofitting is disruptive.
|
||||
|
||||
## Key Findings
|
||||
|
||||
### Recommended Stack
|
||||
|
||||
The existing stack (React 19, Hono, Drizzle ORM, SQLite, Bun) handles all v1.2 features without modification. One small library addition is needed.
|
||||
Zero new dependencies are needed for this milestone. The existing stack handles all three features: Tailwind CSS for the comparison table layout, `framer-motion`'s `Reorder` component for drag ordering, Drizzle ORM + Hono + Zod for the one new write endpoint (`PATCH /api/threads/:id/candidates/reorder`), and TanStack Query for the new `useReorderCandidates` mutation. All other React Query hooks (`useThread`, `useSetup`, `useSetups`) already exist and return the data needed for comparison and impact preview without modification.
|
||||
|
||||
**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:**
|
||||
- `framer-motion@12.37.0` (Reorder component): drag-to-reorder — already installed, React 19 peerDeps confirmed in `bun.lock`, replaces any need for `@dnd-kit`
|
||||
- `drizzle-orm@0.45.1`: three new columns on `thread_candidates` (`sort_order REAL`, `pros TEXT`, `cons TEXT`) plus one new service function (`reorderCandidates`)
|
||||
- Tailwind CSS v4: comparison table layout with `overflow-x-auto`, `sticky left-0` for frozen label column, `min-w-[200px]` per candidate column
|
||||
- TanStack Query v5 + existing hooks: impact preview and comparison view derived entirely from cached `useThread` + `useSetup` data — no new API endpoints on read paths
|
||||
- Zod v4: extend `updateCandidateSchema` with `sortOrder: z.number().finite()`, `pros: z.string().max(500).optional()`, `cons: z.string().max(500).optional()`
|
||||
|
||||
**New dependency:**
|
||||
- **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).
|
||||
|
||||
**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)
|
||||
**What NOT to use:**
|
||||
- `@dnd-kit/core@6.3.1` — no React 19 support, unmaintained for ~1 year
|
||||
- `@dnd-kit/react@0.3.2` — pre-1.0, no maintainer response on stability
|
||||
- `@hello-pangea/dnd@18.0.1` — `peerDep react: "^18.0.0"` only, stale
|
||||
- Any third-party comparison table component — custom Tailwind table is trivial and design-consistent
|
||||
|
||||
### Expected Features
|
||||
|
||||
All five v1.3 features are confirmed as P1 (must-have for this milestone). No existing gear management tool (LighterPack, GearGrams, OutPack) has comparison view, delta preview, or ranking — these are unmet-need differentiators adapted from e-commerce comparison UX to the gear domain.
|
||||
|
||||
**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
|
||||
- Side-by-side comparison view — users juggling 3+ candidates mentally across cards expect tabular layout; NNGroup and Smashing Magazine confirm this is the standard for comparison contexts
|
||||
- Weight and cost delta per candidate — gear apps always display weight prominently; delta is more actionable than raw weight
|
||||
- Setup selector for impact preview — required to contextualize the delta; `useSetups()` already exists
|
||||
|
||||
**Should have (differentiators):**
|
||||
- **Weight distribution donut chart** -- LighterPack's pie chart is cited as its best feature; GearBox can uniquely combine category and classification breakdown
|
||||
- **Candidate status tracking (researching/ordered/arrived)** -- entirely unique to GearBox's planning thread concept; no competitor has purchase lifecycle tracking
|
||||
- **Per-setup classification** -- architecturally superior to competitors; the same item can be classified differently across setups
|
||||
- Drag-to-rank ordering — makes priority explicit without numeric input; no competitor has this in the gear domain; requires `sort_order` schema migration
|
||||
- Per-candidate pros/cons fields — structured decision rationale; stored as newline-delimited text (renders as bullets in comparison view); requires `pros`/`cons` schema migration
|
||||
|
||||
**Defer (v2+):**
|
||||
- Per-item weight input in multiple units (parsing complexity)
|
||||
- Interactive chart drill-down (click to zoom into categories)
|
||||
- Weight goals/targets (opinionated norms conflict with hobby-agnostic design)
|
||||
- Custom weight classification labels beyond base/worn/consumable
|
||||
- Server-side full-text search (premature for single-user scale)
|
||||
- Status change timestamps on candidates (useful but not essential now)
|
||||
- Classification-aware impact breakdown (base/worn/consumable) — data available but UI complexity high; flat delta covers 90% of use case
|
||||
- Rank badge on card grid — useful but low urgency; add when users express confusion
|
||||
- Mobile-optimized comparison view (swipe between candidates) — horizontal scroll works for now
|
||||
- Comparison permalink — requires auth/multi-user work not in scope for v1
|
||||
|
||||
**Anti-features (explicitly rejected):**
|
||||
- Custom comparison attributes — complexity trap, rejected in PROJECT.md
|
||||
- Score/rating calculation — opaque algorithms distrust; manual ranking expresses user preference better
|
||||
- Cross-thread comparison — candidates are decision-scoped; different categories are not apples-to-apples
|
||||
|
||||
### Architecture Approach
|
||||
|
||||
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.
|
||||
All three features integrate on the `/threads/$threadId` route with no impact on other routes. The comparison view and impact preview are pure client-side derived views using data already in the React Query cache — no new API endpoints on read paths. The only new server-side endpoint is `PATCH /:id/candidates/reorder` which accepts `{ orderedIds: number[] }` and applies a transactional bulk-update in `thread.service.ts`. The `uiStore` (Zustand) gains two new fields: `compareMode: boolean` and `impactSetupId: number | null`, consistent with existing UI-state-only patterns.
|
||||
|
||||
**Major components:**
|
||||
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. **`WeightChart` component** -- reusable donut chart wrapper; used in collection page (weight by category) and setup detail page (weight by classification)
|
||||
3. **`SearchBar` component** -- reusable search input with clear button; collection page filters via `useMemo` over the cached `useItems()` data
|
||||
4. **Updated `syncSetupItems`** -- breaking API change from `{ itemIds: number[] }` to `{ items: Array<{ itemId, weightClass }> }`; single call site (ItemPicker.tsx) makes this safe
|
||||
5. **`PATCH /api/setups/:id/items/:itemId`** -- new endpoint for updating weight classification without triggering full sync (which would destroy classification data)
|
||||
1. `CandidateCompare.tsx` (new) — side-by-side table; columns = candidates, rows = attributes; pure presentational, derives deltas from `thread.candidates[]`; `overflow-x-auto` for narrow viewports; sticky label column
|
||||
2. `SetupImpactRow.tsx` (new) — delta display (`+Xg / +$Y`); reads from `useSetup(impactSetupId)` data passed as props; handles null weight case explicitly
|
||||
3. `Reorder.Group` / `Reorder.Item` (framer-motion, no new file) — wraps `CandidateCard` list in `$threadId.tsx`; `onReorder` updates local `orderedCandidates` state; `onDragEnd` fires `useReorderCandidates` mutation
|
||||
4. `CandidateCard.tsx` (modified) — gains `rank` prop (gold/silver/bronze badge for top 3), pros/cons indicator icons; `isActive={false}` when rendered inside comparison view
|
||||
5. `CandidateForm.tsx` (modified) — gains `pros`/`cons` textarea fields below existing Notes field
|
||||
|
||||
**Key patterns to follow:**
|
||||
- `tempItems` local state alongside React Query for drag reorder — prevents the documented flicker bug; do not use `setQueryData` alone
|
||||
- Client-computed derived data from cached queries — no new read endpoints (anti-pattern: building `GET /api/threads/:id/compare` or `GET /api/threads/:id/impact`)
|
||||
- `uiStore` for cross-panel persistent UI flags only — no server data in Zustand
|
||||
- Resolved-thread guard — `thread.status === "resolved"` must disable drag handles and block the reorder endpoint (data integrity requirement, not just UX)
|
||||
|
||||
### Critical Pitfalls
|
||||
|
||||
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.
|
||||
1. **Drag flicker from `setQueryData`-only optimistic update** — use `tempItems` local state (`useState<Candidate[] | null>(null)`); render from `tempItems ?? queryData.candidates`; clear on mutation `onSettled`. Must be designed before building the drag UI, not retrofitted. (PITFALLS.md Pitfall 1)
|
||||
|
||||
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.
|
||||
2. **Integer `sortOrder` causes bulk writes** — use `REAL` (float) type for `sort_order` column with fractional indexing so only the moved item requires a single UPDATE. With 8+ candidates and rapid dragging, integer bulk updates produce visible latency and hold a SQLite write lock. Start values at 1000 with 1000-unit gaps. (PITFALLS.md Pitfall 2)
|
||||
|
||||
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.
|
||||
3. **Impact preview shows wrong delta (add vs replace)** — default to "replace" mode when a setup item exists in the same category as the thread; default to "add" mode when no category match. Pure-addition delta misleads users: a 500g candidate replacing an 800g item shows "+500g" instead of "-300g". The distinction must be designed into the service layer, not retrofitted. (PITFALLS.md Pitfall 6)
|
||||
|
||||
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.
|
||||
4. **Comparison/rank on resolved threads** — `thread.status === "resolved"` must hide drag handles, disable rank mutation, and show a read-only summary. The reorder API route must return 400 for resolved threads. This is a data integrity issue, not just UX. (PITFALLS.md Pitfall 8)
|
||||
|
||||
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.
|
||||
5. **Test helper schema drift** — every schema change must update `tests/helpers/db.ts` in the same commit. Run `bun test` immediately after schema + helper update. Missing this produces `SqliteError: no such column` failures. (PITFALLS.md Pitfall 7)
|
||||
|
||||
## Implications for Roadmap
|
||||
|
||||
Based on combined research, a 5-phase structure is recommended:
|
||||
Based on research, a 4-phase structure is recommended with a clear dependency order: schema foundation first, ranking second (consumes new columns), then comparison view and impact preview as sequential client-only phases.
|
||||
|
||||
### Phase 1: Weight Unit Selection
|
||||
### Phase 1: Schema Foundation + Pros/Cons Fields
|
||||
|
||||
**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.
|
||||
**Rationale:** All ranking and pros/cons work shares a schema migration. Batching `sort_order`, `pros`, and `cons` into a single migration avoids multiple ALTER TABLE runs and ensures the test helper is updated once. Pros/cons field UI is low-complexity (two textareas in `CandidateForm`) and can be delivered immediately after the migration, making candidates richer before ranking is built.
|
||||
**Delivers:** `sort_order REAL NOT NULL DEFAULT 0`, `pros TEXT`, `cons TEXT` on `thread_candidates`; pros/cons visible in candidate edit panel; `CandidateCard` shows pros/cons indicator icons; `tests/helpers/db.ts` updated; Zod schemas extended with 500-char length caps
|
||||
**Addresses:** Side-by-side comparison row data (pros/cons), drag-to-rank prerequisite (sort_order)
|
||||
**Avoids:** Test helper schema drift (Pitfall 7), pros/cons as unstructured blobs (Pitfall 5 — newline-delimited format chosen at schema time)
|
||||
|
||||
**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.
|
||||
### Phase 2: Drag-to-Reorder Candidate Ranking
|
||||
|
||||
**Addresses:** Weight unit selection (table stakes from FEATURES.md)
|
||||
**Rationale:** Depends on Phase 1 (`sort_order` column must exist). Schema work is done; this phase is pure service + client. The `tempItems` pattern must be implemented correctly from the start to prevent the React Query flicker bug.
|
||||
**Delivers:** `reorderCandidates` service function (transactional loop); `PATCH /api/threads/:id/candidates/reorder` endpoint with thread ownership validation; `useReorderCandidates` mutation hook; `Reorder.Group` / `Reorder.Item` in thread detail route; rank badge (gold/silver/bronze) on `CandidateCard`; resolved-thread guard (no drag handles, API returns 400 for resolved)
|
||||
**Uses:** `framer-motion@12.37.0` Reorder API (already installed), Drizzle ORM transaction, fractional `sort_order REAL` arithmetic (single UPDATE per drag)
|
||||
**Avoids:** dnd-kit flicker (Pitfall 1 — `tempItems` pattern), bulk integer writes (Pitfall 2 — REAL type), resolved-thread corruption (Pitfall 8)
|
||||
|
||||
**Avoids:** Rounding drift (Pitfall 1), inconsistent unit application (Pitfall 7), flash of unconverted weights on load
|
||||
### Phase 3: Side-by-Side Comparison View
|
||||
|
||||
**Schema changes:** None (uses existing settings table key-value store)
|
||||
**Rationale:** No schema dependency — can technically be built before Phase 2, but is most useful when rank, pros, and cons are already in the data model so the comparison table shows the full picture from day one. Pure client-side presentational component; no API changes.
|
||||
**Delivers:** `CandidateCompare.tsx` component; "Compare" toggle button in thread header; `compareMode` in `uiStore`; comparison table with sticky label column, horizontal scroll, weight/price relative deltas (lightest/cheapest candidate highlighted); responsive at 768px viewport; read-only summary for resolved threads
|
||||
**Implements:** Client-computed derived data pattern — data from `useThread()` cache; `Math.min` across candidates for relative delta; `formatWeight`/`formatPrice` for display
|
||||
**Avoids:** Comparison breaking at narrow widths (Pitfall 4 — `overflow-x-auto` + `min-w-[200px]`), comparison visible on resolved threads (Pitfall 8), server endpoint for comparison deltas (architecture anti-pattern)
|
||||
|
||||
### Phase 2: Search, Filter, and Planning Category Filter
|
||||
### Phase 4: Setup Impact Preview
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
**Addresses:** Search items by name (table stakes), filter by category (table stakes), planning category filter upgrade (differentiator)
|
||||
|
||||
**Avoids:** Server-side search anti-pattern (Pitfall 3), search state lost on tab switch (UX pitfall), category groups disappearing incorrectly during filtering
|
||||
|
||||
**Schema changes:** None
|
||||
|
||||
### 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.
|
||||
|
||||
**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).
|
||||
|
||||
**Addresses:** Candidate status tracking (differentiator -- unique to GearBox)
|
||||
|
||||
**Avoids:** Status without transition validation (Pitfall 4), test helper desync (Pitfall 6), not handling candidate status during thread resolution
|
||||
|
||||
**Schema changes:** Add `status TEXT NOT NULL DEFAULT 'researching'` to `thread_candidates`
|
||||
|
||||
### Phase 4: Weight Classification
|
||||
|
||||
**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.
|
||||
|
||||
**Addresses:** Weight classification base/worn/consumable (table stakes), per-setup classification (differentiator)
|
||||
|
||||
**Avoids:** Classification on items table (Pitfall 2), test helper desync (Pitfall 6), losing classification data on sync
|
||||
|
||||
**Schema changes:** Add `weight_class TEXT NOT NULL DEFAULT 'base'` to `setup_items`
|
||||
|
||||
### Phase 5: Weight Distribution Charts
|
||||
|
||||
**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.
|
||||
|
||||
**Addresses:** Weight distribution visualization (differentiator)
|
||||
|
||||
**Avoids:** Chart/totals divergence (Pitfall 5), chart crashing on null-weight items, unnecessary chart re-renders on unrelated state changes
|
||||
|
||||
**Schema changes:** None (npm dependency: `bun add react-minimal-pie-chart`)
|
||||
**Rationale:** No schema dependency. Easiest to build last because the comparison view UI (Phase 3) already establishes the thread header area where the setup selector lives. Both add-mode and replace-mode deltas must be designed here to avoid the misleading pure-addition delta.
|
||||
**Delivers:** Setup selector dropdown in thread header (`useSetups()` data); `SetupImpactRow.tsx` component; `impactSetupId` in `uiStore`; add-mode delta and replace-mode delta (auto-defaults to replace when same-category item exists in setup); null weight guard ("-- (no weight data)" not "+0g"); unit-aware display via `useWeightUnit()` / `useCurrency()`
|
||||
**Uses:** Existing `useSetup(id)` hook (no new API), existing `formatWeight` / `formatPrice` formatters, `categoryId` on thread for replacement item detection
|
||||
**Avoids:** Stale data in impact preview (Pitfall 3 — reactive `useQuery` for setup data), wrong delta from add-vs-replace confusion (Pitfall 6), null weight treated as 0 (integration gotcha), server endpoint for delta calculation (architecture anti-pattern)
|
||||
|
||||
### Phase Ordering Rationale
|
||||
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **Phase 4 after Phase 1** because classification totals need the unit-aware formatter.
|
||||
- **Phase 5 last** because it is pure visualization depending on data from Phases 1 and 4, and introduces the only external dependency.
|
||||
- Phase 1 before all others: SQLite schema changes batched into a single migration; test helper updated once; pros/cons in edit panel adds value immediately without waiting for the comparison view
|
||||
- Phase 2 before Phase 3: rank data (sort order, rank badge) is more valuable displayed in the comparison table than in the card grid alone; building the comparison view after ranking ensures the table is complete on first delivery
|
||||
- Phase 3 before Phase 4: comparison view establishes the thread header chrome (toggle button area) where the setup selector in Phase 4 will live; building header UI in Phase 3 reduces Phase 4 scope
|
||||
- Phases 3 and 4 are technically independent and could parallelize, but sequencing them keeps the thread detail header changes contained to one phase at a time
|
||||
|
||||
### Research Flags
|
||||
|
||||
Phases likely needing deeper research during planning:
|
||||
- **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 (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.
|
||||
Phases that need careful plan review before execution (not full research-phase, but plan must address specific design decisions):
|
||||
- **Phase 2:** The `tempItems` local state pattern and fractional `sort_order` arithmetic are non-obvious. The PLAN.md must spell these out explicitly before coding. PITFALLS.md Pitfall 1 and Pitfall 2 must be addressed in the plan, not discovered during implementation.
|
||||
- **Phase 4:** The add-vs-replace distinction requires deliberate design (which mode is default, how replacement item is detected by category, how null weight is surfaced). PITFALLS.md Pitfall 6 must be resolved in the plan before the component is built.
|
||||
|
||||
Phases with standard patterns (skip research-phase):
|
||||
- **Phase 1 (Weight Unit Selection):** Well-documented pattern. Extend `formatWeight`, add a `useSetting` wrapper, propagate through components. No unknowns.
|
||||
- **Phase 2 (Search/Filter):** Textbook client-side filtering with `useMemo`. No API changes. Standard React pattern.
|
||||
- **Phase 3 (Candidate Status):** Simple column addition with Zod enum validation. Existing `useUpdateCandidate` mutation already handles partial updates.
|
||||
Phases with standard patterns (can skip `/gsd:research-phase`):
|
||||
- **Phase 1:** Standard Drizzle migration + Zod schema extension; established patterns in the codebase; ARCHITECTURE.md provides exact column definitions
|
||||
- **Phase 3:** Pure presentational component; Tailwind comparison table is well-documented; ARCHITECTURE.md provides complete component structure, props interface, and delta calculation code
|
||||
|
||||
## Confidence Assessment
|
||||
|
||||
| Area | Confidence | Notes |
|
||||
|------|------------|-------|
|
||||
| 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 | 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 | 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 | Derived from codebase-specific patterns (test helper duplication, dual computation paths) combined with domain risks (unit conversion rounding, classification scope). Not generic warnings. |
|
||||
| Stack | HIGH | Verified from `bun.lock` (framer-motion React 19 peerDeps confirmed); dnd-kit abandonment verified via npm + GitHub; Motion Reorder API verified via motion.dev docs |
|
||||
| Features | HIGH | Codebase analysis confirmed no rank/pros/cons columns in existing schema; NNGroup + Smashing Magazine for comparison UX patterns; competitor analysis (LighterPack, GearGrams, OutPack) confirmed feature gap |
|
||||
| Architecture | HIGH | Full integration map derived from direct codebase analysis; build order confirmed by column dependency graph; all changed files enumerated (3 new, 10 modified); complete code patterns provided |
|
||||
| Pitfalls | HIGH | dnd-kit flicker: verified in GitHub Discussion #1522 and Issue #921; fractional indexing: verified via steveruiz.me and fractional-indexing library; comparison UX: Baymard Institute and NNGroup |
|
||||
|
||||
**Overall confidence:** HIGH
|
||||
|
||||
### Gaps to Address
|
||||
|
||||
- **`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.
|
||||
- **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.
|
||||
- **Impact preview add-vs-replace UX:** Research establishes that both modes are needed and when to default to each (same-category item in setup = replace mode). The exact affordance — dropdown to select which item is replaced vs. automatic category matching — is not fully specified. Recommendation: auto-match by category with a "change" link to override. Decide during Phase 4 planning.
|
||||
- **Comparison view maximum candidate count:** Research recommends 3-4 max for usability. GearBox has no current limit on candidates per thread. Whether to enforce a hard display limit (hide additional candidates behind "show more") or allow unrestricted horizontal scroll should be decided during Phase 3 planning.
|
||||
- **Sort order initialization for existing candidates:** When the migration runs, existing `thread_candidates` rows get `sort_order = 0` (default). Phase 1 plan must specify whether to initialize existing candidates with spaced values (e.g., 1000, 2000, 3000) at migration time or accept that all existing rows start at 0 and rely on first drag to establish order.
|
||||
|
||||
## Sources
|
||||
|
||||
### Primary (HIGH confidence)
|
||||
- [Drizzle ORM Filter Operators](https://orm.drizzle.team/docs/operators) -- like, eq, and operators for search/filter
|
||||
- [Drizzle ORM Conditional Filters Guide](https://orm.drizzle.team/docs/guides/conditional-filters-in-query) -- dynamic filter composition
|
||||
- [react-minimal-pie-chart GitHub](https://github.com/toomuchdesign/react-minimal-pie-chart) -- v9.1.2, React 19 peerDeps verified in package.json
|
||||
- [LighterPack](https://lighterpack.com/) -- base/worn/consumable classification standard, pie chart visualization pattern
|
||||
- [99Boulders LighterPack Tutorial](https://www.99boulders.com/lighterpack-tutorial) -- classification definitions and feature walkthrough
|
||||
- [BackpackPeek Pack Weight Calculator Guide](https://backpackpeek.com/blog/pack-weight-calculator-base-weight-guide) -- weight classification methodology
|
||||
- Direct codebase analysis of GearBox v1.1 -- schema.ts, services, hooks, routes, test helpers
|
||||
- `bun.lock` (project lockfile) — framer-motion v12.37.0 peerDeps `"react: ^18.0.0 || ^19.0.0"` confirmed
|
||||
- [Motion Reorder docs](https://motion.dev/docs/react-reorder) — `Reorder.Group`, `Reorder.Item`, `onDragEnd` API
|
||||
- [dnd-kit Discussion #1522](https://github.com/clauderic/dnd-kit/discussions/1522) — `tempItems` solution for React Query cache flicker
|
||||
- [dnd-kit Issue #921](https://github.com/clauderic/dnd-kit/issues/921) — root cause of state lifecycle mismatch
|
||||
- [Fractional Indexing — steveruiz.me](https://www.steveruiz.me/posts/reordering-fractional-indices) — why float sort keys beat integer reorder for databases
|
||||
- [Baymard Institute: Comparison Tool Design](https://baymard.com/blog/user-friendly-comparison-tools) — sticky headers, horizontal scroll, minimum column width
|
||||
- [NNGroup: Comparison Tables](https://www.nngroup.com/articles/comparison-tables/) — information architecture, anti-patterns
|
||||
- [Smashing Magazine: Feature Comparison Table](https://www.smashingmagazine.com/2017/08/designing-perfect-feature-comparison-table/) — table layout patterns
|
||||
- GearBox codebase direct analysis (`src/db/schema.ts`, `src/server/services/`, `src/client/hooks/`, `tests/helpers/db.ts`) — confirmed existing patterns, missing columns, integration points
|
||||
|
||||
### Secondary (MEDIUM confidence)
|
||||
- [Hikt](https://hikt.app/) -- searchable gear closet, base vs worn weight display
|
||||
- [PackLight (iOS)](https://apps.apple.com/us/app/packlight-for-backpacking/id1054845207) -- search, categories, bar graph visualization
|
||||
- [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
|
||||
- [@dnd-kit/core npm](https://www.npmjs.com/package/@dnd-kit/core) — v6.3.1 last published ~1 year ago, no React 19
|
||||
- [dnd-kit React 19 issue #1511](https://github.com/clauderic/dnd-kit/issues/1511) — CLOSED but React 19 TypeScript issues confirmed
|
||||
- [@dnd-kit/react roadmap discussion #1842](https://github.com/clauderic/dnd-kit/discussions/1842) — 0 maintainer replies; pre-1.0 risk signal
|
||||
- [hello-pangea/dnd React 19 issue #864](https://github.com/hello-pangea/dnd/issues/864) — still open as of Jan 2026
|
||||
- [BrightCoding dnd-kit deep dive (2025)](https://www.blog.brightcoding.dev/2025/08/21/the-ultimate-drag-and-drop-toolkit-for-react-a-deep-dive-into-dnd-kit/) — react-beautiful-dnd abandoned; dnd-kit current standard but React 19 gap confirmed
|
||||
- [TrailsMag: Leaving LighterPack](https://trailsmag.net/blogs/hiker-box/ultralight-the-gear-tracking-app-i-m-leaving-lighterpack-for) — LighterPack feature gap analysis
|
||||
- [Contentsquare: Comparing products UX](https://contentsquare.com/blog/comparing-products-design-practices-to-help-your-users-avoid-fragmented-comparison-7/) — fragmented comparison pitfalls
|
||||
|
||||
### Tertiary (LOW confidence)
|
||||
- [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)
|
||||
- [Fractional Indexing SQLite library](https://github.com/sqliteai/fractional-indexing) — implementation reference for lexicographic sort keys (pattern reference only; direct float arithmetic sufficient for this use case)
|
||||
- [Top 5 Drag-and-Drop Libraries for React 2026](https://puckeditor.com/blog/top-5-drag-and-drop-libraries-for-react) — ecosystem overview confirming dnd-kit and hello-pangea/dnd limitations
|
||||
|
||||
---
|
||||
*Research completed: 2026-03-16*
|
||||
|
||||
Reference in New Issue
Block a user