All files / web/src/components/toys/euclid/interaction useToolInteraction.ts

0% Statements 0/770
0% Branches 0/1
0% Functions 0/1
0% Lines 0/770

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
import { useEffect, useCallback } from 'react'
import type {
  ConstructionState,
  EuclidViewportState,
  ExtendPhase,
  IntersectionCandidate,
  ConstructionElement,
  ExpectedAction,
} from '../types'
import type { ToolPhaseManager } from './useToolPhaseManager'
import { getPoint } from '../engine/constructionState'
import { MACRO_REGISTRY, wouldViolateDistinctness } from '../engine/macros'
import { screenToWorld2D, worldToScreen2D } from '../../shared/coordinateConversions'
import { hitTestPoints, hitTestIntersectionCandidates, hitTestAlongRulerEdge } from './hitTesting'

/** Sweep threshold: ~350 degrees → commit circle */
const SWEEP_THRESHOLD = 2 * Math.PI - 0.26

interface UseToolInteractionOptions {
  canvasRef: React.RefObject<HTMLCanvasElement | null>
  viewportRef: React.MutableRefObject<EuclidViewportState>
  constructionRef: React.MutableRefObject<ConstructionState>
  pointerWorldRef: React.MutableRefObject<{ x: number; y: number } | null>
  candidatesRef: React.MutableRefObject<IntersectionCandidate[]>
  toolPhases: ToolPhaseManager
  onCommitCircle: (centerId: string, radiusPointId: string) => void
  onCommitSegment: (fromId: string, toId: string) => void
  onMarkIntersection: (candidate: IntersectionCandidate) => void
  /** In guided mode, the current step's expected action. Used to constrain
   *  which points the compass/straightedge snaps to during drag. */
  expectedActionRef: React.MutableRefObject<ExpectedAction | null>
  onCommitMacro: (propId: number, inputPointIds: string[]) => void
  /** Called when the 'point' tool places a free point at a world coordinate. */
  onPlaceFreePoint?: (worldX: number, worldY: number) => void
  /** When true, all tool gestures are disabled (e.g. during given-setup mode in editor) */
  disabledRef?: React.MutableRefObject<boolean>
  /** When true, blocks construction tool gestures (but not intersection taps).
   *  Used in editor authoring mode when no citation is selected. */
  requiresCitationRef?: React.MutableRefObject<boolean>
  /** Called when a tool gesture is blocked because requiresCitationRef is true. */
  onToolBlocked?: () => void
  /** Extend tool preview position — updated on pointermove in 'extending' phase. */
  extendPreviewRef?: React.MutableRefObject<{ x: number; y: number } | null>
  /** Called when the extend tool commits (3rd click). */
  onCommitExtend?: (baseId: string, throughId: string, projX: number, projY: number) => void
}

function normalizeAngle(angle: number): number {
  while (angle > Math.PI) angle -= 2 * Math.PI
  while (angle <= -Math.PI) angle += 2 * Math.PI
  return angle
}

/** Angle threshold (radians) for extend mode detection — ~8° */
const EXTEND_ANGLE_THRESHOLD = (8 * Math.PI) / 180
/** Screen-px past the through-point to activate extend mode */
const EXTEND_PAST_THRESHOLD_PX = 15

interface ExtendCandidate {
  baseId: string
  throughId: string
  projX: number
  projY: number
}

/**
 * Detect whether the cursor has dragged past a point along an existing segment,
 * activating Post.2 "produce a finite straight line" as a sub-mode of the straightedge.
 *
 * Checks all segments that share `fromId` as an endpoint.  For each, computes the
 * angle between (fromId → cursor) and (fromId → otherEnd).  If the angle is small
 * (< 8°) and the cursor projects past the other end by > 15 screen-px, that's
 * an extend candidate.  The best-aligned candidate wins.
 */
