# Browse / results page — design

Discovery experience for the in-stock parts grid: **filtering** (type,
company, price range), **text search** (wildcard, optional fuzzy),
**sorting**, **pagination**, and a **card ↔ table view** toggle. Applies
to the existing `/browse` route and feeds the build feature (the "+ Add"
button lives in both views — see `build-feature-design.md`).

Companion to `build-feature-design.md`; see also memory
`site-ng-decisions`, `frontend-data-usage`.

## Grounding facts (measured 2026-05-22)

- `parts` is **InnoDB** (converted from MyISAM 2026-06, see memory
  `myisam-to-innodb-conversion-future`), ~28,291 rows, MySQL **8.0.26**.
- Indexes: `PRIMARY(id)`, `url_idx(url)`, `typeindex(type)` — **no index on
  `price` or `company`**, no FULLTEXT index.
- **`ft_min_word_len = 4`** — NOTE: that's the *MyISAM* FULLTEXT min token; now
  that `parts` is InnoDB the relevant knob is **`innodb_ft_min_token_size`** (also
  defaults to 3, but verify on pair) and a FULLTEXT index would be an InnoDB
  FULLTEXT index. Re-confirm before relying on it.
- DB is **local to the app** in both environments (dev = `arpartsfinder_dev`
  mirror on the Pi; prod = mod_passenger on pair.com next to vdb1b). So
  query latency is *not* a constraint here — at 28K rows even a full scan
  is sub-100ms. This frees the design from premature index work.

## URL / state model

Every control is a **query param on `/browse`** → bookmarkable, shareable,
crawlable (SEO is the commission channel). htmx issues `hx-get` to
`/browse/parts` with `hx-push-url` so the address bar tracks state and
filtered views are linkable.

| Param | Meaning | Default |
|---|---|---|
| `type` | part-type code (allowlist) | all |
| `company` | retailer (allowlist from `companies()`) | all |
| `pmin` / `pmax` | price range (numeric) | none |
| `q` | search text | none |
| `sort` | sort key (allowlist, below) | `new` |
| `page` | 1-based page number | 1 |
| `per` | page size: 24 / 48 / 96 | 48 |
| `view` | `card` \| `table` | `card` (cookie-persisted) |

## Filtering

- **Type / company** — already present; keep as validated `=` predicates.
- **Price range** — two numeric inputs → `price BETWEEN %s AND %s` (each
  side optional: `price >= pmin`, `price <= pmax`). Guard against
  inverted/negative input server-side. The base `price > 0` predicate
  stays (legacy filters out $0 placeholder rows).
- All filters compose with AND, built from a validated params object —
  never string-interpolate user input into SQL.

## Text search — recommendation: multi-term `LIKE`, not FULLTEXT

The instinct is a MySQL FULLTEXT index, but it's the **wrong fit here**:

1. **`ft_min_word_len = 4` silently drops the exact short tokens AR
   shoppers type** — `bcg` (3), `300`, `556` (3), `ar` (2) would never
   match. Fixing it means changing a server global + a full reindex, which
   pair.com shared hosting won't let us do.
