Add the swipe gesture to the Discover deck's top card
The top card follows a pointer drag per handoff Motion §4: captured with setPointerCapture under touch-action none, it moves to translate(dx, dy*0.3) rotate(dx/18 deg) with the "Try it!" and "Pass" stamps at clamp(±dx/100). A release past 110 px right throws it from where it was let go (340 ms, no wiggle); past 110 px left folds it from the drag transform; anything shorter springs back over 420 ms and resets the stamps. Swipe decisions go through the same decide handler as the buttons and ← / → keys, so the busy lock and reduced-motion fade apply unchanged; only the top card is draggable and input is ignored while busy. motion.ts gains dragTransform, follow, unfollow and snapBack beside the exits; DeckCard marks its Pass stamp as a part. Maestro task 54c12e9e-5f36-4595-babb-e54107bb473b. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import type { DOMAttributes } from 'react'
|
||||
import { DIFFICULTIES, type Difficulty } from '../dinners/api.ts'
|
||||
import { Photo } from '../ui/Photo.tsx'
|
||||
import type { SideQuest } from './api.ts'
|
||||
@@ -8,25 +9,32 @@ export const DECK_DEPTH = [0, 1, 2] as const
|
||||
|
||||
const DIFFICULTY_LABEL: Record<Difficulty, string> = { easy: 'Easy', medium: 'Medium', hard: 'Hard' }
|
||||
|
||||
// SwipeHandlers are the pointer handlers that drag the top card.
|
||||
export type SwipeHandlers = Pick<DOMAttributes<HTMLElement>, 'onPointerDown' | 'onPointerMove' | 'onPointerUp' | 'onPointerCancel'>
|
||||
|
||||
export type DeckCardProps = {
|
||||
quest: SideQuest
|
||||
// 0 is the top card; 1 and 2 stack behind it.
|
||||
depth: number
|
||||
// swipe makes the card draggable; only the top card gets it.
|
||||
swipe?: SwipeHandlers
|
||||
}
|
||||
|
||||
// DeckCard is one Side quest in the deck. Only the top card is read out and
|
||||
// reachable; the cards behind it are the stack's edge, kept rendered so they
|
||||
// can be promoted. Its "Try it!" and "Pass" stamps stay hidden until a
|
||||
// decision shows them, and its shade until Pass folds it (see motion.ts).
|
||||
export function DeckCard({ quest, depth }: DeckCardProps) {
|
||||
// decision or a drag shows them, and its shade until Pass folds it (see
|
||||
// motion.ts).
|
||||
export function DeckCard({ quest, depth, swipe }: DeckCardProps) {
|
||||
const top = depth === 0
|
||||
const titleId = `side-quest-${quest.id}`
|
||||
return (
|
||||
<article
|
||||
className={`${styles.card} ${styles[`depth${depth}`]}`}
|
||||
className={`${styles.card} ${styles[`depth${depth}`]}${swipe === undefined ? '' : ` ${styles.draggable}`}`}
|
||||
aria-labelledby={top ? titleId : undefined}
|
||||
aria-hidden={top ? undefined : true}
|
||||
inert={!top}
|
||||
{...swipe}
|
||||
>
|
||||
<Photo id={quest.photo_id} name={quest.name} radius="24px" inset="10px" sizes="400px" className={styles.photo} />
|
||||
<div className={styles.content}>
|
||||
@@ -41,7 +49,7 @@ export function DeckCard({ quest, depth }: DeckCardProps) {
|
||||
<span className={`${styles.stamp} ${styles.tryStamp}`} data-part="try-stamp" aria-hidden="true">
|
||||
Try it!
|
||||
</span>
|
||||
<span className={`${styles.stamp} ${styles.passStamp}`} aria-hidden="true">
|
||||
<span className={`${styles.stamp} ${styles.passStamp}`} data-part="pass-stamp" aria-hidden="true">
|
||||
Pass
|
||||
</span>
|
||||
<span className={styles.shade} data-part="shade" />
|
||||
|
||||
@@ -104,6 +104,12 @@
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
/* The top card follows a drag instead of scrolling the page. */
|
||||
.draggable {
|
||||
touch-action: none;
|
||||
cursor: grab;
|
||||
}
|
||||
|
||||
.depth1 {
|
||||
z-index: 2;
|
||||
transform: translateY(8px) scale(0.95);
|
||||
|
||||
@@ -668,4 +668,342 @@ describe('DiscoverPage', () => {
|
||||
expect(sent(server.fetchMock)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('swipe', () => {
|
||||
const accepted = (quest: typeof BOWLS) => jsonResponse(200, { suggestion: { ...quest, status: 'accepted' }, replenish_job_id: null })
|
||||
const declined = (quest: typeof BOWLS) => jsonResponse(200, { suggestion: { ...quest, status: 'declined' }, replenish_job_id: null })
|
||||
const on = (animations: FakeAnimation[], target: Element) => animations.filter((a) => a.target === target)
|
||||
const SPRING = 'cubic-bezier(.34,1.4,.64,1)'
|
||||
let capture: Mock<(pointerId: number) => void>
|
||||
|
||||
// jsdom has no pointer capture.
|
||||
beforeEach(() => {
|
||||
capture = vi.fn()
|
||||
Element.prototype.setPointerCapture = capture
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Reflect.deleteProperty(Element.prototype, 'setPointerCapture')
|
||||
})
|
||||
|
||||
// press, drag and release put a pointer down on the card at (200, 300),
|
||||
// move it by dx, dy, and let go.
|
||||
function press(card: Element) {
|
||||
fireEvent.pointerDown(card, { pointerId: 7, isPrimary: true, button: 0, clientX: 200, clientY: 300 })
|
||||
}
|
||||
function drag(card: Element, dx: number, dy: number) {
|
||||
fireEvent.pointerMove(card, { pointerId: 7, isPrimary: true, clientX: 200 + dx, clientY: 300 + dy })
|
||||
}
|
||||
function release(card: Element) {
|
||||
fireEvent.pointerUp(card, { pointerId: 7, isPrimary: true, button: 0 })
|
||||
}
|
||||
const stamps = (card: HTMLElement) => [within(card).getByText('Try it!'), within(card).getByText('Pass')]
|
||||
|
||||
it('makes the top card follow the pointer, captured, with the stamps showing how far it has gone', async () => {
|
||||
stubServer([BOWLS, TIKKA])
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
const [tryStamp, passStamp] = stamps(card)
|
||||
expect(declaredStyle(card).getPropertyValue('touch-action')).toBe('none')
|
||||
|
||||
press(card)
|
||||
expect(capture).toHaveBeenCalledExactlyOnceWith(7)
|
||||
expect(capture.mock.contexts[0]).toBe(card)
|
||||
|
||||
drag(card, 54, 20)
|
||||
expect(card.style.transform).toBe('translate(54px,6px) rotate(3deg)')
|
||||
expect(tryStamp!.style.opacity).toBe('0.54')
|
||||
expect(passStamp!.style.opacity).toBe('0')
|
||||
|
||||
drag(card, -36, -10)
|
||||
expect(card.style.transform).toBe('translate(-36px,-3px) rotate(-2deg)')
|
||||
expect(tryStamp!.style.opacity).toBe('0')
|
||||
expect(passStamp!.style.opacity).toBe('0.36')
|
||||
|
||||
drag(card, -180, 0)
|
||||
expect(tryStamp!.style.opacity).toBe('0')
|
||||
expect(passStamp!.style.opacity).toBe('1')
|
||||
expect(animations).toEqual([])
|
||||
})
|
||||
|
||||
it('Try it on a release past 110 px right: throws the card from where it was let go, in 340 ms with no wiggle, then records it', async () => {
|
||||
const server = stubServer([BOWLS, TIKKA, ORZO], {
|
||||
'POST /api/v1/suggestions/s1/accept': () => {
|
||||
server.deck = [TIKKA, ORZO]
|
||||
return accepted(BOWLS)
|
||||
},
|
||||
})
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
const pill = await screen.findByText('Quest log · 6')
|
||||
const tryButton = screen.getByRole('button', { name: 'Try it' })
|
||||
|
||||
press(card)
|
||||
drag(card, 126, 30)
|
||||
release(card)
|
||||
// No button bump, no wiggle: the stamp pops and the card flies.
|
||||
expect(animations.map((a) => a.target)).toEqual([within(card).getByText('Try it!')])
|
||||
await waitFor(() => expect(tryButton).toBeDisabled())
|
||||
expect(animations).toHaveLength(2)
|
||||
const fly = animations[1]!
|
||||
expect(fly.target).toBe(card)
|
||||
expect(fly.keyframes).toEqual([
|
||||
{ transform: 'translate(126px,9px) rotate(7deg)' },
|
||||
{ transform: 'translate(150%,-60px) rotate(28deg)', opacity: 0 },
|
||||
])
|
||||
expect(fly.options).toEqual({ duration: 340, easing: 'cubic-bezier(.55,0,.8,.4)', fill: 'forwards' })
|
||||
expect(sent(server.fetchMock)).toEqual([])
|
||||
|
||||
await finishRunning(animations)
|
||||
expect(sent(server.fetchMock)).toEqual(['POST /api/v1/suggestions/s1/accept'])
|
||||
expect(on(animations, pill)).toHaveLength(1)
|
||||
const next = await screen.findByRole('article', { name: 'Crock pot chicken tikka masala' })
|
||||
expect(on(animations, next).map((a) => a.options)).toEqual([{ duration: 300, easing: 'cubic-bezier(.2,.8,.2,1)' }])
|
||||
await waitFor(() => expect(tryButton).toBeEnabled())
|
||||
expect(next.style.transform).toBe('')
|
||||
})
|
||||
|
||||
it('Pass on a release past 110 px left: folds the card from where it was let go, then records it', async () => {
|
||||
const server = stubServer([BOWLS, TIKKA], {
|
||||
'POST /api/v1/suggestions/s1/decline': () => {
|
||||
server.deck = [TIKKA]
|
||||
return declined(BOWLS)
|
||||
},
|
||||
})
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
const pill = await screen.findByText('Quest log · 6')
|
||||
const shade = card.querySelector('[data-part="shade"]')!
|
||||
|
||||
press(card)
|
||||
drag(card, -144, 20)
|
||||
release(card)
|
||||
expect(animations.map((a) => a.target)).toEqual([shade, card])
|
||||
expect(animations[1]!.keyframes).toEqual([
|
||||
{ transformOrigin: '0% 50%', transform: 'translate(-144px,6px) rotate(-8deg) rotateY(0deg)', easing: 'cubic-bezier(.45,0,.85,.55)' },
|
||||
{ transformOrigin: '0% 50%', transform: 'translate(-144px,6px) rotate(-8deg) rotateY(-80deg)', offset: 0.45, easing: 'cubic-bezier(.4,0,.9,.6)' },
|
||||
{ transformOrigin: '0% 50%', transform: 'translate(-45%,560px) rotate(-35deg) rotateY(-90deg)', opacity: 0 },
|
||||
])
|
||||
expect(animations[1]!.options).toEqual({ duration: 720, fill: 'forwards' })
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Pass' })).toBeDisabled())
|
||||
expect(sent(server.fetchMock)).toEqual([])
|
||||
|
||||
await finishRunning(animations)
|
||||
expect(sent(server.fetchMock)).toEqual(['POST /api/v1/suggestions/s1/decline'])
|
||||
await screen.findByRole('article', { name: 'Crock pot chicken tikka masala' })
|
||||
expect(on(animations, pill)).toEqual([])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['right', 110],
|
||||
['left', -110],
|
||||
])('springs the card back from a release of 110 px %s, resetting the stamps and deciding nothing', async (_, dx) => {
|
||||
const server = stubServer([BOWLS, TIKKA])
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
const [tryStamp, passStamp] = stamps(card)
|
||||
|
||||
press(card)
|
||||
drag(card, dx, 0)
|
||||
expect([tryStamp!.style.opacity, passStamp!.style.opacity]).toContain('1')
|
||||
release(card)
|
||||
expect(animations).toHaveLength(1)
|
||||
expect(animations[0]!.target).toBe(card)
|
||||
expect(animations[0]!.keyframes).toEqual([{ transform: `translate(${dx}px,0px) rotate(${dx / 18}deg)` }, { transform: 'translate(0px,0px) rotate(0deg)' }])
|
||||
expect(animations[0]!.options).toEqual({ duration: 420, easing: SPRING })
|
||||
expect(card.style.transform).toBe('')
|
||||
expect(tryStamp!.style.opacity).toBe('')
|
||||
expect(passStamp!.style.opacity).toBe('')
|
||||
expect(getComputedStyle(tryStamp!).opacity).toBe('0')
|
||||
expect(getComputedStyle(passStamp!).opacity).toBe('0')
|
||||
|
||||
// A later move with the pointer up does nothing.
|
||||
drag(card, 200, 0)
|
||||
expect(card.style.transform).toBe('')
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
expect(screen.getByRole('button', { name: 'Try it' })).toBeEnabled()
|
||||
expect(sent(server.fetchMock)).toEqual([])
|
||||
})
|
||||
|
||||
it('springs the card back when the pointer is canceled, however far it went', async () => {
|
||||
const server = stubServer([BOWLS])
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
|
||||
press(card)
|
||||
drag(card, 180, 0)
|
||||
fireEvent.pointerCancel(card, { pointerId: 7, isPrimary: true })
|
||||
expect(animations.map((a) => a.options)).toEqual([{ duration: 420, easing: SPRING }])
|
||||
expect(card.style.transform).toBe('')
|
||||
expect(sent(server.fetchMock)).toEqual([])
|
||||
})
|
||||
|
||||
it('ignores a drag while busy', async () => {
|
||||
const server = stubServer([BOWLS, TIKKA], { 'POST /api/v1/suggestions/s1/decline': () => declined(BOWLS) })
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Pass' }))
|
||||
const started = animations.length
|
||||
press(card)
|
||||
drag(card, 160, 0)
|
||||
release(card)
|
||||
expect(capture).not.toHaveBeenCalled()
|
||||
expect(card.style.transform).toBe('')
|
||||
expect(animations).toHaveLength(started)
|
||||
await finishRunning(animations)
|
||||
expect(sent(server.fetchMock)).toEqual(['POST /api/v1/suggestions/s1/decline'])
|
||||
})
|
||||
|
||||
it('puts a drag held while a Retry goes out back at once on release, deciding nothing', async () => {
|
||||
const retry = deferred()
|
||||
let calls = 0
|
||||
const server = stubServer([BOWLS, TIKKA], {
|
||||
'POST /api/v1/suggestions/s1/accept': () => (++calls === 1 ? errorResponse(500, 'internal') : retry.promise),
|
||||
})
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Try it' }))
|
||||
const alert = await screen.findByRole('alert')
|
||||
|
||||
press(card)
|
||||
drag(card, 60, 0)
|
||||
fireEvent.click(within(alert).getByRole('button', { name: 'Retry' }))
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Try it' })).toBeDisabled())
|
||||
drag(card, -160, 0)
|
||||
expect(card.style.transform).toBe('translate(60px,0px) rotate(3.3333333333333335deg)')
|
||||
const started = vi.mocked(Element.prototype.animate).mock.calls.length
|
||||
release(card)
|
||||
expect(card.style.transform).toBe('')
|
||||
expect(within(card).getByText('Try it!').style.opacity).toBe('')
|
||||
expect(vi.mocked(Element.prototype.animate).mock.calls.length).toBe(started)
|
||||
expect(sent(server.fetchMock)).toEqual(['POST /api/v1/suggestions/s1/accept', 'POST /api/v1/suggestions/s1/accept'])
|
||||
retry.resolve(accepted(BOWLS))
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Try it' })).toBeEnabled())
|
||||
})
|
||||
|
||||
it('drags only the top card', async () => {
|
||||
const server = stubServer([BOWLS, TIKKA, ORZO])
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
const { container } = await renderPage()
|
||||
await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
const [, second, third] = container.querySelectorAll<HTMLElement>('article')
|
||||
|
||||
for (const card of [second!, third!]) {
|
||||
expect(declaredStyle(card).getPropertyValue('touch-action')).toBe('')
|
||||
press(card)
|
||||
drag(card, 160, 0)
|
||||
release(card)
|
||||
expect(card.style.transform).toBe('')
|
||||
}
|
||||
expect(capture).not.toHaveBeenCalled()
|
||||
expect(animations).toEqual([])
|
||||
expect(sent(server.fetchMock)).toEqual([])
|
||||
})
|
||||
|
||||
it('ignores a press that is not the primary button', async () => {
|
||||
stubServer([BOWLS])
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
|
||||
fireEvent.pointerDown(card, { pointerId: 7, isPrimary: true, button: 2, clientX: 200, clientY: 300 })
|
||||
drag(card, 160, 0)
|
||||
expect(capture).not.toHaveBeenCalled()
|
||||
expect(card.style.transform).toBe('')
|
||||
})
|
||||
|
||||
it('a key decision mid-drag ends the drag and throws the card from rest', async () => {
|
||||
const server = stubServer([BOWLS, TIKKA], {
|
||||
'POST /api/v1/suggestions/s1/accept': () => {
|
||||
server.deck = [TIKKA]
|
||||
return accepted(BOWLS)
|
||||
},
|
||||
})
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
const [tryStamp] = stamps(card)
|
||||
|
||||
press(card)
|
||||
drag(card, -60, 0)
|
||||
fireEvent.keyDown(window, { key: 'ArrowRight' })
|
||||
expect(card.style.transform).toBe('')
|
||||
expect(tryStamp!.style.opacity).toBe('')
|
||||
// The button bump, stamp pop and wiggle of a Try it from rest.
|
||||
expect(animations.map((a) => a.target)).toEqual([screen.getByRole('button', { name: 'Try it' }), tryStamp, card])
|
||||
release(card)
|
||||
expect(animations).toHaveLength(3)
|
||||
await finishRunning(animations)
|
||||
await finishRunning(animations)
|
||||
expect(sent(server.fetchMock)).toEqual(['POST /api/v1/suggestions/s1/accept'])
|
||||
})
|
||||
|
||||
it('puts a swiped card back at rest when its decision is refused', async () => {
|
||||
stubServer([BOWLS], { 'POST /api/v1/suggestions/s1/decline': () => errorResponse(500, 'internal') })
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
const [tryStamp, passStamp] = stamps(card)
|
||||
|
||||
press(card)
|
||||
drag(card, -150, 0)
|
||||
release(card)
|
||||
await finishRunning(animations)
|
||||
await screen.findByRole('alert')
|
||||
expect(animations.map((a) => a.playState)).toEqual(['idle', 'idle'])
|
||||
expect(card.style.transform).toBe('')
|
||||
expect(tryStamp!.style.opacity).toBe('')
|
||||
expect(passStamp!.style.opacity).toBe('')
|
||||
expect(screen.getByRole('button', { name: 'Pass' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['Try it', 140, 'accept'],
|
||||
['Pass', -140, 'decline'],
|
||||
] as const)('%s by swipe with reduced motion fades the card where it was let go', async (_, dx, action) => {
|
||||
mockViewport(390, { reducedMotion: true })
|
||||
const server = stubServer([BOWLS, TIKKA], {
|
||||
[`POST /api/v1/suggestions/s1/${action}`]: () => {
|
||||
server.deck = [TIKKA]
|
||||
return action === 'accept' ? accepted(BOWLS) : declined(BOWLS)
|
||||
},
|
||||
})
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
|
||||
press(card)
|
||||
drag(card, dx, 0)
|
||||
release(card)
|
||||
expect(animations.map((a) => [a.target, a.keyframes, a.options])).toEqual([[card, [{ opacity: 1 }, { opacity: 0 }], { duration: 200, fill: 'forwards' }]])
|
||||
expect(card.style.transform).toBe(`translate(${dx}px,0px) rotate(${dx / 18}deg)`)
|
||||
await finishRunning(animations)
|
||||
expect(sent(server.fetchMock)).toEqual([`POST /api/v1/suggestions/s1/${action}`])
|
||||
await screen.findByRole('article', { name: 'Crock pot chicken tikka masala' })
|
||||
expect(animations).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('puts the card back at once, without the spring, from a short swipe with reduced motion', async () => {
|
||||
mockViewport(390, { reducedMotion: true })
|
||||
stubServer([BOWLS])
|
||||
const animations = stubAnimate({ autoFinish: false })
|
||||
await renderPage()
|
||||
const card = await screen.findByRole('article', { name: 'Korean beef bowls' })
|
||||
|
||||
press(card)
|
||||
drag(card, 80, 0)
|
||||
release(card)
|
||||
expect(animations).toEqual([])
|
||||
expect(card.style.transform).toBe('')
|
||||
expect(within(card).getByText('Try it!').style.opacity).toBe('')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -18,10 +18,30 @@ import {
|
||||
useStartBatch,
|
||||
type Choice,
|
||||
} from './api.ts'
|
||||
import { DeckCard, DECK_DEPTH } from './DeckCard.tsx'
|
||||
import { bump, fadeOut, isAbort, pass, prefersReducedMotion, promote, tryIt, type Exit } from './motion.ts'
|
||||
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'
|
||||
import styles from './DiscoverPage.module.css'
|
||||
|
||||
// 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 }
|
||||
|
||||
// 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 {
|
||||
@@ -66,12 +86,12 @@ function QuestLogPill({ dinners, ref }: { dinners: { id: string; name: string }[
|
||||
}
|
||||
|
||||
// DiscoverPage is mock 1a: the deck of Side quests to Try it or Pass, one
|
||||
// at a time from the top card. A decision from the buttons or the ← / → keys
|
||||
// throws the top card out (motion.ts) and sends the decision once it is
|
||||
// gone; Retry sends a refused one again. Input is 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.
|
||||
// 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; Retry sends a refused one again. Input is
|
||||
// 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.
|
||||
export function DiscoverPage() {
|
||||
const queryClient = useQueryClient()
|
||||
const deck = useDeck()
|
||||
@@ -106,6 +126,7 @@ export function DiscoverPage() {
|
||||
// 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)
|
||||
const drag = useRef<Drag | null>(null)
|
||||
|
||||
const { mutate: mutateDecision } = decision
|
||||
const deciding = useRef(false)
|
||||
@@ -141,17 +162,37 @@ export function DiscoverPage() {
|
||||
)
|
||||
// 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.
|
||||
// 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.
|
||||
const decide = useCallback(
|
||||
(choice: Choice) => {
|
||||
(choice: Choice, from?: string) => {
|
||||
if (top === undefined || !lock()) return
|
||||
const card = deckRef.current!.querySelector('article')!
|
||||
if (from === undefined && drag.current !== null) {
|
||||
drag.current = null
|
||||
unfollow(card)
|
||||
}
|
||||
const reduced = prefersReducedMotion()
|
||||
let run: Exit
|
||||
if (reduced) {
|
||||
run = fadeOut(card)
|
||||
} else {
|
||||
} else if (from === undefined) {
|
||||
bump((choice === 'try' ? tryRef : passRef).current!)
|
||||
run = choice === 'try' ? tryIt(card) : pass(card)
|
||||
} 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(
|
||||
@@ -168,6 +209,39 @@ export function DiscoverPage() {
|
||||
[top, lock, send],
|
||||
)
|
||||
|
||||
// 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. Input while busy is ignored, and a drag held into a busy
|
||||
// spell (a Retry) is put back on release.
|
||||
const swipe = useMemo<SwipeHandlers>(() => {
|
||||
function release(card: HTMLElement, pointerId: number, decides: boolean) {
|
||||
const current = drag.current
|
||||
if (current === null || current.pointerId !== pointerId) return
|
||||
drag.current = null
|
||||
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 snapBack(card, current.transform)
|
||||
}
|
||||
return {
|
||||
onPointerDown: (event) => {
|
||||
if (deciding.current || !event.isPrimary || event.button !== 0) return
|
||||
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
|
||||
current.dx = event.clientX - current.x
|
||||
current.transform = follow(event.currentTarget, current.dx, event.clientY - current.y)
|
||||
},
|
||||
onPointerUp: (event) => release(event.currentTarget, event.pointerId, true),
|
||||
onPointerCancel: (event) => release(event.currentTarget, event.pointerId, false),
|
||||
}
|
||||
}, [decide])
|
||||
|
||||
// Leaving the page stops an exit before its decision is sent.
|
||||
useEffect(() => () => exit.current?.cancel(), [])
|
||||
|
||||
@@ -239,7 +313,7 @@ export function DiscoverPage() {
|
||||
<>
|
||||
<div ref={deckRef} className={styles.deck}>
|
||||
{deck.data.slice(0, DECK_DEPTH.length).map((quest, depth) => (
|
||||
<DeckCard key={quest.id} quest={quest} depth={depth} />
|
||||
<DeckCard key={quest.id} quest={quest} depth={depth} swipe={depth === 0 ? swipe : undefined} />
|
||||
))}
|
||||
</div>
|
||||
<div className={styles.actions}>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { stubAnimate, type FakeAnimation } from '../test/animate.ts'
|
||||
import { bump, fadeOut, isAbort, pass, promote, tryIt } from './motion.ts'
|
||||
import { bump, dragTransform, fadeOut, follow, isAbort, pass, promote, snapBack, tryIt, unfollow } from './motion.ts'
|
||||
|
||||
let animations: FakeAnimation[]
|
||||
|
||||
@@ -15,10 +15,11 @@ afterEach(() => {
|
||||
// card builds a deck card with the parts DeckCard marks.
|
||||
function card() {
|
||||
const article = document.createElement('article')
|
||||
article.innerHTML = '<span data-part="try-stamp"></span><span data-part="shade"></span>'
|
||||
article.innerHTML = '<span data-part="try-stamp"></span><span data-part="pass-stamp"></span><span data-part="shade"></span>'
|
||||
return {
|
||||
article,
|
||||
stamp: article.querySelector('[data-part="try-stamp"]')!,
|
||||
stamp: article.querySelector<HTMLElement>('[data-part="try-stamp"]')!,
|
||||
passStamp: article.querySelector<HTMLElement>('[data-part="pass-stamp"]')!,
|
||||
shade: article.querySelector('[data-part="shade"]')!,
|
||||
}
|
||||
}
|
||||
@@ -169,8 +170,52 @@ describe('motion', () => {
|
||||
expect(animations.map((a) => a.playState)).toEqual(['idle', 'idle'])
|
||||
})
|
||||
|
||||
it('drags: translate(dx, dy·0.3) rotate(dx/18 deg)', () => {
|
||||
expect(dragTransform(90, 20)).toBe('translate(90px,6px) rotate(5deg)')
|
||||
expect(dragTransform(-36, -10)).toBe('translate(-36px,-3px) rotate(-2deg)')
|
||||
})
|
||||
|
||||
it.each([
|
||||
[50, '0.5', '0'],
|
||||
[-50, '0', '0.5'],
|
||||
[160, '1', '0'],
|
||||
[-160, '0', '1'],
|
||||
[0, '0', '0'],
|
||||
])('follows a drag of %i px with the stamps at Try it! %s, Pass %s', (dx, tryOpacity, passOpacity) => {
|
||||
const { article, stamp, passStamp } = card()
|
||||
expect(follow(article, dx, 0)).toBe(dragTransform(dx, 0))
|
||||
expect(article.style.transform).toBe(dragTransform(dx, 0))
|
||||
expect(stamp.style.opacity).toBe(tryOpacity)
|
||||
expect(passStamp.style.opacity).toBe(passOpacity)
|
||||
expect(animations).toEqual([])
|
||||
})
|
||||
|
||||
it('unfollows at once, back to the stylesheet', () => {
|
||||
const { article, stamp, passStamp } = card()
|
||||
follow(article, -80, 12)
|
||||
unfollow(article)
|
||||
expect(article.getAttribute('style')).toBe('')
|
||||
expect(stamp.getAttribute('style')).toBe('')
|
||||
expect(passStamp.getAttribute('style')).toBe('')
|
||||
expect(animations).toEqual([])
|
||||
})
|
||||
|
||||
it('snaps back from the drag transform to rest, 420 ms spring, and hides the stamps', () => {
|
||||
const { article, stamp, passStamp } = card()
|
||||
const from = follow(article, 70, 30)
|
||||
snapBack(article, from)
|
||||
expect(article.style.transform).toBe('')
|
||||
expect(stamp.style.opacity).toBe('')
|
||||
expect(passStamp.style.opacity).toBe('')
|
||||
expect(animations).toHaveLength(1)
|
||||
expect(animations[0]!.target).toBe(article)
|
||||
expect(animations[0]!.keyframes).toEqual([{ transform: 'translate(70px,9px) rotate(3.888888888888889deg)' }, { transform: 'translate(0px,0px) rotate(0deg)' }])
|
||||
expect(animations[0]!.options).toEqual({ duration: 420, easing: 'cubic-bezier(.34,1.4,.64,1)' })
|
||||
})
|
||||
|
||||
it('fails fast on a card without its parts', () => {
|
||||
expect(() => tryIt(document.createElement('article'))).toThrow('deck card has no try-stamp')
|
||||
expect(() => pass(document.createElement('article'))).toThrow('deck card has no shade')
|
||||
expect(() => follow(document.createElement('article'), 10, 0)).toThrow('deck card has no try-stamp')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// The deck's motion, from the handoff's Motion §2 (Try it), §3 (Pass),
|
||||
// §5 (deck advance) and §6 (reduced motion), with the Web Animations API.
|
||||
// The exits take the card's starting transform so the swipe gesture can
|
||||
// throw a dragged card from where it was let go.
|
||||
// §4 (swipe), §5 (deck advance) and §6 (reduced motion), with the Web
|
||||
// Animations API. The exits take the card's starting transform so the swipe
|
||||
// gesture can throw a dragged card from where it was let go.
|
||||
|
||||
const SPRING = 'cubic-bezier(.34,1.4,.64,1)'
|
||||
const THROW = 'cubic-bezier(.55,0,.8,.4)'
|
||||
@@ -93,6 +93,38 @@ export function pass(card: HTMLElement, from: string = REST): Exit {
|
||||
return exit.done(finished)
|
||||
}
|
||||
|
||||
// dragTransform is the top card's transform dragged dx, dy from where the
|
||||
// pointer went down.
|
||||
export function dragTransform(dx: number, dy: number): string {
|
||||
return `translate(${dx}px,${dy * 0.3}px) rotate(${dx / 18}deg)`
|
||||
}
|
||||
|
||||
// follow moves a dragged card to its drag transform and shows each stamp as
|
||||
// far as the drag has gone toward its side, fully at 100 px. It returns the
|
||||
// transform, for the exit or snap-back the release starts.
|
||||
export function follow(card: HTMLElement, dx: number, dy: number): string {
|
||||
const transform = dragTransform(dx, dy)
|
||||
card.style.transform = transform
|
||||
part(card, 'try-stamp').style.opacity = String(clamp(dx / 100))
|
||||
part(card, 'pass-stamp').style.opacity = String(clamp(-dx / 100))
|
||||
return transform
|
||||
}
|
||||
|
||||
// unfollow puts a dragged card and its stamps back where the stylesheet
|
||||
// places them, at once.
|
||||
export function unfollow(card: HTMLElement) {
|
||||
card.style.removeProperty('transform')
|
||||
part(card, 'try-stamp').style.removeProperty('opacity')
|
||||
part(card, 'pass-stamp').style.removeProperty('opacity')
|
||||
}
|
||||
|
||||
// snapBack springs a card let go short of a decision back to rest from its
|
||||
// drag transform, and hides its stamps.
|
||||
export function snapBack(card: HTMLElement, from: string): Animation {
|
||||
unfollow(card)
|
||||
return card.animate([{ transform: from }, { transform: REST }], { duration: 420, easing: SPRING })
|
||||
}
|
||||
|
||||
// fadeOut is both exits under prefers-reduced-motion: reduce.
|
||||
export function fadeOut(card: HTMLElement): Exit {
|
||||
const exit = recorder()
|
||||
@@ -110,6 +142,10 @@ export function promote(cards: HTMLElement[]): Animation[] {
|
||||
)
|
||||
}
|
||||
|
||||
function clamp(value: number): number {
|
||||
return Math.min(1, Math.max(0, value))
|
||||
}
|
||||
|
||||
// part is the card's element marked data-part="name", which DeckCard renders.
|
||||
function part(card: HTMLElement, name: string): HTMLElement {
|
||||
const element = card.querySelector<HTMLElement>(`[data-part="${name}"]`)
|
||||
|
||||
Reference in New Issue
Block a user