Skip to content
Source
Sign inSign up
samwillis/one-million-boxes
Open History to see the last commit

useMoveCounterShake.ts

21 lines794 Bytes

1import { useEffect, useRef } from "react"
2​
3/** Shake only the move display, keeping the pencil's drawing hotspot stationary. */
4export function useMoveCounterShake(emptyMoveAttempts: number) {
5 const ref = useRef<HTMLDivElement>(null)
6​
7 useEffect(() => {
8 if (emptyMoveAttempts === 0 || !ref.current) return
9 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
10​
11 // Cancelling the previous animation lets every blocked click get feedback,
12 // even when React batches repeated attempts with the same message.
13 const animation = ref.current.animate(
14 [0, -4, 4, -3, 3, 0].map((x) => ({ transform: `translateX(${x}px)` })),
15 { duration: 280, easing: "ease-out" },
16 )
17 return () => animation.cancel()
18 }, [emptyMoveAttempts])
19​
20 return ref