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

edge-picker.ts

67 lines2.5 KB

1import { H, W, coordsToEdgeId } from "../../shared/edge-math"
2​
3/**
4 * Detect if the current device supports touch
5 */
6export function isTouchDevice(): boolean {
7 return (
8 `ontouchstart` in window ||
9 navigator.maxTouchPoints > 0 ||
10 // @ts-expect-error msMaxTouchPoints is IE-specific
11 navigator.msMaxTouchPoints > 0
12 )
14​
15/**
16 * Find the nearest edge to a world coordinate.
17 * Returns the edge ID if one is close enough, or null otherwise.
18 *
19 * Only picks edges if zoomed in enough.
20 * Touch devices have a larger hit radius and lower minimum zoom requirement.
21 *
22 * @param worldX - X coordinate in world space
23 * @param worldY - Y coordinate in world space
24 * @param scale - Pixels per grid cell (zoom * DOT_SPACING)
25 * @param isTouch - Whether this is a touch interaction (defaults to isTouchDevice())
26 */
27export function findNearestEdge(
28 worldX: number,
29 worldY: number,
30 scale: number,
31 isTouch?: boolean,
32): number | null {
33 // Default to device detection if not specified
34 const touchMode = isTouch ?? isTouchDevice()
35​
36 // Minimum scale (pixels per cell) for edge picking
37 // Touch devices need lower threshold for easier selection
38 const minScale = touchMode ? 12 : 15
39 if (![worldX, worldY, scale].every(Number.isFinite) || scale < minScale) return null
40​
41 // Larger hit radius for touch to accommodate finger imprecision
42 const hitRadius = touchMode ? 0.4 : 0.25
43​
44 const clamp = (value: number, min: number, max: number) => Math.max(min, Math.min(max, value))
45 const horizontalX = clamp(Math.floor(worldX), 0, W - 1)
46 const horizontalY = clamp(Math.round(worldY), 0, H)
47 const verticalX = clamp(Math.round(worldX), 0, W)
48 const verticalY = clamp(Math.floor(worldY), 0, H - 1)
49​
50 // Measure distance to each full segment, including its endpoints. Clamping
51 // the projection gives round hit caps without selecting beyond the board.
52 const horizontalDistance = Math.hypot(
53 worldX - clamp(worldX, horizontalX, horizontalX + 1),
54 worldY - horizontalY,
55 )
56 const verticalDistance = Math.hypot(
57 worldX - verticalX,
58 worldY - clamp(worldY, verticalY, verticalY + 1),
59 )
60 if (Math.min(horizontalDistance, verticalDistance) > hitRadius) return null
61​
62 // At intersections, pick the closer line instead of favoring a horizontal
63 // edge's overlapping hit area. Exact ties consistently select horizontal.
64 return horizontalDistance <= verticalDistance
65 ? coordsToEdgeId(horizontalX, horizontalY, true)
66 : coordsToEdgeId(verticalX, verticalY, false)