function detectExtendMode(
  fromId: string,
  cursorWorld: { x: number; y: number },
  state: ConstructionState,
  viewport: EuclidViewportState,
  _w: number,
  _h: number,
  currentExtend: ExtendPhase
): ExtendCandidate | null {
  const fromPt = getPoint(state, fromId)
  if (!fromPt) return null

  const segments = state.elements.filter(
    (el): el is Extract<ConstructionElement, { kind: 'segment' }> =>
      el.kind === 'segment' && (el.fromId === fromId || el.toId === fromId)
  )

  let best: ExtendCandidate | null = null
  let bestAngle = EXTEND_ANGLE_THRESHOLD

  for (const seg of segments) {
    const otherId = seg.fromId === fromId ? seg.toId : seg.fromId
    const otherPt = getPoint(state, otherId)
    if (!otherPt) continue

    // Vector from fromPt to otherPt (the segment direction)
    const sdx = otherPt.x - fromPt.x
    const sdy = otherPt.y - fromPt.y
    const slen = Math.sqrt(sdx * sdx + sdy * sdy)
    if (slen < 0.001) continue

    // Vector from fromPt to cursor
    const cdx = cursorWorld.x - fromPt.x
    const cdy = cursorWorld.y - fromPt.y
    const clen = Math.sqrt(cdx * cdx + cdy * cdy)
    if (clen < 0.001) continue

    // Angle between the two vectors
    const dot = (sdx * cdx + sdy * cdy) / (slen * clen)
    const angle = Math.acos(Math.min(1, Math.max(-1, dot)))
    if (angle >= bestAngle) continue

    // Project cursor onto the segment ray — how far past the other endpoint?
    const dirX = sdx / slen
    const dirY = sdy / slen
    const projDist = cdx * dirX + cdy * dirY // distance from fromPt along ray
    const pastDist = projDist - slen // how far past otherPt (in world units)
    const pastPx = pastDist * viewport.pixelsPerUnit

    if (pastPx < EXTEND_PAST_THRESHOLD_PX) continue

    // This is a valid candidate — project cursor onto the ray past otherPt
    const projX = otherPt.x + dirX * pastDist
    const projY = otherPt.y + dirY * pastDist

    best = { baseId: fromId, throughId: otherId, projX, projY }
    bestAngle = angle
  }

  // If currently extending, also accept the current target even if a slightly better one exists
  // (prevents flickering between overlapping segments)
  if (!best && currentExtend.tag === 'extending') {
    return null // hysteresis handled by caller
  }

  return best
}

/**
 * Single hook handling compass, straightedge, and intersection marking.
 * Registers on canvas with { capture: true } to intercept before pan/zoom.
 */
