Open History to see the last commit
1import { useCallback, useEffect, useRef } from "react"
2import type { CSSProperties, RefObject } from "react"
3import { useTeam } from "../../contexts/team-context"
4import { TEAM_COLORS } from "../../../shared/teams"
5import { edgeIdToCoords } from "../../../shared/edge-math"
6import { useViewStateContext } from "../../hooks/useViewState"
7import { worldToScreen } from "../../lib/view-transform"
8import { MoveDial } from "../ui/MoveDial"
9import "./DrawingCursor.css"
10
11interface DrawingCursorProps {
12 containerRef: RefObject<HTMLDivElement | null>
13 disabled: boolean
14 pendingEdge: number | null
15 onStrokeFrame: (edgeId: number | null, progress: number) => void
16}
17
18/**
19 * A mouse-only pencil and move HUD. The tip is the real pointer hotspot;
20 * movement updates a compositor transform without rerendering the board.
21 * Touch and UI controls retain their normal input and quota display.
22 */
23export function DrawingCursor({
24 containerRef,
25 disabled,
26 pendingEdge,
27 onStrokeFrame,
28}: DrawingCursorProps) {
29 const cursorRef = useRef<HTMLDivElement>(null)
30 const pencilRef = useRef<SVGSVGElement>(null)
31 const pointerPosition = useRef({ x: 0, y: 0 })
32 const strokeAnimation = useRef<Animation | null>(null)
33 const strokeFrame = useRef<number | null>(null)
34 const strokeEdge = useRef<number | null>(null)
35 const lastStrokeEdge = useRef<number | null>(null)
36 const { view, canvasSize } = useViewStateContext()
37 const { team } = useTeam()
38 const teamColor = TEAM_COLORS[team].primary
39
40 const cancelStroke = useCallback(() => {
41 strokeAnimation.current?.cancel()
42 strokeAnimation.current = null
43 if (strokeFrame.current !== null) cancelAnimationFrame(strokeFrame.current)
44 strokeFrame.current = null
45 if (strokeEdge.current !== null) {
46 strokeEdge.current = null
47 onStrokeFrame(null, 1)
48 }
49 if (pencilRef.current) pencilRef.current.dataset.drawing = "false"
50 }, [onStrokeFrame])
51
52 useEffect(() => {
53 if (pendingEdge === null) {
54 lastStrokeEdge.current = null
55 return
56 }
57 if (lastStrokeEdge.current === pendingEdge) return
58 lastStrokeEdge.current = pendingEdge
59 const pencil = pencilRef.current
60 const cursor = cursorRef.current
61 if (!pencil || !cursor || disabled || cursor.dataset.visible !== "true") return
62 if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
63
64 // A pending edge exists only after the local move check succeeds. Trace its
65 // endpoints without delaying the write or animating the moves dial itself.
66 const edge = edgeIdToCoords(pendingEdge)
67 const start = worldToScreen(edge.x, edge.y, view, canvasSize.width, canvasSize.height)
68 const end = worldToScreen(
69 edge.x + (edge.horizontal ? 1 : 0),
70 edge.y + (edge.horizontal ? 0 : 1),
71 view,
72 canvasSize.width,
73 canvasSize.height,
74 )
75 const pointer = pointerPosition.current
76 const angle = cursor.style.getPropertyValue("--pencil-angle") || "0deg"
77 const transform = (point: { x: number; y: number }) =>
78 `translate(${point.x - pointer.x}px, ${point.y - pointer.y}px) rotate(${angle})`
79 cancelStroke()
80 pencil.dataset.drawing = "true"
81 const animation = pencil.animate(
82 [
83 { transform: transform(pointer), offset: 0, easing: "ease-out" },
84 { transform: transform(start), offset: 0.16 },
85 { transform: transform(end), offset: 0.76, easing: "ease-out" },
86 { transform: transform(pointer), offset: 1 },
87 ],
88 { duration: 260, easing: "linear" },
89 )
90 strokeAnimation.current = animation
91 strokeEdge.current = pendingEdge
92 onStrokeFrame(pendingEdge, 0)
93 const paintStroke = () => {
94 if (strokeAnimation.current !== animation) return
95 // The same animation clock drives the pencil and canvas reveal. Only the
96 // middle keyframe interval draws ink; approach and return leave it still.
97 const progress = animation.effect?.getComputedTiming().progress ?? 0
98 onStrokeFrame(pendingEdge, Math.max(0, Math.min(1, (progress - 0.16) / 0.6)))
99 strokeFrame.current = requestAnimationFrame(paintStroke)
100 }
101 strokeFrame.current = requestAnimationFrame(paintStroke)
102 animation.onfinish = () => {
103 if (strokeAnimation.current === animation) cancelStroke()
104 }
105 // Let a completed stroke finish even if Realtime confirms the edge early.
106 // Pointer movement, leaving the board and unmounting cancel it immediately.
107 }, [pendingEdge, view, canvasSize, disabled, cancelStroke, onStrokeFrame])
108
109 useEffect(() => {
110 const container = containerRef.current
111 const cursor = cursorRef.current
112 if (!container || !cursor || disabled) return
113
114 const mouseAvailable = window.matchMedia("(any-hover: hover) and (any-pointer: fine)")
115 let frame: number | null = null
116 let position = { x: 0, y: 0, width: 0, height: 0 }
117
118 const hide = () => {
119 cancelStroke()
120 cursor.dataset.visible = "false"
121 if (frame !== null) cancelAnimationFrame(frame)
122 frame = null
123 }
124
125 const paintPosition = () => {
126 frame = null
127 const { x, y, width, height } = position
128 pointerPosition.current = { x, y }
129 const left = x > width - 82
130 const above = y > height - 62
131 const pencilAngle = y < 48 ? (left ? 180 : 90) : left ? -90 : 0
132
133 cursor.style.transform = `translate3d(${x}px, ${y}px, 0)`
134 cursor.style.setProperty("--dial-x", left ? "-68px" : "22px")
135 cursor.style.setProperty("--dial-y", above ? "-54px" : "8px")
136 cursor.style.setProperty("--pencil-angle", `${pencilAngle}deg`)
137 if (cursor.dataset.visible !== "true") cursor.dataset.visible = "true"
138 }
139
140 const move = (event: PointerEvent) => {
141 cancelStroke()
142 if (event.pointerType !== "mouse" || !mouseAvailable.matches) {
143 hide()
144 return
145 }
146 const rect = container.getBoundingClientRect()
147 position = {
148 x: event.clientX - rect.left,
149 y: event.clientY - rect.top,
150 width: rect.width,
151 height: rect.height,
152 }
153 if (frame === null) frame = requestAnimationFrame(paintPosition)
154 }
155
156 // Native cursor suppression is a stable board capability, not a per-frame
157 // mutation. Toggling cursor CSS while moving can flash the OS cursor.
158 const syncMouseAvailability = () => {
159 if (mouseAvailable.matches) container.dataset.pencilEnabled = "true"
160 else delete container.dataset.pencilEnabled
161 hide()
162 }
163 syncMouseAvailability()
164
165 container.addEventListener("pointermove", move)
166 container.addEventListener("pointerleave", hide)
167 container.addEventListener("pointercancel", hide)
168 container.addEventListener("wheel", cancelStroke, { passive: true })
169 window.addEventListener("blur", hide)
170 document.addEventListener("visibilitychange", hide)
171 mouseAvailable.addEventListener("change", syncMouseAvailability)
172 return () => {
173 hide()
174 delete container.dataset.pencilEnabled
175 container.removeEventListener("pointermove", move)
176 container.removeEventListener("pointerleave", hide)
177 container.removeEventListener("pointercancel", hide)
178 container.removeEventListener("wheel", cancelStroke)
179 window.removeEventListener("blur", hide)
180 document.removeEventListener("visibilitychange", hide)
181 mouseAvailable.removeEventListener("change", syncMouseAvailability)
182 }
183 }, [containerRef, disabled, cancelStroke])
184
185 return (
186 <div
187 ref={cursorRef}
188 className="drawing-cursor"
189 data-testid="drawing-cursor"
190 data-visible="false"
191 aria-hidden="true"
192 style={{ "--pencil-color": teamColor } as CSSProperties}
193 >
194 {/* The pencil tip is (4,44), which CSS anchors exactly to the pointer. */}
195 <svg
196 ref={pencilRef}
197 className="drawing-cursor-pencil"
198 data-testid="drawing-pencil"
199 data-drawing="false"
200 viewBox="0 0 48 48"
201 fill="none"
202 >
203 <g stroke="#262626" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
204 <path d="M4 44 10 27 32 5 43 16 21 38Z" fill="#F0B375" />
205 <path d="M10 27 32 5 43 16 21 38Z" fill="var(--pencil-color)" />
206 <path d="m15 32 22-22" stroke="white" strokeOpacity="0.65" />
207 <path d="m32 5 2-2q2-2 4 0l7 7q2 2 0 4l-2 2Z" fill="#FFCCE5" />
208 <path d="m29 8 11 11 3-3L32 5Z" fill="#D7D8DB" />
209 <path d="m4 44 3-8 5 5Z" fill="#262626" />
210 </g>
211 </svg>
212
213 <MoveDial className="cursor-ammo" testId="cursor-ammo" />
214 </div>
215 )
216}