deckhearth/pages/scanner.js

216 lines
7.4 KiB
JavaScript
Raw Normal View History

import { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/router';
import Layout from '../components/Layout';
import ScannerCamera from '../components/scanner/ScannerCamera';
import ScannerReview from '../components/scanner/ScannerReview';
import ScannerCheckoutSheet from '../components/scanner/ScannerCheckoutSheet';
import { Modal, Button } from '../components/ui';
refactor(auth): collapse lib/auth-context.js + lib/admin-auth.js onto lib/use-auth.js (#31) `lib/use-auth.js` is now the sole client-side auth surface (P1 §9 of `.convoys/ship-readiness.md`). The legacy `lib/auth-context.js` (`AuthProvider` + `useAuth`) and `lib/admin-auth.js` (`AdminProvider` + `useAdmin` + `useIsAdmin`) are deleted; every importer is migrated to the canonical hook. Pre-convoy a worst-case page mount issued THREE identical `GET /api/auth/verify` requests (one per provider/hook); the post-convoy floor is one verify per page mount (3 → 1 on `pages/card/[id].js`, 2 → 1 elsewhere). Importer inventory swept (7 source files): - `pages/_app.js` — removed `<AuthProvider>` wrapper; `<ThemeProvider>` is now the only top-level provider. `lib/use-auth.js` is hook-only, no replacement provider needed. - `pages/index.js`, `pages/scanner.js`, `pages/decks.js`, `pages/deck/[id].js`, `pages/deck-builder.js` — `import { useAuth }` path swap from `../lib/auth-context` to `../lib/use-auth`. All five pages destructured only `{ user }` or `{ user, loading }`; verified no consumer reads `login` / `register` from useAuth (those flows are in `pages/login.js` / `pages/signup.js` which call the API directly), so no shape-parity gap on `lib/use-auth.js`. - `pages/card/[id].js` — replaced `useIsAdmin()` (the only consumer of `lib/admin-auth.js` anywhere in the tree) with synchronous `user?.role === 'admin'` derived from the existing `useAuth()` call. Render condition at line 524 stays byte-identical. Decisions documented in `.convoys/single-auth-provider.md`: - D1: no extension to `lib/use-auth.js` (zero call sites for `login` / `register` from useAuth — those flows are direct fetches in `login.js` / `signup.js`). - D2: `useIsAdmin()` collapses onto `useAuth()`; no separate hook. - D3: provider tree `<ThemeProvider><AuthProvider>{children}</AuthProvider></ThemeProvider>` → `<ThemeProvider>{children}</ThemeProvider>`. - D4: 3 → 1 verify roundtrip on `card/[id].js`; 2 → 1 on every other page-load. - D5: zero test files modified; the 21-test vitest suite is server- side or prop-driven (`Layout.test.js` passes `user` as a prop, never imports the legacy hooks). Doc / config updates so the deletion lands cleanly: - `.github/CODEOWNERS` — drop the two CODEOWNERS lines for the deleted files. - `AGENTS.md` § 2 architecture row + § 3 "Auth (client)" bullet — rewritten for the post-convoy single-surface state. - `.cursor/rules/auth-and-permissions.mdc` — § "Legacy" reframed to "deleted by this convoy"; § "Authentication state on the client" updated to the post-convoy `useAuth()` shape and the direct-fetch login flow used by `login.js` / `signup.js`. - `.cursor/rules/no-go-zones.mdc` — auth-refactors bullet drops the deleted files from the canonical list. - `.cursor/skills/add-page/SKILL.md` — checklist + anti-pattern row refer to the deletion. Verification: - `rg "lib/auth-context|lib/admin-auth" --type js` → 0 hits in source. - `npm run lint` → 128 → 125 problems (3 fewer errors from the deleted unused-import lines; no regression). - `npm run test:run` → 21/21 pass (including the 5 Layout regression locks from `fix-layout-default-user`, which are prop-driven and unaffected). - `npm run build` → all 26 pages compile end-to-end; no SSR / static- generation breakage that would have surfaced if a page tried to use the legacy context hook unwrapped. - Manual smoke deferred to operator post-merge per convoy doc. Risks (full discussion in convoy file): - R1 shape parity gap — verified zero consumers of legacy-only surface; mitigated. - R2 SSR mismatch from removing `<AuthProvider>` — `useEffect`- guarded `localStorage` read; identical SSR shape pre/post; build passes. - R3 missed importer — post-delete grep + build pass would surface any miss. - R5 stale `useAuth` cache across components — pre-existing pattern, called out as follow-up rather than addressed here. Out of scope: any change to `lib/permission-middleware.js` (server- side; resolved P0 #1), `lib/auth-secret.js` (resolved P0 #2), `pages/api/**` route handlers, login / register API contracts, or the seeded admin account flow. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-26 23:58:08 -04:00
import { useAuth } from '../lib/use-auth';
import { useScannerSession } from '../lib/use-scanner-session.js';
import { useScannerQueue } from '../lib/use-scanner-queue.js';
import { useCameraScanner } from '../lib/use-camera-scanner.js';
import { useScannerIdentification } from '../lib/use-scanner-identification.js';
import { clearScannerCartStorage } from '../lib/scanner-session.js';
import { collectionDisplayName } from '../lib/collection-vocabulary.js';
export default function Scanner() {
const { user, loading: authLoading } = useAuth();
const router = useRouter();
const [isCheckoutOpen, setIsCheckoutOpen] = useState(false);
const [isListPickerOpen, setIsListPickerOpen] = useState(false);
const [showLeaveModal, setShowLeaveModal] = useState(false);
const [listCommitError, setListCommitError] = useState(null);
const verificationPausedRef = useRef(false);
const { scanDefaults } = useScannerSession();
const queue = useScannerQueue({ user, scanDefaults, deckMode: null });
const onVerifyCardRef = useRef(null);
const camera = useCameraScanner({
onError: (msg) => console.error('Camera error:', msg),
onVerifyCard: (cardTracker) => onVerifyCardRef.current?.(cardTracker),
verificationPausedRef,
});
const identification = useScannerIdentification({
onCardScanned: queue.handleCardScanned,
onError: (msg) => console.error('Identification error:', msg),
videoRef: camera.videoRef,
canvasRef: camera.canvasRef,
onVerifyCardRef,
verificationPausedRef,
});
const unprocessedCount = queue.unprocessedCount;
useEffect(() => {
if (!authLoading && !user) {
router.push(`/login?returnUrl=${encodeURIComponent('/scanner')}`);
}
}, [authLoading, user, router]);
useEffect(() => {
const mobileCheckoutPauses =
typeof window !== 'undefined' &&
window.matchMedia('(max-width: 767px)').matches &&
isCheckoutOpen;
verificationPausedRef.current =
mobileCheckoutPauses ||
isListPickerOpen ||
Boolean(identification.disambiguation);
}, [isCheckoutOpen, isListPickerOpen, identification.disambiguation]);
const handleLeaveConfirm = () => {
clearScannerCartStorage();
queue.clearScannedCards();
setShowLeaveModal(false);
router.back();
};
const handleListPick = async (collectionId) => {
setListCommitError(null);
const selectedIds = queue.scannedCards
.filter((card) => queue.selectedCards.has(card.id))
.map((card) => card.id);
if (selectedIds.length === 0) return;
const successfulIds = await queue.commitSelectedToCollection(collectionId);
if (!successfulIds?.length) {
setListCommitError('Could not add cards to the list. Try again.');
return;
}
setIsListPickerOpen(false);
};
if (authLoading) {
return (
<Layout user={null}>
<div className="flex items-center justify-center min-h-[50vh]">
<div
className="animate-spin rounded-full h-12 w-12 border-b-2"
style={{ borderColor: 'var(--text-accent)' }}
/>
</div>
</Layout>
);
}
if (!user) {
return null;
}
return (
<Layout user={user} chrome="immersive">
<div className="relative flex flex-col md:flex-row h-full min-h-0 max-md:fixed max-md:inset-0">
<div
className="flex-1 min-h-0 min-w-0"
inert={isCheckoutOpen ? true : undefined}
aria-hidden={isCheckoutOpen || undefined}
>
<ScannerCamera
queue={queue}
camera={camera}
identification={identification}
onBack={() =>
unprocessedCount > 0 ? setShowLeaveModal(true) : router.back()
}
onOpenCheckout={() => setIsCheckoutOpen(true)}
onGalleryIdentify={(file) => identification.identifyFromGalleryFile(file)}
latestPeekCard={queue.scannedCards[0] ?? null}
cartCount={unprocessedCount}
isCheckoutOpen={isCheckoutOpen}
verificationPausedRef={verificationPausedRef}
/>
</div>
<div className="md:hidden">
{isCheckoutOpen && (
<ScannerCheckoutSheet
queue={queue}
onClose={() => setIsCheckoutOpen(false)}
onOpenListPicker={() => setIsListPickerOpen(true)}
trapActive={!isListPickerOpen}
/>
)}
</div>
<div
className="hidden md:flex md:w-[360px] md:flex-shrink-0 md:border-l md:min-h-0"
style={{ borderColor: 'var(--border)' }}
>
<ScannerReview
queue={queue}
collections={queue.collections}
variant="side-panel"
onOpenListPicker={() => setIsListPickerOpen(true)}
/>
</div>
<Modal
open={showLeaveModal}
onClose={() => setShowLeaveModal(false)}
title="Leave scanner?"
description={`${unprocessedCount} scanned ${unprocessedCount === 1 ? 'card' : 'cards'} haven't been added yet. Leaving will clear your cart.`}
>
<div className="flex flex-col sm:flex-row gap-3 sm:justify-end">
<Button variant="secondary" onClick={() => setShowLeaveModal(false)}>
Keep scanning
</Button>
<Button variant="danger" onClick={handleLeaveConfirm}>
Leave
</Button>
</div>
</Modal>
<Modal
open={isListPickerOpen}
onClose={() => {
setIsListPickerOpen(false);
setListCommitError(null);
}}
title="Choose a List"
description="Add the selected cards to one of your lists."
>
{listCommitError && (
<div
className="mb-3 px-3 py-2 rounded-lg text-sm"
style={{
backgroundColor: 'color-mix(in srgb, var(--color-error) 12%, transparent)',
border: '1px solid color-mix(in srgb, var(--color-error) 35%, transparent)',
color: 'var(--color-error)',
}}
role="alert"
>
{listCommitError}
</div>
)}
<ul className="space-y-2 max-h-[50vh] overflow-y-auto">
{queue.collections.map((collection) => (
<li key={collection.id}>
<button
type="button"
onClick={() => handleListPick(collection.id)}
disabled={queue.isProcessing}
className="w-full text-left px-4 py-3 rounded-xl transition-opacity hover:opacity-80 disabled:opacity-50 glass-panel"
style={{ color: 'var(--text-primary)', minHeight: 44 }}
>
{collectionDisplayName(collection)}
</button>
</li>
))}
{queue.collections.length === 0 && (
<p className="text-sm" style={{ color: 'var(--text-secondary)' }}>
No lists yet. Create a list from the Lists page first.
</p>
)}
</ul>
</Modal>
</div>
</Layout>
);
}