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

GameCanvas.tsx

840 lines25.8 KB

1import { useCallback, useEffect, useMemo, useRef, useState } from "react"
2import { useViewStateContext } from "../../hooks/useViewState"
3import { useGameState } from "../../hooks/useGameState"
4import { usePanZoom } from "../../hooks/usePanZoom"
5import { useQuota } from "../../contexts/quota-context"
6import {
7 getScale,
8 getVisibleBounds,
9 screenRectToWorldBounds,
10 screenToWorld,
11 worldToScreen,
12} from "../../lib/view-transform"
13import { H, W, edgeIdToCoords } from "../../../shared/edge-math"
14import { findNearestEdge } from "../../lib/edge-picker"
15import { getDebugConfig, subscribeDebugConfig } from "../../lib/debug-config"
16import { TouchFeedback, useTouchFeedback } from "../ui/TouchFeedback"
17import { TEAMS, TEAM_COLORS } from "../../../shared/teams"
18import { renderBoxes } from "./BoxRenderer"
19import { renderEdges } from "./EdgeRenderer"
20import { renderDots } from "./DotRenderer"
21import { DrawingCursor } from "./DrawingCursor"
22import type { DebugConfig } from "../../lib/debug-config"
23import "./GameCanvas.css"
24​
25const POP_DURATION = 800 // ms - should match CSS animation
26​
27// Match --color-bg so the board, overview bitmap, and surrounding UI agree.
28const BACKGROUND_COLOR = `#FAFAFA`
29​
30/**
31 * Trigger haptic feedback if available
32 */
33function triggerHapticFeedback(pattern: number | Array<number> = 10) {
34 if (`vibrate` in navigator) {
35 navigator.vibrate(pattern)
36 }
38​
39export function GameCanvas() {
40 const canvasRef = useRef<HTMLCanvasElement>(null)
41 const drawingEdgeRef = useRef<{ edgeId: number; progress: number } | null>(null)
42 const containerRef = useRef<HTMLDivElement>(null)
43 const { view, pan, zoomTo, canvasSize, setCanvasSize } = useViewStateContext()
44 const {
45 gameState,
46 boxBitmap,
47 pendingEdge,
48 placeEdge,
49 recentEvents,
50 version,
51 isLoading,
52 isReadyToRender,
53 notifyCanvasRendered,
54 isGameComplete,
55 } = useGameState()
56 const { setBonusPosition } = useQuota()
57 const [hoveredEdge, setHoveredEdge] = useState<number | null>(null)
58 const lastEdgeScreenPosRef = useRef<{ x: number; y: number } | null>(null)
59 const { ripples, addRipple } = useTouchFeedback()
60 const [debugConfig, setDebugConfig] = useState<DebugConfig>(getDebugConfig)
61​
62 const prevViewRef = useRef<typeof view | null>(null)
63 const prevCanvasSizeRef = useRef<typeof canvasSize | null>(null)
64 const prevHoveredEdgeRef = useRef<number | null>(null)
65 const prevPendingEdgeRef = useRef<number | null>(null)
66 const prevDebugConfigRef = useRef<DebugConfig | null>(null)
67 const lastProcessedEventIdRef = useRef<number>(-1)
68 const zoomRedrawTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
69 const lastZoomRedrawRef = useRef<number>(0)
70 const zoomSnapshotRef = useRef<HTMLCanvasElement | null>(null)
71 const hasDrawnRef = useRef(false)
72 const latestStateRef = useRef({
73 view,
74 canvasSize,
75 pendingEdge,
76 hoveredEdge,
77 debugConfig,
78 gameState,
79 boxBitmap,
80 })
81​
82 // Subscribe to debug config changes
83 useEffect(() => {
84 return subscribeDebugConfig(setDebugConfig)
85 }, [])
86​
87 // Track touch state for tap vs drag detection
88 const touchStartPos = useRef<{ x: number; y: number } | null>(null)
89 const touchMoved = useRef(false)
90​
91 // Track mouse state for click vs drag detection
92 const mouseStartPos = useRef<{ x: number; y: number } | null>(null)
93 const mouseMoved = useRef(false)
94​
95 // Handle resize
96 useEffect(() => {
97 const container = containerRef.current
98 if (!container) return
99​
100 const observer = new ResizeObserver((entries) => {
101 const { width, height } = entries[0].contentRect
102 setCanvasSize({ width, height })
103 })
104​
105 observer.observe(container)
106 return () => observer.disconnect()
107 }, [setCanvasSize])
108​
109 // Set up pan/zoom handlers
110 const { setCurrentZoom } = usePanZoom(containerRef, {
111 onPan: pan,
112 onZoom: (newZoom, focalX, focalY) => {
113 // Convert focal point from screen to world coordinates for proper zoom centering
114 if (focalX !== undefined && focalY !== undefined) {
115 const worldFocal = screenToWorld(focalX, focalY, view, canvasSize.width, canvasSize.height)
116 zoomTo(newZoom, worldFocal.x, worldFocal.y)
117 } else {
118 zoomTo(newZoom)
119 }
120 },
121 })
122​
123 // Sync external zoom changes with usePanZoom
124 useEffect(() => {
125 setCurrentZoom(view.zoom)
126 }, [view.zoom, setCurrentZoom])
127​
128 useEffect(() => {
129 latestStateRef.current = {
130 view,
131 canvasSize,
132 pendingEdge,
133 hoveredEdge,
134 debugConfig,
135 gameState,
136 boxBitmap,
137 }
138 }, [view, canvasSize, pendingEdge, hoveredEdge, debugConfig, gameState, boxBitmap])
139​
140 const setupCanvas = useCallback(
141 (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement) => {
142 const dpr = window.devicePixelRatio || 1
143 const targetWidth = Math.floor(canvasSize.width * dpr)
144 const targetHeight = Math.floor(canvasSize.height * dpr)
145 if (canvas.width !== targetWidth || canvas.height !== targetHeight) {
146 canvas.width = targetWidth
147 canvas.height = targetHeight
148 }
149 ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
150 ctx.imageSmoothingEnabled = true
151 ctx.imageSmoothingQuality = "high"
152 return dpr
153 },
154 [canvasSize.width, canvasSize.height],
155 )
156​
157 const renderLayers = useCallback(
158 (
159 ctx: CanvasRenderingContext2D,
160 renderState: {
161 view: typeof view
162 canvasSize: typeof canvasSize
163 pendingEdge: typeof pendingEdge
164 hoveredEdge: typeof hoveredEdge
165 debugConfig: typeof debugConfig
166 gameState: typeof gameState
167 boxBitmap: typeof boxBitmap
168 },
169 bounds?: { minX: number; minY: number; maxX: number; maxY: number },
170 clipRect?: { x: number; y: number; width: number; height: number },
171 ) => {
172 const {
173 view: renderView,
174 canvasSize: renderCanvasSize,
175 pendingEdge: renderPendingEdge,
176 hoveredEdge: renderHoveredEdge,
177 debugConfig: renderDebugConfig,
178 gameState: renderGameState,
179 boxBitmap: renderBoxBitmap,
180 } = renderState
181​
182 if (clipRect) {
183 ctx.save()
184 ctx.beginPath()
185 ctx.rect(clipRect.x, clipRect.y, clipRect.width, clipRect.height)
186 ctx.clip()
187 ctx.fillStyle = BACKGROUND_COLOR
188 ctx.fillRect(clipRect.x, clipRect.y, clipRect.width, clipRect.height)
189 } else {
190 ctx.fillStyle = BACKGROUND_COLOR
191 ctx.fillRect(0, 0, renderCanvasSize.width, renderCanvasSize.height)
192 }
193​
194 if (renderDebugConfig.renderShadedBoxes) {
195 renderBoxes(
196 ctx,
197 renderGameState,
198 renderView,
199 renderCanvasSize.width,
200 renderCanvasSize.height,
201 renderBoxBitmap,
202 )
203 }
204​
205 renderEdges(
206 ctx,
207 renderGameState,
208 renderView,
209 renderCanvasSize.width,
210 renderCanvasSize.height,
211 renderPendingEdge,
212 renderHoveredEdge,
213 renderDebugConfig.renderGridLines,
214 renderDebugConfig.renderDrawnLines,
215 bounds,
216 drawingEdgeRef.current,
217 )
218​
219 if (renderDebugConfig.renderDots) {
220 renderDots(ctx, renderView, renderCanvasSize.width, renderCanvasSize.height)
221 }
222​
223 if (clipRect) {
224 ctx.restore()
225 }
226 },
227 [],
228 )
229​
230 // Stroke frames repaint only a narrow strip around the active edge. Refs keep
231 // this animation out of React renders and preserve immediate Realtime updates.
232 const updateDrawingEdge = useCallback(
233 (edgeId: number | null, progress: number) => {
234 const previous = drawingEdgeRef.current
235 if (previous?.edgeId === edgeId && previous.progress === progress) return
236 drawingEdgeRef.current = edgeId === null ? null : { edgeId, progress }
237 const redrawEdgeId = edgeId ?? previous?.edgeId
238 const canvas = canvasRef.current
239 const ctx = canvas?.getContext("2d")
240 if (!canvas || !ctx || redrawEdgeId === undefined) return
241 const state = latestStateRef.current
242 const edge = edgeIdToCoords(redrawEdgeId)
243 const start = worldToScreen(
244 edge.x,
245 edge.y,
246 state.view,
247 state.canvasSize.width,
248 state.canvasSize.height,
249 )
250 const end = worldToScreen(
251 edge.x + (edge.horizontal ? 1 : 0),
252 edge.y + (edge.horizontal ? 0 : 1),
253 state.view,
254 state.canvasSize.width,
255 state.canvasSize.height,
256 )
257 const padding = Math.max(4, getScale(state.view) * 0.4)
258 const rect = {
259 x: start.x - padding,
260 y: start.y - padding,
261 width: end.x - start.x + padding * 2,
262 height: end.y - start.y + padding * 2,
263 }
264 const bounds = screenRectToWorldBounds(
265 state.view,
266 state.canvasSize.width,
267 state.canvasSize.height,
268 rect.x,
269 rect.y,
270 rect.width,
271 rect.height,
272 )
273 setupCanvas(ctx, canvas)
274 renderLayers(ctx, state, bounds, rect)
275 },
276 [renderLayers, setupCanvas],
277 )
278​
279 const performFullRedraw = useCallback(() => {
280 const canvas = canvasRef.current
281 if (!canvas || canvasSize.width === 0) return
282​
283 const ctx = canvas.getContext(`2d`)
284 if (!ctx) return
285​
286 const renderState = latestStateRef.current
287 if (renderState.canvasSize.width === 0) return
288 setupCanvas(ctx, canvas)
289 renderLayers(ctx, renderState)
290 }, [canvasSize.height, canvasSize.width, renderLayers, setupCanvas])
291​
292 const captureZoomSnapshot = useCallback(() => {
293 const canvas = canvasRef.current
294 if (!canvas) return
295​
296 const snapshot = zoomSnapshotRef.current ?? document.createElement(`canvas`)
297 zoomSnapshotRef.current = snapshot
298 if (snapshot.width !== canvas.width || snapshot.height !== canvas.height) {
299 snapshot.width = canvas.width
300 snapshot.height = canvas.height
301 }
302 const snapshotCtx = snapshot.getContext(`2d`)
303 if (!snapshotCtx) return
304 snapshotCtx.setTransform(1, 0, 0, 1, 0, 0)
305 snapshotCtx.drawImage(canvas, 0, 0)
306 }, [])
307​
308 const scheduleZoomRedraw = useCallback(() => {
309 const throttleMs = 1000 / 12
310 const now = Date.now()
311 const elapsed = now - lastZoomRedrawRef.current
312​
313 if (elapsed >= throttleMs) {
314 lastZoomRedrawRef.current = now
315 performFullRedraw()
316 return
317 }
318​
319 if (zoomRedrawTimerRef.current) return
320​
321 zoomRedrawTimerRef.current = setTimeout(() => {
322 zoomRedrawTimerRef.current = null
323 lastZoomRedrawRef.current = Date.now()
324 performFullRedraw()
325 }, throttleMs - elapsed)
326 }, [performFullRedraw])
327​
328 useEffect(() => {
329 return () => {
330 if (zoomRedrawTimerRef.current) {
331 clearTimeout(zoomRedrawTimerRef.current)
332 zoomRedrawTimerRef.current = null
333 }
334 }
335 }, [])
336​
337 useEffect(() => {
338 const canvas = canvasRef.current
339 if (!canvas || canvasSize.width === 0) return
340​
341 const ctx = canvas.getContext(`2d`)
342 if (!ctx) return
343​
344 const dpr = setupCanvas(ctx, canvas)
345 const renderState = {
346 view,
347 canvasSize,
348 pendingEdge,
349 hoveredEdge,
350 debugConfig,
351 gameState,
352 boxBitmap,
353 }
354 latestStateRef.current = renderState
355 if (isLoading && !isReadyToRender) {
356 return
357 }
358​
359 if (isLoading && isReadyToRender) {
360 performFullRedraw()
361 hasDrawnRef.current = true
362 notifyCanvasRendered()
363 prevViewRef.current = view
364 prevCanvasSizeRef.current = canvasSize
365 prevDebugConfigRef.current = debugConfig
366 prevHoveredEdgeRef.current = hoveredEdge
367 prevPendingEdgeRef.current = pendingEdge
368 return
369 }
370​
371 const prevView = prevViewRef.current
372 const prevCanvasSize = prevCanvasSizeRef.current
373 const prevDebugConfig = prevDebugConfigRef.current
374​
375 const debugChanged =
376 !prevDebugConfig ||
377 prevDebugConfig.renderShadedBoxes !== debugConfig.renderShadedBoxes ||
378 prevDebugConfig.renderDots !== debugConfig.renderDots ||
379 prevDebugConfig.renderGridLines !== debugConfig.renderGridLines ||
380 prevDebugConfig.renderDrawnLines !== debugConfig.renderDrawnLines
381​
382 const sizeChanged =
383 !prevCanvasSize ||
384 prevCanvasSize.width !== canvasSize.width ||
385 prevCanvasSize.height !== canvasSize.height
386​
387 if (!hasDrawnRef.current) {
388 performFullRedraw()
389 hasDrawnRef.current = true
390 prevViewRef.current = view
391 prevCanvasSizeRef.current = canvasSize
392 prevDebugConfigRef.current = debugConfig
393 prevHoveredEdgeRef.current = hoveredEdge
394 prevPendingEdgeRef.current = pendingEdge
395 return
396 }
397​
398 if (sizeChanged || debugChanged || !prevView) {
399 performFullRedraw()
400 prevViewRef.current = view
401 prevCanvasSizeRef.current = canvasSize
402 prevDebugConfigRef.current = debugConfig
403 prevHoveredEdgeRef.current = hoveredEdge
404 prevPendingEdgeRef.current = pendingEdge
405 return
406 }
407​
408 const redrawScreenRect = (rect: { x: number; y: number; width: number; height: number }) => {
409 if (rect.width <= 0 || rect.height <= 0) return
410 const bounds = screenRectToWorldBounds(
411 view,
412 canvasSize.width,
413 canvasSize.height,
414 rect.x,
415 rect.y,
416 rect.width,
417 rect.height,
418 )
419 renderLayers(ctx, renderState, bounds, rect)
420 }
421​
422 const zoomChanged = prevView.zoom !== view.zoom
423 if (zoomChanged) {
424 captureZoomSnapshot()
425 const scaleRatio = getScale(view) / getScale(prevView)
426 const cx = canvasSize.width / 2
427 const cy = canvasSize.height / 2
428 const offsetX =
429 (cx - scaleRatio * cx + (prevView.centerX - view.centerX) * getScale(view)) * dpr
430 const offsetY =
431 (cy - scaleRatio * cy + (prevView.centerY - view.centerY) * getScale(view)) * dpr
432​
433 const snapshot = zoomSnapshotRef.current
434 if (snapshot) {
435 ctx.setTransform(scaleRatio, 0, 0, scaleRatio, offsetX, offsetY)
436 ctx.drawImage(snapshot, 0, 0)
437 ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
438 }
439​
440 const prevBounds = getVisibleBounds(prevView, canvasSize.width, canvasSize.height)
441 const prevTopLeft = worldToScreen(
442 prevBounds.minX,
443 prevBounds.minY,
444 view,
445 canvasSize.width,
446 canvasSize.height,
447 )
448 const prevBottomRight = worldToScreen(
449 prevBounds.maxX,
450 prevBounds.maxY,
451 view,
452 canvasSize.width,
453 canvasSize.height,
454 )
455​
456 const rectLeft = Math.min(prevTopLeft.x, prevBottomRight.x)
457 const rectRight = Math.max(prevTopLeft.x, prevBottomRight.x)
458 const rectTop = Math.min(prevTopLeft.y, prevBottomRight.y)
459 const rectBottom = Math.max(prevTopLeft.y, prevBottomRight.y)
460​
461 if (rectLeft > 0) {
462 redrawScreenRect({
463 x: 0,
464 y: 0,
465 width: rectLeft,
466 height: canvasSize.height,
467 })
468 }
469 if (rectRight < canvasSize.width) {
470 redrawScreenRect({
471 x: rectRight,
472 y: 0,
473 width: canvasSize.width - rectRight,
474 height: canvasSize.height,
475 })
476 }
477 if (rectTop > 0) {
478 redrawScreenRect({
479 x: 0,
480 y: 0,
481 width: canvasSize.width,
482 height: rectTop,
483 })
484 }
485 if (rectBottom < canvasSize.height) {
486 redrawScreenRect({
487 x: 0,
488 y: rectBottom,
489 width: canvasSize.width,
490 height: canvasSize.height - rectBottom,
491 })
492 }
493​
494 scheduleZoomRedraw()
495 prevViewRef.current = view
496 prevCanvasSizeRef.current = canvasSize
497 prevDebugConfigRef.current = debugConfig
498 prevHoveredEdgeRef.current = hoveredEdge
499 prevPendingEdgeRef.current = pendingEdge
500 return
501 }
502​
503 const scale = getScale(view)
504 const deltaX = (prevView.centerX - view.centerX) * scale
505 const deltaY = (prevView.centerY - view.centerY) * scale
506 const centerChanged = deltaX !== 0 || deltaY !== 0
507​
508 if (centerChanged) {
509 if (Math.abs(deltaX) >= canvasSize.width || Math.abs(deltaY) >= canvasSize.height) {
510 performFullRedraw()
511 } else {
512 ctx.setTransform(1, 0, 0, 1, 0, 0)
513 ctx.drawImage(canvas, Math.round(deltaX * dpr), Math.round(deltaY * dpr))
514 ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
515​
516 if (deltaX > 0) {
517 redrawScreenRect({
518 x: 0,
519 y: 0,
520 width: deltaX,
521 height: canvasSize.height,
522 })
523 } else if (deltaX < 0) {
524 redrawScreenRect({
525 x: canvasSize.width + deltaX,
526 y: 0,
527 width: -deltaX,
528 height: canvasSize.height,
529 })
530 }
531​
532 if (deltaY > 0) {
533 redrawScreenRect({
534 x: 0,
535 y: 0,
536 width: canvasSize.width,
537 height: deltaY,
538 })
539 } else if (deltaY < 0) {
540 redrawScreenRect({
541 x: 0,
542 y: canvasSize.height + deltaY,
543 width: canvasSize.width,
544 height: -deltaY,
545 })
546 }
547 }
548 }
549​
550 const edgeIdsToRedraw = new Set<number>()
551 const prevPending = prevPendingEdgeRef.current
552 const prevHovered = prevHoveredEdgeRef.current
553​
554 if (prevPending !== pendingEdge) {
555 if (prevPending !== null) edgeIdsToRedraw.add(prevPending)
556 if (pendingEdge !== null) edgeIdsToRedraw.add(pendingEdge)
557 }
558​
559 if (prevHovered !== hoveredEdge) {
560 if (prevHovered !== null) edgeIdsToRedraw.add(prevHovered)
561 if (hoveredEdge !== null) edgeIdsToRedraw.add(hoveredEdge)
562 }
563​
564 for (const event of recentEvents) {
565 if (event.id > lastProcessedEventIdRef.current) {
566 edgeIdsToRedraw.add(event.edgeId)
567 lastProcessedEventIdRef.current = Math.max(lastProcessedEventIdRef.current, event.id)
568 }
569 }
570​
571 if (edgeIdsToRedraw.size > 0) {
572 const lineWidth = Math.max(0.5, scale * 0.1)
573 const padding = Math.max(2, lineWidth * 2)
574​
575 for (const edgeId of edgeIdsToRedraw) {
576 const coords = edgeIdToCoords(edgeId)
577 const minX = Math.max(0, coords.x - (coords.horizontal ? 0 : 1))
578 const maxX = Math.min(W, coords.x + 1)
579 const minY = Math.max(0, coords.y - (coords.horizontal ? 1 : 0))
580 const maxY = Math.min(H, coords.y + 1)
581​
582 const topLeft = worldToScreen(minX, minY, view, canvasSize.width, canvasSize.height)
583 const bottomRight = worldToScreen(maxX, maxY, view, canvasSize.width, canvasSize.height)
584​
585 const x = Math.min(topLeft.x, bottomRight.x) - padding
586 const y = Math.min(topLeft.y, bottomRight.y) - padding
587 const width = Math.abs(bottomRight.x - topLeft.x) + padding * 2
588 const height = Math.abs(bottomRight.y - topLeft.y) + padding * 2
589​
590 const clippedX = Math.max(0, x)
591 const clippedY = Math.max(0, y)
592 const clippedWidth = Math.min(canvasSize.width - clippedX, width)
593 const clippedHeight = Math.min(canvasSize.height - clippedY, height)
594​
595 redrawScreenRect({
596 x: clippedX,
597 y: clippedY,
598 width: clippedWidth,
599 height: clippedHeight,
600 })
601 }
602 }
603​
604 prevViewRef.current = view
605 prevCanvasSizeRef.current = canvasSize
606 prevDebugConfigRef.current = debugConfig
607 prevHoveredEdgeRef.current = hoveredEdge
608 prevPendingEdgeRef.current = pendingEdge
609 }, [
610 boxBitmap,
611 canvasSize,
612 captureZoomSnapshot,
613 debugConfig,
614 gameState,
615 hoveredEdge,
616 pendingEdge,
617 performFullRedraw,
618 recentEvents,
619 renderLayers,
620 scheduleZoomRedraw,
621 setupCanvas,
622 view,
623 version,
624 ])
625​
626 // Calculate pops for other players' moves in viewport
627 const canvasPops = useMemo(() => {
628 const now = Date.now()
629​
630 return recentEvents
631 .filter((e) => !e.isLocal && now - e.timestamp < POP_DURATION)
632 .map((event) => {
633 const coords = edgeIdToCoords(event.edgeId)
634 // Get edge center position in world coordinates
635 const worldX = coords.horizontal ? coords.x + 0.5 : coords.x
636 const worldY = coords.horizontal ? coords.y : coords.y + 0.5
637​
638 // Convert to screen coordinates (relative to canvas)
639 const screenPos = worldToScreen(worldX, worldY, view, canvasSize.width, canvasSize.height)
640​
641 // Check if in viewport (with some margin for the pop animation)
642 // Container has overflow:hidden so pops outside will be clipped
643 const margin = 50
644 if (
645 screenPos.x < -margin ||
646 screenPos.x > canvasSize.width + margin ||
647 screenPos.y < -margin ||
648 screenPos.y > canvasSize.height + margin
649 ) {
650 return null
651 }
652​
653 // Get team color
654 const teamName = TEAMS[event.teamId]
655 const color = TEAM_COLORS[teamName].primary
656​
657 return {
658 key: `${event.id}`,
659 x: screenPos.x,
660 y: screenPos.y,
661 color,
662 age: now - event.timestamp,
663 }
664 })
665 .filter((pop): pop is NonNullable<typeof pop> => pop !== null)
666 }, [recentEvents, view, canvasSize])
667​
668 // Handle mouse down - track position for click vs drag detection
669 const handleMouseDown = useCallback((e: React.MouseEvent) => {
670 mouseStartPos.current = { x: e.clientX, y: e.clientY }
671 mouseMoved.current = false
672 }, [])
673​
674 // Handle mouse move for edge hover and drag detection
675 const handleMouseMove = useCallback(
676 (e: React.MouseEvent) => {
677 // Check if mouse has moved significantly during a drag (button pressed)
678 // Use a small threshold to avoid triggering on tiny movements
679 if (mouseStartPos.current && e.buttons > 0) {
680 const dx = e.clientX - mouseStartPos.current.x
681 const dy = e.clientY - mouseStartPos.current.y
682 const distance = Math.sqrt(dx * dx + dy * dy)
683 if (distance > 5) {
684 mouseMoved.current = true
685 }
686 }
687​
688 // Disable hover when game is complete
689 if (isGameComplete) {
690 setHoveredEdge(null)
691 return
692 }
693​
694 if (!canvasRef.current) return
695​
696 const rect = canvasRef.current.getBoundingClientRect()
697 const x = e.clientX - rect.left
698 const y = e.clientY - rect.top
699​
700 const worldPos = screenToWorld(x, y, view, canvasSize.width, canvasSize.height)
701 const edgeId = findNearestEdge(worldPos.x, worldPos.y, getScale(view), false)
702​
703 setHoveredEdge(edgeId)
704​
705 // Track screen position for bonus toast
706 if (edgeId !== null) {
707 lastEdgeScreenPosRef.current = { x: e.clientX, y: e.clientY }
708 }
709 },
710 [view, canvasSize, isGameComplete],
711 )
712​
713 // Handle click to place edge
714 const handleClick = useCallback(
715 (e: React.MouseEvent<HTMLCanvasElement>) => {
716 // Skip if user was dragging (pan gesture)
717 if (mouseMoved.current) {
718 mouseStartPos.current = null
719 return
720 }
721 mouseStartPos.current = null
722​
723 // Disable drawing when game is complete
724 if (isGameComplete) return
725​
726 const rect = e.currentTarget.getBoundingClientRect()
727 const worldPos = screenToWorld(
728 e.clientX - rect.left,
729 e.clientY - rect.top,
730 view,
731 canvasSize.width,
732 canvasSize.height,
733 )
734 const edgeId = findNearestEdge(worldPos.x, worldPos.y, getScale(view), false)
735 if (edgeId !== null) {
736 setBonusPosition({ x: e.clientX, y: e.clientY })
737 placeEdge(edgeId)
738 triggerHapticFeedback(15)
739 }
740 },
741 [view, canvasSize, placeEdge, isGameComplete, setBonusPosition],
742 )
743​
744 // Handle touch start - track position for tap detection
745 const handleTouchStart = useCallback((e: React.TouchEvent) => {
746 if (e.touches.length === 1) {
747 const touch = e.touches[0]
748 touchStartPos.current = { x: touch.clientX, y: touch.clientY }
749 touchMoved.current = false
750 }
751 }, [])
752​
753 // Handle touch move - detect if user is dragging vs tapping
754 const handleTouchMove = useCallback(() => {
755 // usePanZoom handles the actual panning, we just track movement state
756 touchMoved.current = true
757 }, [])
758​
759 // Handle touch end - place edge on tap (not drag)
760 const handleTouchEnd = useCallback(
761 (e: React.TouchEvent) => {
762 // Disable drawing when game is complete
763 if (isGameComplete) {
764 touchStartPos.current = null
765 return
766 }
767​
768 // Only process if this was a tap (not a pan/zoom gesture)
769 if (touchMoved.current || !touchStartPos.current || e.touches.length > 0) {
770 touchStartPos.current = null
771 return
772 }
773​
774 const canvas = canvasRef.current
775 if (!canvas) return
776​
777 const rect = canvas.getBoundingClientRect()
778 const x = touchStartPos.current.x - rect.left
779 const y = touchStartPos.current.y - rect.top
780​
781 const worldPos = screenToWorld(x, y, view, canvasSize.width, canvasSize.height)
782 const edgeId = findNearestEdge(worldPos.x, worldPos.y, getScale(view), true)
783​
784 if (edgeId !== null) {
785 // Add visual feedback
786 addRipple(x, y)
787 // Haptic feedback
788 triggerHapticFeedback(15)
789 // Set bonus position for toast (use client coordinates)
790 setBonusPosition({
791 x: touchStartPos.current.x,
792 y: touchStartPos.current.y,
793 })
794 // Place the edge
795 placeEdge(edgeId)
796 }
797​
798 touchStartPos.current = null
799 },
800 [view, canvasSize, placeEdge, addRipple, isGameComplete, setBonusPosition],
801 )
802​
803 return (
804 <div ref={containerRef} className="game-canvas-container">
805 <canvas
806 ref={canvasRef}
807 className="game-canvas"
808 data-testid="game-canvas"
809 style={{ width: canvasSize.width, height: canvasSize.height }}
810 onMouseDown={handleMouseDown}
811 onMouseMove={handleMouseMove}
812 onMouseLeave={() => setHoveredEdge(null)}
813 onClick={handleClick}
814 onTouchStart={handleTouchStart}
815 onTouchMove={handleTouchMove}
816 onTouchEnd={handleTouchEnd}
817 />
818 <TouchFeedback ripples={ripples} />
819 <DrawingCursor
820 containerRef={containerRef}
821 disabled={isLoading || isGameComplete}
822 pendingEdge={pendingEdge}
823 onStrokeFrame={updateDrawingEdge}
824 />
825 {/* Pop animations for other players' moves */}
826 {canvasPops.map((pop) => (
827 <div
828 key={pop.key}
829 className="game-canvas-pop"
830 style={{
831 left: pop.x,
832 top: pop.y,
833 backgroundColor: pop.color,
834 animationDelay: `-${pop.age}ms`,
835 }}
836 />
837 ))}
838 </div>
839 )