From fa0ed9e2b6c2bb7c6722c36b6cf230b5a2accd1c Mon Sep 17 00:00:00 2001 From: Clarence Date: Tue, 1 Dec 2026 23:44:33 +0800 Subject: [PATCH] refactor: adopt shared useMediaQuery and stored-value helpers from @merqo/ui Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 6 ++++++ package.json | 2 +- src/app/dashboard/README.md | 4 ++-- src/app/dashboard/counter/README.md | 2 +- .../counter/remember-program.dom.test.tsx | 6 +++--- src/app/dashboard/counter/remember-program.tsx | 7 ++----- src/app/dashboard/overview/README.md | 2 +- src/app/dashboard/overview/visits-trend.tsx | 12 ++---------- src/app/dashboard/serve-cta.dom.test.tsx | 12 ++++++++++-- src/app/dashboard/serve-cta.tsx | 7 ++----- .../card-check/components/program-card-status.tsx | 15 +++------------ 11 files changed, 33 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ea284b3..6b37d633 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to loopkit are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). +## [0.6.4] - 2026-12-01 + +### Changed + +- The visits trend, the Counter's last-program memory, the "Serve a customer" button and the retired-card notice now use the shared `useMediaQuery` and `readStored`/`writeStored` helpers from `@merqo/ui`. The last-program value is now stored as JSON, so a device with the old raw value uses the default program until the vendor next opens the Counter. + ## [0.6.3] - 2026-12-01 ### Changed diff --git a/package.json b/package.json index c0085f4b..0ab39737 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "loopkit", - "version": "0.6.3", + "version": "0.6.4", "private": true, "packageManager": "pnpm@11.10.0", "engines": { diff --git a/src/app/dashboard/README.md b/src/app/dashboard/README.md index 13da88f1..53f52443 100644 --- a/src/app/dashboard/README.md +++ b/src/app/dashboard/README.md @@ -32,8 +32,8 @@ Shared controls and `cn` used by this folder's modules are imported from `@merqo - `loading.tsx` — `DashboardLoading` skeleton fallback (pulse placeholders for header and cards) shown while the dashboard route segment streams - `page.tsx` — `DashboardPage` server component: `requireVendor` + `applyDueCutovers`, loads programs (redirects to `/setup` on zero), fetches `getVendorStats` / `countExpiredVouchers` / `listActivity(limit 6)` / `getVendorOverviewInputs` / `getVendorProfile` in parallel, wires them through `buildOverviewModel`, and renders the Overview: a head row (greeting + stall name + date + ``) carrying `data-tour="shop-qr"` (the onboarding tour's step-1 anchor), then `` / `` / `` / `` / `` in the main column and `` / `` in a right rail (a `lg:` two-zone grid when the vendor has 2+ programs, one centred `max-w-[46rem]` column otherwise). A zero-enrolled vendor sees just the head row and a "no customers yet" card (`@merqo/ui`'s `ElevatedCard`). No `isPro()` gating (Phase 1 ships ungated) - `overview/` — the Overview's presentational components (`briefing`, `base-strip`, `visits-trend`, `worth-a-look`, `recent-activity`, `reward-cost-panel`, `your-programs`), each with a `*.dom.test.tsx` -- `serve-cta.tsx` — client `ServeCta`: the "Serve a customer" button, links to `/dashboard/counter?p=` for the last program served on this device (reads `localStorage` key `loopkit:last-counter-program` via `useSyncExternalStore`, the Counter writes it), falling back to the server-provided default -- `serve-cta.dom.test.tsx` — jsdom tests: stored program wins when owned, falls back to the default when the stored id is not owned or `localStorage` throws +- `serve-cta.tsx` — client `ServeCta`: the "Serve a customer" button, links to `/dashboard/counter?p=` for the last program served on this device (reads `localStorage` key `loopkit:last-counter-program` via `readStored` inside `useSyncExternalStore`, the Counter writes it as JSON; a legacy raw-string value reads as null and falls back until the Counter rewrites it), falling back to the server-provided default +- `serve-cta.dom.test.tsx` — jsdom tests: stored program wins when owned, falls back to the default when the stored id is not owned, is a legacy raw string, or `localStorage` throws - `plan/` - `profile/` - `program-display.test.ts` — unit tests for `PROGRAM_TYPE_BADGE` and `describeProgram` across every program type diff --git a/src/app/dashboard/counter/README.md b/src/app/dashboard/counter/README.md index ba26c043..75a3b624 100644 --- a/src/app/dashboard/counter/README.md +++ b/src/app/dashboard/counter/README.md @@ -12,7 +12,7 @@ Shared controls and `cn` used by this folder's modules are imported from `@merqo - `page.tsx` — `CounterPage` server component. Requires a vendor; loads programs and redirects to `/dashboard` when there are none. With no `?p=`, it fetches `activeCardCountsByProgram` and redirects to `pickDefaultCounterProgram`'s pick (the busiest active program), or `/dashboard` when nothing is active. Otherwise it resolves the program from `?p=` (redirect to `/dashboard` if it is not one of the vendor's), builds the vendor-wide shop-join link (`/c?v=`) plus its QR, reads the stall name, computes `getEntitlement(await isPro())` and passes its `showBranding` down as `ServeCustomer`'s `showBranding` prop, mounts `RememberProgram`, renders the head row (program name + badge + `describeProgram` + a `ProgramSwitcher` chip when the vendor runs more than one program), and renders `ServeCustomer` keyed on the program id. Wrapper is `mx-auto max-w-4xl` (wider than the old `max-w-2xl` to fit the two-column serve layout), nested inside `../layout.tsx`'s shared `
`. Derives `redemption_mode` off the program's own `config` and passes it as `ServeCustomer`'s `pointsRedemptionMode`. - `counter-view.ts` — `pickDefaultCounterProgram(programs, activeCountById)`: pure helper picking the program id with the most active cards (ties to the earlier entry, first program when all counts are zero or missing, `null` when empty). - `counter-view.test.ts` — unit tests for `pickDefaultCounterProgram`. -- `remember-program.tsx` — client `RememberProgram`: renders nothing; on mount and whenever `id` changes, writes `localStorage["loopkit:last-counter-program"]` (swallows a throwing `setItem`). Sub-plan 3's "Serve a customer" CTA reads this key. +- `remember-program.tsx` — client `RememberProgram`: renders nothing; on mount and whenever `id` changes, writes `localStorage["loopkit:last-counter-program"]` as JSON via `@merqo/ui`'s `writeStored` (swallows a throwing `setItem`). Sub-plan 3's "Serve a customer" CTA reads this key. - `remember-program.dom.test.tsx` — jsdom tests: writes on mount, updates on `id` change, does not crash when storage throws. - `scan-hero.tsx` — client `ScanHero`: the Counter's primary action, a thin wrapper around `ScanButton` `variant="hero"` with the label "Serve a customer" and the sub "Camera opens when you tap". All decode/token-resolve logic stays in `ScanButton`. - `scan-hero.dom.test.tsx` — jsdom tests: renders the label and sub copy as a button, carries the cornered dashed frame chrome. diff --git a/src/app/dashboard/counter/remember-program.dom.test.tsx b/src/app/dashboard/counter/remember-program.dom.test.tsx index 6f685b3d..68e6656d 100644 --- a/src/app/dashboard/counter/remember-program.dom.test.tsx +++ b/src/app/dashboard/counter/remember-program.dom.test.tsx @@ -14,14 +14,14 @@ describe("RememberProgram", () => { it("writes the program id on mount and renders nothing", () => { const { container } = render(); expect(container).toBeEmptyDOMElement(); - expect(localStorage.getItem(KEY)).toBe("p7"); + expect(localStorage.getItem(KEY)).toBe('"p7"'); }); it("updates the stored value when the id changes", () => { const { rerender } = render(); - expect(localStorage.getItem(KEY)).toBe("p7"); + expect(localStorage.getItem(KEY)).toBe('"p7"'); rerender(); - expect(localStorage.getItem(KEY)).toBe("p9"); + expect(localStorage.getItem(KEY)).toBe('"p9"'); }); it("does not crash when setItem throws", () => { diff --git a/src/app/dashboard/counter/remember-program.tsx b/src/app/dashboard/counter/remember-program.tsx index a4c3255b..eae53495 100644 --- a/src/app/dashboard/counter/remember-program.tsx +++ b/src/app/dashboard/counter/remember-program.tsx @@ -1,16 +1,13 @@ "use client"; import { useEffect } from "react"; +import { writeStored } from "@merqo/ui"; // Records the program the vendor last worked the Counter in, per device. // Sub-plan 3's "Serve a customer" CTA reads this key to route back here. export function RememberProgram({ id }: { id: string }) { useEffect(() => { - try { - localStorage.setItem("loopkit:last-counter-program", id); - } catch { - // Private mode or blocked storage: routing just falls back to the default. - } + writeStored("loopkit:last-counter-program", id); }, [id]); return null; } diff --git a/src/app/dashboard/overview/README.md b/src/app/dashboard/overview/README.md index 1772ad0b..0e946fbb 100644 --- a/src/app/dashboard/overview/README.md +++ b/src/app/dashboard/overview/README.md @@ -13,7 +13,7 @@ composes them. - `briefing.dom.test.tsx` — renders the full sentence, pulls out a numeric lead, treats a non-numeric lead as plain text, asserts no em dash - `base-strip.tsx` — `BaseStrip({ stats, redemptionRatePct, returnRatePct })`, client: the 4 base stats as `@merqo/ui` `StatTile`s wrapped in `@merqo/ui`'s `ElevatedCard`, each with an `InfoTooltip trigger="tap"` whose content is the stat's title/body/hint; below them the redemption-rate and return-rate figures, each with their own tap tooltip. `--` (two hyphens) for a null return rate - `base-strip.dom.test.tsx` — jsdom: the 4 displays/labels render, tapping a stat's info trigger reveals its body copy, the two rate figures render, `--%` for a null return rate and no em dash anywhere -- `visits-trend.tsx` — `VisitsTrend({ bars7, bars14, deltaVsLastWeek })`, client: a div-bar strip (the `stats/visits-chart.tsx` idiom) showing 7 bars by default and 14 on `matchMedia("(min-width: 56rem)")`, the prior week's 7 bars muted; a "Visits, last N days" caption and an "up/down N vs last week" delta (hidden at 0) +- `visits-trend.tsx` — `VisitsTrend({ bars7, bars14, deltaVsLastWeek })`, client: a div-bar strip (the `stats/visits-chart.tsx` idiom) showing 7 bars by default and 14 on `useMediaQuery("(min-width: 56rem)")` from `@merqo/ui`, the prior week's 7 bars muted; a "Visits, last N days" caption and an "up/down N vs last week" delta (hidden at 0) - `visits-trend.dom.test.tsx` — jsdom with a stubbed `matchMedia`: 7 bars + 7-day caption + a positive delta on a narrow screen, 14 bars + 14-day caption + a negative delta on a wide screen, the delta hidden at 0 - `worth-a-look.tsx` — `WorthALook({ items })`: one `next/link` per `WorthALookItem` to `/dashboard/customers?cohort=gone-quiet`, `?cohort=one-away` or `?cohort=two-away`, matching the exact overview cohort, with strong + sub copy; renders nothing when `items` is empty - `worth-a-look.dom.test.tsx` — jsdom: two items render two links with the right hrefs, empty renders nothing, singular wording for a count of one diff --git a/src/app/dashboard/overview/visits-trend.tsx b/src/app/dashboard/overview/visits-trend.tsx index 2d98f15f..75376fc9 100644 --- a/src/app/dashboard/overview/visits-trend.tsx +++ b/src/app/dashboard/overview/visits-trend.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useState } from "react"; +import { useMediaQuery } from "@merqo/ui"; import { VisitsBars } from "../visits-bars"; import type { TrendBar } from "@/app/dashboard/dashboard-view"; @@ -15,15 +15,7 @@ export function VisitsTrend({ bars14: TrendBar[]; deltaVsLastWeek: number; }) { - const [wide, setWide] = useState(false); - - useEffect(() => { - const mq = window.matchMedia(WIDE); - const sync = () => setWide(mq.matches); - sync(); - mq.addEventListener("change", sync); - return () => mq.removeEventListener("change", sync); - }, []); + const wide = useMediaQuery(WIDE); const bars = wide ? bars14 : bars7; const priorCount = wide ? bars14.length - 7 : 0; diff --git a/src/app/dashboard/serve-cta.dom.test.tsx b/src/app/dashboard/serve-cta.dom.test.tsx index b229d281..a83dce7b 100644 --- a/src/app/dashboard/serve-cta.dom.test.tsx +++ b/src/app/dashboard/serve-cta.dom.test.tsx @@ -12,7 +12,7 @@ afterEach(() => { describe("ServeCta", () => { it("targets the stored program when it is one the vendor owns", () => { - window.localStorage.setItem(KEY, "p2"); + window.localStorage.setItem(KEY, JSON.stringify("p2")); render(); expect( screen.getByRole("link", { name: /serve a customer/i }), @@ -20,7 +20,15 @@ describe("ServeCta", () => { }); it("falls back to the default when the stored id is not owned", () => { - window.localStorage.setItem(KEY, "gone"); + window.localStorage.setItem(KEY, JSON.stringify("gone")); + render(); + expect( + screen.getByRole("link", { name: /serve a customer/i }), + ).toHaveAttribute("href", "/dashboard/counter?p=p1"); + }); + + it("falls back to the default for a legacy raw-string value until the Counter rewrites it", () => { + window.localStorage.setItem(KEY, "p2"); render(); expect( screen.getByRole("link", { name: /serve a customer/i }), diff --git a/src/app/dashboard/serve-cta.tsx b/src/app/dashboard/serve-cta.tsx index ef9c417b..b20c1332 100644 --- a/src/app/dashboard/serve-cta.tsx +++ b/src/app/dashboard/serve-cta.tsx @@ -2,6 +2,7 @@ import { useSyncExternalStore } from "react"; import Link from "next/link"; +import { readStored } from "@merqo/ui"; import { PlusCircle } from "lucide-react"; const LAST_USED_KEY = "loopkit:last-counter-program"; @@ -12,11 +13,7 @@ const subscribe = (onChange: () => void) => { }; function readLastUsed(): string | null { - try { - return window.localStorage.getItem(LAST_USED_KEY); - } catch { - return null; - } + return readStored(LAST_USED_KEY, (v) => (typeof v === "string" ? v : null)); } // The "Serve a customer" button. Routes to the Counter for the last program diff --git a/src/features/card-check/components/program-card-status.tsx b/src/features/card-check/components/program-card-status.tsx index e745b534..22757422 100644 --- a/src/features/card-check/components/program-card-status.tsx +++ b/src/features/card-check/components/program-card-status.tsx @@ -19,7 +19,7 @@ import { AlertDialogTitle, Button, } from "@merqo/ui/primitives"; -import { ConfirmDialog } from "@merqo/ui"; +import { ConfirmDialog, readStored, writeStored } from "@merqo/ui"; // One customer's progress card for a single program, at the vendor-level // /c page. Each instance owns its own regenerate-dialog state — necessary @@ -47,12 +47,7 @@ export function ProgramCardStatus({ useEffect(() => { if (card.active || !card.replacedByName) return; const key = `loopkit:seen-replaced:${card.programId}`; - let dismissed = false; - try { - dismissed = localStorage.getItem(key) !== null; - } catch { - // Storage is optional for the notice. - } + const dismissed = readStored(key) !== null; if (!dismissed) { // eslint-disable-next-line react-hooks/set-state-in-effect -- localStorage is only readable on the client after mount setNoticeOpen(true); @@ -61,11 +56,7 @@ export function ProgramCardStatus({ }, [card.programId]); function dismissNotice() { - try { - localStorage.setItem(`loopkit:seen-replaced:${card.programId}`, "1"); - } catch { - // Dismissing the notice also works when storage is unavailable. - } + writeStored(`loopkit:seen-replaced:${card.programId}`, 1); setNoticeOpen(false); }