2. Adding the FULLTEXT index is an **`ALTER` on the live `parts` table** during
   the rebuild. (Historically this was a MyISAM table-lock-cascade risk; `parts`
   is **InnoDB** now (2026-06), so online DDL makes the rebuild far less
   disruptive — but it's still a live-table ALTER to do off-peak.)
3. At **28K rows the performance argument for FULLTEXT evaporates** — a
   `LIKE` scan is trivially fast.

**v1 design:** split `q` on whitespace; each term becomes
`(description LIKE %term% OR company LIKE %term%)`, all terms AND-ed
(so "magpul grip" narrows correctly). Substring match gives wildcard
behavior for free, short tokens included. Optional explicit wildcard:
let `*` map to `%`. No DDL, no lock, no short-token blind spot.

**Fuzzy (typo tolerance) — defer to v2, app-side:** MySQL 8 has no native
trigram/fuzzy. Rather than a search engine (overkill on a Pi), the cheap
path given 28K rows is to fetch the filtered candidate set and rank with
`rapidfuzz` in Python when `q` yields few/no `LIKE` hits — a "did you
mean" fallback, not the primary path. Flagged, not built in v1.

## Sorting

`sort` maps through a **server-side allowlist** to a fixed `ORDER BY`
fragment (user input never reaches the clause):

| `sort` | ORDER BY |
|---|---|
| `new` (default) | `added DESC` (also surfaces restocks — `added` resets on restock) |
| `price_asc` | `price ASC` |
| `price_desc` | `price DESC` |
| `name` | `description ASC` |

(`price`/`description` sorts do a filesort over the filtered set — fine at
this size; revisit an index only if a result set ever gets large.)

## Pagination

- **Offset pagination** (`LIMIT per OFFSET (page-1)*per`) — adequate at
  28K rows; keyset/seek is unnecessary complexity here.
- One extra `SELECT COUNT(*)` with the same WHERE → total, for page
  numbers + "showing X–Y of N."
- Page sizes **24 / 48 / 96** (echoes legacy/PSA conventions).
- htmx: a pager fragment plus the grid; real `?page=N` URLs via
  `hx-push-url` keep deep pages crawlable/bookmarkable. A "Load more"
  affordance can append instead of replace for casual scrolling, but the
  numbered URLs remain the canonical, indexable form.

## Card ↔ table view

- `view=card` (current grid) or `view=table` (dense rows: thumb,
  description, company, type label, price, in-stock, "+ Add", "view →").
- Two partials sharing one query result: `partials/parts_grid.html`
  (exists) + `partials/parts_table.html` (new). The view toggle is an
  htmx swap; the choice is persisted in a cookie and reflected in `view`.
- Table view pairs naturally with **clickable column headers** that set
  `sort` — the discoverable way to sort by price/name.
- Both views render the human type label (`type_label` filter) and route
  buy links through `jump.cgi?site=<id>` (per `site-ng-decisions`).

## Query-layer refactor

Replace the single-purpose `in_stock(type, company)` with one flexible
reader that takes a validated params object and returns `(rows, total)`:

```python
def search_parts(*, type=None, company=None, pmin=None, pmax=None,
                 q=None, sort="new", page=1, per=48):
    # build WHERE from non-None filters (parameterized),
    # ORDER BY from the sort allowlist, LIMIT/OFFSET from page/per;
    # run COUNT(*) with the same WHERE for the pager.
    ...
    return rows, total
```

Sort keys, `view`, and `per` are validated against allowlists in the view
before reaching SQL. `companies()` / `list_types()` stay as the dropdown
sources.

## Phasing

1. **B1 — filters + sort + pagination:** price range, `sort` allowlist,
   offset paging + count, the `search_parts()` refactor. (No schema
   changes.)
2. **B2 — text search:** multi-term `LIKE` over description+company, `*`
   wildcard, search box wired to the htmx flow.
3. **B3 — table view:** `parts_table.html`, cookie-persisted toggle,
   column-header sorting.
4. **B4 — fuzzy fallback (optional):** `rapidfuzz` "did you mean" when
   `LIKE` returns little.

These are independent of the build feature and can ship alongside or
ahead of it; B1–B3 also make the plain browse page materially better on
their own.

## Open questions for Mike

1. **"Load more" vs numbered pages** as the primary UX (we keep numbered
   URLs underneath either way for SEO). *Recommendation: numbered pager
   primary — matches the legacy mental model and is obviously crawlable.*
2. **Default page size** — 24 / 48 / 96. *Recommendation: 48.*
3. **Is fuzzy search actually wanted**, or is wildcard `LIKE` enough?
   *Recommendation: ship B2 wildcard first; add B4 only if real searches
   miss on typos.*
4. **Default view** — card or table? *Recommendation: card default
   (visual, mobile-friendly), table opt-in for power browsing.*
```
