Files
MealQuest/web/src/discover/DiscoverPage.tsx
T

390 lines
15 KiB
TypeScript
Raw Normal View History

2026-10-07 01:28:13 -04:00
import { useQueryClient } from '@tanstack/react-query'
import { Heart, X } from 'lucide-react'
2026-10-07 02:18:40 -04:00
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type PointerEvent, type Ref } from 'react'
2026-10-07 01:28:13 -04:00
import { useJob } from '../api/index.ts'
import { Card } from '../ui/Card.tsx'
import { EmptyState } from '../ui/EmptyState.tsx'
import { ErrorBanner } from '../ui/ErrorBanner.tsx'
import { Icon } from '../ui/Icon.tsx'
import { IconButton } from '../ui/IconButton.tsx'
import { Skeleton } from '../ui/Skeleton.tsx'
import {
BATCH_JOB_KIND,
DECK_KEY,
parseBatchResult,
useDeck,
useDecide,
useQuestLog,
useStartBatch,
type Choice,
} from './api.ts'
2026-10-07 02:18:40 -04:00
import { DeckCard, DECK_DEPTH, type SwipeHandlers } from './DeckCard.tsx'
import {
bump,
fadeOut,
follow,
isAbort,
pass,
prefersReducedMotion,
promote,
snapBack,
tryIt,
unfollow,
type Exit,
} from './motion.ts'
2026-10-07 01:28:13 -04:00
import styles from './DiscoverPage.module.css'
2026-10-07 02:18:40 -04:00
// SWIPE_THRESHOLD is how far, in px, the top card must be dragged left or
// right for its release to Pass or Try it.
const SWIPE_THRESHOLD = 110
// A Drag is the pointer dragging the top card: where it went down, and the
// card's drag transform so far.
type Drag = { pointerId: number; x: number; y: number; dx: number; transform: string | null }
2026-10-07 01:28:13 -04:00
// isEditable says whether a key press belongs to a field being typed in,
// which the deck's ← / → keys leave alone.
function isEditable(target: EventTarget | null): boolean {
return (
target instanceof HTMLElement &&
(target.isContentEditable || target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement || target instanceof HTMLSelectElement)
)
}
// QuestLogPill is the "Quest log · N" pill. It shows and hides the names
// of the dinners in the Quest log; the Quest log sheet replaces this list.
// ref is the visible pill, which Try it bumps.
function QuestLogPill({ dinners, ref }: { dinners: { id: string; name: string }[]; ref: Ref<HTMLSpanElement> }) {
2026-10-07 01:28:13 -04:00
const [open, setOpen] = useState(false)
const listId = useId()
return (
<>
<button
type="button"
className={styles.questLogButton}
aria-expanded={open}
aria-controls={open ? listId : undefined}
onClick={() => setOpen(!open)}
>
<span ref={ref} className={styles.questLog}>Quest log · {dinners.length}</span>
2026-10-07 01:28:13 -04:00
</button>
{open && (
<Card id={listId} tone="muted" className={styles.questLogList}>
{dinners.length === 0 ? (
<p className={styles.questLogEmpty}>No dinners in the Quest log yet. Try it on a Side quest to add one.</p>
) : (
<ul aria-label="Quest log" className={styles.questLogNames}>
{dinners.map((dinner) => (
<li key={dinner.id}>{dinner.name}</li>
))}
</ul>
)}
</Card>
)}
</>
)
}
// DiscoverPage is mock 1a: the deck of Side quests to Try it or Pass, one
2026-10-07 02:18:40 -04:00
// at a time from the top card. A decision from the buttons, the ← / → keys
// or a swipe of the top card throws it out (motion.ts) and sends the
// decision once it is gone, taking the card off the deck at once (see
// useDecide); Retry sends a refused one again. Input is
2026-10-07 02:18:40 -04:00
// locked from the press until the decision settles: the lock is a ref, set
// before anything starts, so a second press before the next render does
// nothing, and busy mirrors it to disable the buttons.
2026-10-07 01:28:13 -04:00
export function DiscoverPage() {
const queryClient = useQueryClient()
const deck = useDeck()
const questLog = useQuestLog()
const decision = useDecide()
const startBatch = useStartBatch()
// The job of the batch last known to be finding Side quests: the one Get
// more now started or joined, or the replenish a decision started.
const [batchJobId, setBatchJobId] = useState<string | null>(null)
const job = useJob<unknown>(BATCH_JOB_KIND, batchJobId)
2026-10-07 01:28:13 -04:00
const top = deck.data?.[0]
const [busy, setBusy] = useState(false)
const jobRunning = batchJobId !== null && job.status !== 'succeeded' && job.status !== 'failed'
2026-10-07 01:28:13 -04:00
const finding = startBatch.isPending || jobRunning
const { mutate: mutateStartBatch } = startBatch
const getMore = useCallback(() => mutateStartBatch(undefined, { onSuccess: (b) => setBatchJobId(b.job_id) }), [mutateStartBatch])
2026-10-07 01:28:13 -04:00
// The batch's result as far as it has gone, or why it cannot be read.
const batch = useMemo(() => {
if (job.result === null) return { stored: 0, error: null }
try {
return { stored: parseBatchResult(`GET /api/v1/jobs/${batchJobId}`, job.result).suggestion_ids.length, error: null }
2026-10-07 01:28:13 -04:00
} catch (error) {
return { stored: 0, error: error as Error }
}
}, [job.result, batchJobId])
2026-10-07 01:28:13 -04:00
// The job's failure, the latest poll's failure, an answer that is not the
// batch's job, or an unreadable result.
const batchError = job.error ?? batch.error
const deckRef = useRef<HTMLDivElement>(null)
const passRef = useRef<HTMLButtonElement>(null)
const tryRef = useRef<HTMLButtonElement>(null)
const questLogRef = useRef<HTMLSpanElement>(null)
// The top card's exit until its decision settles, and the Side quest the
// last decision sent was for, until the deck moves past it.
const exit = useRef<Exit | null>(null)
const leaving = useRef<string | null>(null)
2026-10-07 02:18:40 -04:00
const drag = useRef<Drag | null>(null)
// The top card's snap-back while it may still run; a new drag or a
// decision stops it so it does not fight the card's new motion.
const springing = useRef<Animation | null>(null)
const stopSpring = useCallback(() => {
springing.current?.cancel()
springing.current = null
}, [])
2026-10-07 01:28:13 -04:00
const { mutate: mutateDecision } = decision
const deciding = useRef(false)
const lock = useCallback(() => {
if (deciding.current) return false
deciding.current = true
setBusy(true)
return true
}, [])
// send records a decision. A refused one puts the card back; a saved one
// that started a replenish batch follows its job.
const send = useCallback(
2026-10-07 01:28:13 -04:00
(variables: { id: string; choice: Choice }) => {
leaving.current = variables.id
2026-10-07 01:28:13 -04:00
mutateDecision(variables, {
onSuccess: (replenishJobId) => {
if (replenishJobId !== null) setBatchJobId(replenishJobId)
},
onError: () => {
exit.current?.cancel()
leaving.current = null
},
2026-10-07 01:28:13 -04:00
onSettled: () => {
exit.current = null
2026-10-07 01:28:13 -04:00
deciding.current = false
setBusy(false)
2026-10-07 01:28:13 -04:00
},
})
},
[mutateDecision],
)
const submit = useCallback(
(variables: { id: string; choice: Choice }) => {
if (lock()) send(variables)
},
[lock, send],
)
// decide bumps the button, throws the top card out — or, motion reduced,
// fades it — then sends the decision; Try it bumps the Quest log pill too.
2026-10-07 02:18:40 -04:00
// A swipe's decision comes from the card's drag transform: it is thrown
// from there without a bump or wiggle. A button or key decision ends a
// drag in progress, putting the card back first.
2026-10-07 01:28:13 -04:00
const decide = useCallback(
2026-10-07 02:18:40 -04:00
(choice: Choice, from?: string) => {
if (top === undefined || !lock()) return
2026-10-07 02:18:40 -04:00
stopSpring()
const card = deckRef.current!.querySelector('article')!
2026-10-07 02:18:40 -04:00
if (from === undefined && drag.current !== null) {
drag.current = null
unfollow(card)
}
const reduced = prefersReducedMotion()
let run: Exit
if (reduced) {
run = fadeOut(card)
2026-10-07 02:18:40 -04:00
} else if (from === undefined) {
bump((choice === 'try' ? tryRef : passRef).current!)
run = choice === 'try' ? tryIt(card) : pass(card)
2026-10-07 02:18:40 -04:00
} else {
run = choice === 'try' ? tryIt(card, from) : pass(card, from)
}
if (from !== undefined) {
// Putting a swiped card back puts it back at rest.
const thrown = run
run = {
finished: thrown.finished,
cancel: () => {
thrown.cancel()
unfollow(card)
},
}
}
exit.current = run
run.finished.then(
() => {
// The Quest log pill is missing while the Quest log fails to load.
if (choice === 'try' && !reduced && questLogRef.current !== null) bump(questLogRef.current)
send({ id: top.id, choice })
},
(error: unknown) => {
if (!isAbort(error)) throw error
},
)
2026-10-07 01:28:13 -04:00
},
2026-10-07 02:18:40 -04:00
[top, lock, send, stopSpring],
2026-10-07 01:28:13 -04:00
)
2026-10-07 02:18:40 -04:00
// swipe drags the top card: it follows the pointer, captured from the
// press, until the release decides past the threshold or springs it back
// short of it. The release decides from where the pointer let go, which
// may differ from its last move. A cancel, or losing the capture before
// the release, springs it back from its last move. One pointer drags at
// a time: a press while a drag is in progress is ignored, as is input
// while busy, and a drag held into a busy spell (a Retry) is put back on
// release.
const swipe = useMemo<SwipeHandlers>(() => {
function track(card: HTMLElement, current: Drag, event: PointerEvent<HTMLElement>) {
current.dx = event.clientX - current.x
current.transform = follow(card, current.dx, event.clientY - current.y)
}
function release(event: PointerEvent<HTMLElement>, decides: boolean) {
const card = event.currentTarget
const current = drag.current
if (current === null || current.pointerId !== event.pointerId) return
drag.current = null
const moved = current.transform !== null || event.clientX !== current.x || event.clientY !== current.y
if (decides && moved && !deciding.current) track(card, current, event)
if (current.transform === null) return
if (deciding.current) unfollow(card)
else if (decides && current.dx > SWIPE_THRESHOLD) decide('try', current.transform)
else if (decides && current.dx < -SWIPE_THRESHOLD) decide('pass', current.transform)
else if (prefersReducedMotion()) unfollow(card)
else springing.current = snapBack(card, current.transform)
}
return {
onPointerDown: (event) => {
if (drag.current !== null || deciding.current || !event.isPrimary || event.button !== 0) return
stopSpring()
event.currentTarget.setPointerCapture(event.pointerId)
drag.current = { pointerId: event.pointerId, x: event.clientX, y: event.clientY, dx: 0, transform: null }
},
onPointerMove: (event) => {
const current = drag.current
if (current === null || current.pointerId !== event.pointerId || deciding.current) return
track(event.currentTarget, current, event)
},
onPointerUp: (event) => release(event, true),
onPointerCancel: (event) => release(event, false),
// After a release the drag is already over, so this only ends a drag
// whose capture was lost before it.
onLostPointerCapture: (event) => release(event, false),
}
}, [decide, stopSpring])
// Leaving the page stops an exit before its decision is sent.
useEffect(() => () => exit.current?.cancel(), [])
2026-10-07 02:18:40 -04:00
const topId = top?.id
// A drag belongs to the card it started on, which a new top card ends.
useLayoutEffect(() => {
drag.current = null
}, [topId])
// Once the deck moves past the card a decision was sent for, the cards
// behind it move up a depth.
useLayoutEffect(() => {
if (leaving.current === null || leaving.current === topId) return
leaving.current = null
if (topId === undefined || prefersReducedMotion()) return
promote([...deckRef.current!.querySelectorAll<HTMLElement>(':scope > article')])
}, [topId])
2026-10-07 01:28:13 -04:00
useEffect(() => {
function onKeyDown(event: KeyboardEvent) {
if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
if (isEditable(event.target)) return
if (event.key === 'ArrowLeft') decide('pass')
else if (event.key === 'ArrowRight') decide('try')
else return
event.preventDefault()
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [decide])
// The batch stores its Side quests as it goes, so the deck is read again
// whenever it reports more, and once it ends.
const { stored } = batch
useEffect(() => {
if (job.status === undefined) return
void queryClient.invalidateQueries({ queryKey: DECK_KEY })
}, [queryClient, job.status, stored])
let body
if (deck.isError) {
body = <ErrorBanner onRetry={() => void deck.refetch()}>Couldn't load your side quests. {deck.error.message}</ErrorBanner>
} else if (deck.isPending || (deck.data.length === 0 && (finding || decision.isPending))) {
// An empty deck is not caught up while a batch finds more Side quests,
// or while the last decision may yet start one or come back refused.
2026-10-07 01:28:13 -04:00
body = (
<section aria-busy="true" aria-label="Side quests loading" className={styles.loading}>
<div className={styles.deck}>
{DECK_DEPTH.map((depth) => (
<Skeleton key={depth} data-testid="skeleton-card" className={`${styles.skeletonCard} ${styles[`depth${depth}`]}`} />
))}
</div>
{finding && <p className={styles.finding}>Finding new side quests…</p>}
{jobRunning && batchError !== null && (
<ErrorBanner onRetry={job.poll}>Couldn't check on new side quests. {batchError.message}</ErrorBanner>
)}
</section>
)
} else if (top === undefined) {
body = (
<>
{startBatch.isError && (
<ErrorBanner onRetry={getMore}>Couldn't ask for more side quests. {startBatch.error.message}</ErrorBanner>
2026-10-07 01:28:13 -04:00
)}
{batchError !== null && (
<ErrorBanner onRetry={getMore}>Couldn't find new side quests. {batchError.message}</ErrorBanner>
2026-10-07 01:28:13 -04:00
)}
<EmptyState title="All caught up" action={{ label: 'Get more now', onClick: getMore }}>
2026-10-07 01:28:13 -04:00
New side quests arrive Sunday.
</EmptyState>
</>
)
} else {
body = (
<>
<div ref={deckRef} className={styles.deck}>
2026-10-07 01:28:13 -04:00
{deck.data.slice(0, DECK_DEPTH.length).map((quest, depth) => (
2026-10-07 02:18:40 -04:00
<DeckCard key={quest.id} quest={quest} depth={depth} swipe={depth === 0 ? swipe : undefined} />
2026-10-07 01:28:13 -04:00
))}
</div>
<div className={styles.actions}>
<IconButton ref={passRef} label="Pass" size={62} tone="neutral" showLabel disabled={busy} onClick={() => decide('pass')}>
2026-10-07 01:28:13 -04:00
<Icon icon={X} size="nav" />
</IconButton>
<IconButton ref={tryRef} label="Try it" size={62} tone="teal" showLabel disabled={busy} onClick={() => decide('try')}>
2026-10-07 01:28:13 -04:00
<Icon icon={Heart} size="nav" />
</IconButton>
</div>
{decision.isError && (
<ErrorBanner onRetry={() => submit(decision.variables!)}>
Couldn't save that choice. {decision.error.message}
</ErrorBanner>
)}
</>
)
}
return (
<div className={styles.page}>
<header className={styles.header}>
<div>
<p className={styles.kicker}>Discover</p>
<h1 className={styles.title}>Side quests</h1>
</div>
{questLog.isSuccess && <QuestLogPill ref={questLogRef} dinners={questLog.data} />}
2026-10-07 01:28:13 -04:00
</header>
{questLog.isError && (
<ErrorBanner onRetry={() => void questLog.refetch()}>Couldn't load the Quest log. {questLog.error.message}</ErrorBanner>
)}
{body}
</div>
)
}