export function useToolInteraction({
  canvasRef,
  viewportRef,
  constructionRef,
  pointerWorldRef,
  candidatesRef,
  toolPhases,
  onCommitCircle,
  onCommitSegment,
  onMarkIntersection,
  expectedActionRef,
  onCommitMacro,
  onPlaceFreePoint,
  disabledRef,
  requiresCitationRef,
  onToolBlocked,
  extendPreviewRef,
  onCommitExtend,
}: UseToolInteractionOptions) {
  const getCanvasRect = useCallback(() => {
    return canvasRef.current?.getBoundingClientRect()
  }, [canvasRef])

  useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return

    // Destructure refs from manager for direct use in hot path
    const {
      compassPhaseRef,
      straightedgePhaseRef,
      extendPhaseRef,
      macroPhaseRef,
      snappedPointIdRef,
      activeToolRef,
      pointerCapturedRef,
      needsDrawRef,
    } = toolPhases

    function toWorld(sx: number, sy: number, cw: number, ch: number) {
      const v = viewportRef.current
      return screenToWorld2D(
        sx,
        sy,
        v.center.x,
        v.center.y,
        v.pixelsPerUnit,
        v.pixelsPerUnit,
        cw,
        ch
      )
    }

    function getCSSSize() {
      const dpr = window.devicePixelRatio || 1
      return {
        w: canvas!.width / dpr,
        h: canvas!.height / dpr,
      }
    }

    function requestDraw() {
      needsDrawRef.current = true
    }

    // ── Pointer event handlers ──

    function handlePointerDown(e: PointerEvent) {
      // Disable all tool gestures when disabled (e.g. given-setup mode)
      if (disabledRef?.current) return
      // Disable tool gestures when Move tool is active (its own handler takes over)
      if (activeToolRef.current === 'move') return

      const rect = getCanvasRect()
      if (!rect) return
      const sx = e.clientX - rect.left
      const sy = e.clientY - rect.top
      const { w, h } = getCSSSize()
      const world = toWorld(sx, sy, w, h)
      const isTouch = e.pointerType === 'touch'
      const state = constructionRef.current
      const viewport = viewportRef.current
      const tool = activeToolRef.current

      // Update pointer position
      pointerWorldRef.current = world

      // Hit test points
      const hitPt = hitTestPoints(sx, sy, state, viewport, w, h, isTouch)
      snappedPointIdRef.current = hitPt?.id ?? null

      // ── Intersection marking: tap near a candidate ──
      // In guided mode, only allow candidate taps during intersection steps.
      // Otherwise, accidental taps during compass/straightedge steps create
      // unwanted points from leftover candidates.
      const compass = compassPhaseRef.current
      const straightedge = straightedgePhaseRef.current
      const expected = expectedActionRef.current
      const allowCandidateTap = !expected || expected.type === 'intersection'
      if (allowCandidateTap && compass.tag === 'idle' && straightedge.tag === 'idle') {
        const hitCandidate = hitTestIntersectionCandidates(
          sx,
          sy,
          candidatesRef.current,
          viewport,
          w,
          h,
          isTouch
        )
        if (hitCandidate) {
          e.stopPropagation()
          pointerCapturedRef.current = true
          onMarkIntersection(hitCandidate)
          requestDraw()
          // Release capture immediately — it's a tap
          pointerCapturedRef.current = false
          return
        }
      }

      // Block construction tool gestures when citation is required (editor authoring mode)
      if (requiresCitationRef?.current) {
        onToolBlocked?.()
        return
      }

      // ── Point tool: place a free point at cursor position ──
      if (tool === 'point') {
        if (!hitPt) {
          e.stopPropagation()
          onPlaceFreePoint?.(world.x, world.y)
          requestDraw()
        }
        return
      }

      // ── Tool gestures ──
      if (!hitPt) {
        requestDraw()
        return
      }

      if (tool === 'compass') {
        if (compass.tag === 'idle') {
          // Set center
          e.stopPropagation()
          pointerCapturedRef.current = true
          compassPhaseRef.current = { tag: 'center-set', centerId: hitPt.id }
          toolPhases.notifyPhaseChange()
          requestDraw()
          return
        }
      }

      if (tool === 'straightedge') {
        if (straightedge.tag === 'idle') {
          // Set from point
          e.stopPropagation()
          pointerCapturedRef.current = true
          straightedgePhaseRef.current = { tag: 'from-set', fromId: hitPt.id }
          toolPhases.notifyPhaseChange()
          requestDraw()
          return
        }
      }

      if (tool === 'macro') {
        const macro = macroPhaseRef.current
        if (macro.tag === 'selecting') {
          // In guided mode, only accept the expected point at this selection index.
          // This prevents wrong-order selections (e.g. clicking B before A) from
          // triggering a heavyweight correction — instead the wrong point is silently
          // ignored, like compass radius filtering does for compass steps.
          if (expected?.type === 'macro' && expected.propId === macro.propId) {
            const selectionIndex = macro.selectedPointIds.length
            const expectedPointId = expected.inputPointIds[selectionIndex]
            if (expectedPointId && hitPt.id !== expectedPointId) {
              requestDraw()
              return
            }
          }

          // Reject selections that would violate the macro's distinctness constraints.
          // Each macro declares which input pairs must be distinct points — e.g. I.1
          // requires inputs [0,1] to differ (can't build a triangle on a zero-length
          // segment), while I.3 only requires [0,1] and [2,3] to differ (the two
          // segments can share endpoints like [A, E, A, F]).
          const macroDef = MACRO_REGISTRY[macro.propId]
          if (macroDef?.distinctInputPairs) {
            if (
              wouldViolateDistinctness(
                macroDef.distinctInputPairs,
                macro.selectedPointIds,
                hitPt.id
              )
            ) {
              requestDraw()
              return
            }
          }

          e.stopPropagation()

          const newSelected = [...macro.selectedPointIds, hitPt.id]
          if (newSelected.length >= macro.inputs.length) {
            // All inputs collected — commit
            toolPhases.setMacroPhase({ tag: 'idle' })
            pointerCapturedRef.current = false
            onCommitMacro(macro.propId, newSelected)
            toolPhases.notifyPhaseChange()
          } else {
            toolPhases.setMacroPhase({ ...macro, selectedPointIds: newSelected })
            toolPhases.notifyPhaseChange()
          }
          requestDraw()
          return
        }
      }
    }

    function handlePointerMove(e: PointerEvent) {
      if (disabledRef?.current) return
      const rect = getCanvasRect()
      if (!rect) return
      const sx = e.clientX - rect.left
      const sy = e.clientY - rect.top
      const { w, h } = getCSSSize()
      const world = toWorld(sx, sy, w, h)
      const isTouch = e.pointerType === 'touch'
      const state = constructionRef.current
      const viewport = viewportRef.current

      pointerWorldRef.current = world

      // Always update snap
      const hitPt = hitTestPoints(sx, sy, state, viewport, w, h, isTouch)
      snappedPointIdRef.current = hitPt?.id ?? null

      const compass = compassPhaseRef.current

      // ── Compass: center-set → check if we've reached another point (snap to radius) ──
      if (compass.tag === 'center-set') {
        if (hitPt && hitPt.id !== compass.centerId) {
          // In guided mode, only snap to the expected radius point
          const expected = expectedActionRef.current
          if (
            expected?.type === 'compass' &&
            expected.centerId === compass.centerId &&
            hitPt.id !== expected.radiusPointId
          ) {
            // Skip — not the expected radius point, user is dragging through
            requestDraw()
            return
          }

          // Snap to this point as radius point
          const center = getPoint(state, compass.centerId)
          if (center) {
            const dx = hitPt.x - center.x
            const dy = hitPt.y - center.y
            const radius = Math.sqrt(dx * dx + dy * dy)
            compassPhaseRef.current = {
              tag: 'radius-set',
              centerId: compass.centerId,
              radiusPointId: hitPt.id,
              radius,
              enterTime: performance.now(),
            }
            toolPhases.notifyPhaseChange()
          }
        }
        requestDraw()
        return
      }

      // ── Compass: radius-set → re-snap or transition to sweeping ──
      if (compass.tag === 'radius-set') {
        // If near a different point (not center), re-snap to it
        if (hitPt && hitPt.id !== compass.centerId) {
          if (hitPt.id !== compass.radiusPointId) {
            // In guided mode, only re-snap to the expected radius point
            const expected = expectedActionRef.current
            if (
              expected?.type === 'compass' &&
              expected.centerId === compass.centerId &&
              hitPt.id !== expected.radiusPointId
            ) {
              // Skip — not the expected radius point
              requestDraw()
              return
            }

            const center = getPoint(state, compass.centerId)
            if (center) {
              const dx = hitPt.x - center.x
              const dy = hitPt.y - center.y
              compassPhaseRef.current = {
                tag: 'radius-set',
                centerId: compass.centerId,
                radiusPointId: hitPt.id,
                radius: Math.sqrt(dx * dx + dy * dy),
                enterTime: performance.now(),
              }
              toolPhases.notifyPhaseChange()
            }
          }
          // Still on a point — don't start sweeping yet
          requestDraw()
          return
        }

        // Pointer left all points. If the user was just passing through
        // (< 150ms dwell), go back to center-set so they can keep dragging.
        const dwellTime = performance.now() - compass.enterTime
        if (dwellTime < 150) {
          compassPhaseRef.current = { tag: 'center-set', centerId: compass.centerId }
          toolPhases.notifyPhaseChange()
          requestDraw()
          return
        }

        // Dwelled long enough — the user settled on this point. Start sweeping.
        const center = getPoint(state, compass.centerId)
        const radiusPt = getPoint(state, compass.radiusPointId)
        if (center && radiusPt) {
          const startAngle = Math.atan2(radiusPt.y - center.y, radiusPt.x - center.x)
          const currentAngle = Math.atan2(world.y - center.y, world.x - center.x)
          compassPhaseRef.current = {
            tag: 'sweeping',
            centerId: compass.centerId,
            radiusPointId: compass.radiusPointId,
            radius: compass.radius,
            startAngle,
            prevAngle: currentAngle,
            cumulativeSweep: 0,
          }
          // Capture pointer so sweep continues even when cursor leaves canvas
          // (e.g. moves over proof-steps panel or outside the viewport)
          canvas!.setPointerCapture(e.pointerId)
          toolPhases.notifyPhaseChange()
        }
        requestDraw()
        return
      }

      // ── Compass: sweeping → accumulate angle ──
      if (compass.tag === 'sweeping') {
        const center = getPoint(state, compass.centerId)
        if (center) {
          const newAngle = Math.atan2(world.y - center.y, world.x - center.x)
          const delta = normalizeAngle(newAngle - compass.prevAngle)
          const newSweep = compass.cumulativeSweep + delta

          compassPhaseRef.current = {
            ...compass,
            prevAngle: newAngle,
            cumulativeSweep: newSweep,
          }

          // Check for completion
          if (Math.abs(newSweep) >= SWEEP_THRESHOLD) {
            // Release pointer capture acquired at sweep start
            try {
              canvas!.releasePointerCapture(e.pointerId)
            } catch {
              /* not captured */
            }
            onCommitCircle(compass.centerId, compass.radiusPointId)
            compassPhaseRef.current = { tag: 'idle' }
            pointerCapturedRef.current = false
            toolPhases.notifyPhaseChange()
          }
        }
        requestDraw()
        return
      }

      // ── Straightedge: from-set → snap to point closest to ruler edge + extend detection ──
      if (straightedgePhaseRef.current.tag === 'from-set') {
        const fromId = straightedgePhaseRef.current.fromId
        const from = getPoint(state, fromId)
        if (from) {
          const sf = worldToScreen2D(
            from.x,
            from.y,
            viewport.center.x,
            viewport.center.y,
            viewport.pixelsPerUnit,
            viewport.pixelsPerUnit,
            w,
            h
          )
          const edgeHit = hitTestAlongRulerEdge(
            sf.x,
            sf.y,
            sx,
            sy,
            fromId,
            state,
            viewport,
            w,
            h,
            isTouch
          )
          const prevSnapped = snappedPointIdRef.current
          snappedPointIdRef.current = edgeHit?.id ?? null
          if (snappedPointIdRef.current !== prevSnapped) {
            toolPhases.notifyPhaseChange()
          }

          // ── Extend detection (Post.2): drag along existing segment past its endpoint ──
          if (extendPreviewRef) {
            const ext = detectExtendMode(
              fromId,
              world,
              state,
              viewport,
              w,
              h,
              extendPhaseRef.current
            )
            if (ext) {
              if (
                extendPhaseRef.current.tag !== 'extending' ||
                extendPhaseRef.current.baseId !== ext.baseId ||
                extendPhaseRef.current.throughId !== ext.throughId
              ) {
                extendPhaseRef.current = {
                  tag: 'extending',
                  baseId: ext.baseId,
                  throughId: ext.throughId,
                }
                toolPhases.notifyPhaseChange()
              }
              extendPreviewRef.current = { x: ext.projX, y: ext.projY }
              // Clear snap — we're in extend mode, not targeting a point
              snappedPointIdRef.current = null
            } else if (extendPhaseRef.current.tag === 'extending') {
              // Hysteresis: only exit if cursor is pulled back 8px before the through-point
              const throughPt = getPoint(state, extendPhaseRef.current.throughId)
              if (throughPt) {
                const basePt = getPoint(state, extendPhaseRef.current.baseId)
                if (basePt) {
                  const dx = throughPt.x - basePt.x
                  const dy = throughPt.y - basePt.y
                  const len = Math.sqrt(dx * dx + dy * dy)
                  if (len > 0.001) {
                    const dirX = dx / len
                    const dirY = dy / len
                    const projOnRay = (world.x - basePt.x) * dirX + (world.y - basePt.y) * dirY
                    const throughDist = len
                    const hysteresisWorld = 8 / viewport.pixelsPerUnit
                    if (projOnRay < throughDist - hysteresisWorld) {
                      // Cursor pulled back — exit extend mode
                      extendPhaseRef.current = { tag: 'idle' }
                      extendPreviewRef.current = null
                      toolPhases.notifyPhaseChange()
                    } else {
                      // Still close to or past through-point — stay in extend, update preview
                      const t = Math.max(0, projOnRay - throughDist)
                      extendPreviewRef.current = {
                        x: throughPt.x + dirX * t,
                        y: throughPt.y + dirY * t,
                      }
                    }
                  }
                }
              }
            }
          }
        }
        requestDraw()
        return
      }

      requestDraw()
    }

    function handlePointerUp(e: PointerEvent) {
      if (disabledRef?.current) return
      const rect = getCanvasRect()
      if (!rect) return
      const sx = e.clientX - rect.left
      const sy = e.clientY - rect.top
      const { w, h } = getCSSSize()
      const isTouch = e.pointerType === 'touch'
      const state = constructionRef.current
      const viewport = viewportRef.current

      const compass = compassPhaseRef.current
      const straightedge = straightedgePhaseRef.current

      // ── Compass: cancel on pointer up if not completed ──
      if (compass.tag !== 'idle') {
        // Release pointer capture if we captured it during sweep
        try {
          canvas!.releasePointerCapture(e.pointerId)
        } catch {
          /* not captured */
        }
        compassPhaseRef.current = { tag: 'idle' }
        pointerCapturedRef.current = false
        toolPhases.notifyPhaseChange()
        requestDraw()
        return
      }

      // ── Straightedge: commit segment OR extend ──
      if (straightedge.tag === 'from-set') {
        // Check extend mode first — if extending, commit the extension
        if (extendPhaseRef.current.tag === 'extending' && extendPreviewRef) {
          const preview = extendPreviewRef.current
          if (preview) {
            onCommitExtend?.(
              extendPhaseRef.current.baseId,
              extendPhaseRef.current.throughId,
              preview.x,
              preview.y
            )
          }
          extendPhaseRef.current = { tag: 'idle' }
          extendPreviewRef.current = null
          straightedgePhaseRef.current = { tag: 'idle' }
          pointerCapturedRef.current = false
          toolPhases.notifyPhaseChange()
          requestDraw()
          return
        }

        // Normal straightedge: commit to point closest to ruler edge
        const from = getPoint(state, straightedge.fromId)
        if (from) {
          const sf = worldToScreen2D(
            from.x,
            from.y,
            viewport.center.x,
            viewport.center.y,
            viewport.pixelsPerUnit,
            viewport.pixelsPerUnit,
            w,
            h
          )
          const edgeHit = hitTestAlongRulerEdge(
            sf.x,
            sf.y,
            sx,
            sy,
            straightedge.fromId,
            state,
            viewport,
            w,
            h,
            isTouch
          )
          if (edgeHit) {
            onCommitSegment(straightedge.fromId, edgeHit.id)
          }
        }
        // Clear extend state in case it was partially set
        extendPhaseRef.current = { tag: 'idle' }
        if (extendPreviewRef) extendPreviewRef.current = null
        straightedgePhaseRef.current = { tag: 'idle' }
        pointerCapturedRef.current = false
        toolPhases.notifyPhaseChange()
        requestDraw()
        return
      }

      pointerCapturedRef.current = false
      // Only clear pointer on touch — mouse keeps position for idle tool overlay
      if (e.pointerType === 'touch') {
        pointerWorldRef.current = null
      }
      snappedPointIdRef.current = null
      requestDraw()
    }

    function handlePointerCancel(e: PointerEvent) {
      try {
        canvas!.releasePointerCapture(e.pointerId)
      } catch {
        /* not captured */
      }
      toolPhases.resetAll()
      if (extendPreviewRef) extendPreviewRef.current = null
      pointerWorldRef.current = null
      snappedPointIdRef.current = null
      toolPhases.notifyPhaseChange()
      requestDraw()
    }

    // Register with capture: true to intercept before pan/zoom
    canvas.addEventListener('pointerdown', handlePointerDown, { capture: true })
    canvas.addEventListener('pointermove', handlePointerMove, { capture: true })
    canvas.addEventListener('pointerup', handlePointerUp, { capture: true })
    canvas.addEventListener('pointercancel', handlePointerCancel, { capture: true })

    return () => {
      canvas.removeEventListener('pointerdown', handlePointerDown, { capture: true })
      canvas.removeEventListener('pointermove', handlePointerMove, { capture: true })
      canvas.removeEventListener('pointerup', handlePointerUp, { capture: true })
      canvas.removeEventListener('pointercancel', handlePointerCancel, { capture: true })
    }
  }, [
    canvasRef,
    viewportRef,
    constructionRef,
    pointerWorldRef,
    candidatesRef,
    toolPhases,
    onCommitCircle,
    onCommitSegment,
    onMarkIntersection,
    expectedActionRef,
    onCommitMacro,
    onPlaceFreePoint,
    getCanvasRect,
    disabledRef,
    requiresCitationRef,
    onToolBlocked,
    extendPreviewRef,
    onCommitExtend,
  ])
}