All files / web/src/components/worksheet-parsing BoundingBoxOverlay.tsx

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

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
'use client'

import type { ReactNode } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { css } from '../../../styled-system/css'
import type { ParsedProblem, BoundingBox } from '@/lib/worksheet-parsing'

interface BoundingBoxOverlayProps {
  /** The problems with bounding box data */
  problems: ParsedProblem[]
  /** Currently selected problem index (null if none) */
  selectedIndex: number | null
  /** Callback when a problem is clicked */
  onSelectProblem: (index: number | null) => void
  /** The image element to overlay on */
  imageRef: React.RefObject<HTMLImageElement | null>
  /** Show debug info (raw coordinates, image dimensions) */
  debug?: boolean
  /** Set of problem indices selected for re-parsing */
  selectedForReparse?: Set<number>
  /** Callback when a problem is toggled for re-parsing */
  onToggleReparse?: (index: number) => void
  /** Adjusted bounding boxes (overrides original when present) */
  adjustedBoxes?: Map<number, BoundingBox>
  /** Callback when a bounding box is adjusted */
  onAdjustBox?: (index: number, box: BoundingBox) => void
}

/** Handle positions for resize */
type HandlePosition = 'nw' | 'ne' | 'sw' | 'se' | 'n' | 's' | 'e' | 'w'

/** State for drag/resize operations */
interface DragState {
  type: 'move' | 'resize'
  index: number
  handle?: HandlePosition
  startX: number
  startY: number
  startBox: BoundingBox
}

/**
 * Calculate the actual rendered dimensions of an image with object-fit: contain
 * Returns the offset and size of the actual image content within the element
 */
function getContainedImageDimensions(img: HTMLImageElement): {
  offsetX: number
  offsetY: number
  width: number
  height: number
} {
  const naturalRatio = img.naturalWidth / img.naturalHeight
  const elementRatio = img.clientWidth / img.clientHeight

  let width: number
  let height: number

  if (naturalRatio > elementRatio) {
    // Image is wider than container - letterboxed top/bottom
    width = img.clientWidth
    height = img.clientWidth / naturalRatio
  } else {
    // Image is taller than container - letterboxed left/right
    height = img.clientHeight
    width = img.clientHeight * naturalRatio
  }

  const offsetX = (img.clientWidth - width) / 2
  const offsetY = (img.clientHeight - height) / 2

  return { offsetX, offsetY, width, height }
}

/**
 * BoundingBoxOverlay - SVG overlay that draws bounding boxes on worksheet images
 *
 * Uses normalized coordinates (0-1) from the parsing results to draw boxes
 * that highlight where each problem was detected on the worksheet.
 *
 * Features:
 * - All problems shown with semi-transparent boxes
 * - Selected problem highlighted with thicker border
 * - Click on a box to select that problem
 * - Automatically sizes to match the underlying image
 */
export function BoundingBoxOverlay({
  problems,
  selectedIndex,
  onSelectProblem,
  imageRef,
  debug = false,
  selectedForReparse = new Set(),
  onToggleReparse,
  adjustedBoxes = new Map(),
  onAdjustBox,
}: BoundingBoxOverlayProps): ReactNode {
  const [dimensions, setDimensions] = useState({
    elementWidth: 0,
    elementHeight: 0,
    // Actual image content dimensions (accounting for object-fit: contain)
    offsetX: 0,
    offsetY: 0,
    contentWidth: 0,
    contentHeight: 0,
    // Natural image dimensions (for debug display)
    naturalWidth: 0,
    naturalHeight: 0,
  })
  const containerRef = useRef<HTMLDivElement>(null)
  const svgRef = useRef<SVGSVGElement>(null)

  // Drag/resize state
  const [dragState, setDragState] = useState<DragState | null>(null)

  // Hover state for showing checkbox on hover
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null)

  // Update dimensions when image loads or resizes
  const updateDimensions = useCallback(() => {
    const img = imageRef.current
    if (img?.complete && img.naturalWidth > 0) {
      const contained = getContainedImageDimensions(img)
      setDimensions({
        elementWidth: img.clientWidth,
        elementHeight: img.clientHeight,
        offsetX: contained.offsetX,
        offsetY: contained.offsetY,
        contentWidth: contained.width,
        contentHeight: contained.height,
        naturalWidth: img.naturalWidth,
        naturalHeight: img.naturalHeight,
      })
    }
  }, [imageRef])

  // Watch for image load and resize
  useEffect(() => {
    const img = imageRef.current
    if (!img) return

    // Update on load
    if (img.complete) {
      updateDimensions()
    } else {
      img.addEventListener('load', updateDimensions)
    }

    // Update on resize using ResizeObserver
    const observer = new ResizeObserver(updateDimensions)
    observer.observe(img)

    return () => {
      img.removeEventListener('load', updateDimensions)
      observer.disconnect()
    }
  }, [imageRef, updateDimensions])

  // Convert normalized coordinates to pixel coordinates
  // Accounts for object-fit: contain letterboxing
  const toPixels = useCallback(
    (box: BoundingBox) => ({
      x: dimensions.offsetX + box.x * dimensions.contentWidth,
      y: dimensions.offsetY + box.y * dimensions.contentHeight,
      width: box.width * dimensions.contentWidth,
      height: box.height * dimensions.contentHeight,
    }),
    [dimensions]
  )

  // Convert pixel coordinates back to normalized (0-1)
  const toNormalized = useCallback(
    (pixelBox: { x: number; y: number; width: number; height: number }): BoundingBox => ({
      x: Math.max(0, Math.min(1, (pixelBox.x - dimensions.offsetX) / dimensions.contentWidth)),
      y: Math.max(0, Math.min(1, (pixelBox.y - dimensions.offsetY) / dimensions.contentHeight)),
      width: Math.max(0.02, Math.min(1, pixelBox.width / dimensions.contentWidth)),
      height: Math.max(0.02, Math.min(1, pixelBox.height / dimensions.contentHeight)),
    }),
    [dimensions]
  )

  // Get the effective bounding box (adjusted or original)
  const getEffectiveBox = useCallback(
    (index: number, problem: ParsedProblem): BoundingBox => {
      return adjustedBoxes.get(index) ?? problem.problemBoundingBox
    },
    [adjustedBoxes]
  )

  // Handle mouse down on box (start drag)
  const handleMouseDown = useCallback(
    (e: React.MouseEvent, index: number, handle?: HandlePosition) => {
      // Only allow drag/resize for boxes that are selected for reparse
      if (!selectedForReparse.has(index) || !onAdjustBox) return

      e.preventDefault()
      e.stopPropagation()

      const problem = problems[index]
      const box = getEffectiveBox(index, problem)

      setDragState({
        type: handle ? 'resize' : 'move',
        index,
        handle,
        startX: e.clientX,
        startY: e.clientY,
        startBox: { ...box },
      })
    },
    [selectedForReparse, onAdjustBox, problems, getEffectiveBox]
  )

  // Handle mouse move (drag/resize)
  const handleMouseMove = useCallback(
    (e: React.MouseEvent) => {
      if (!dragState || !onAdjustBox) return

      const dx = (e.clientX - dragState.startX) / dimensions.contentWidth
      const dy = (e.clientY - dragState.startY) / dimensions.contentHeight

      let newBox: BoundingBox

      if (dragState.type === 'move') {
        // Move the entire box
        newBox = {
          x: Math.max(0, Math.min(1 - dragState.startBox.width, dragState.startBox.x + dx)),
          y: Math.max(0, Math.min(1 - dragState.startBox.height, dragState.startBox.y + dy)),
          width: dragState.startBox.width,
          height: dragState.startBox.height,
        }
      } else {
        // Resize based on handle
        const { handle, startBox } = dragState
        let x = startBox.x
        let y = startBox.y
        let width = startBox.width
        let height = startBox.height

        // Adjust based on which handle is being dragged
        if (handle?.includes('w')) {
          const newX = Math.max(0, Math.min(startBox.x + startBox.width - 0.02, startBox.x + dx))
          width = startBox.width - (newX - startBox.x)
          x = newX
        }
        if (handle?.includes('e')) {
          width = Math.max(0.02, Math.min(1 - startBox.x, startBox.width + dx))
        }
        if (handle?.includes('n')) {
          const newY = Math.max(0, Math.min(startBox.y + startBox.height - 0.02, startBox.y + dy))
          height = startBox.height - (newY - startBox.y)
          y = newY
        }
        if (handle?.includes('s')) {
          height = Math.max(0.02, Math.min(1 - startBox.y, startBox.height + dy))
        }

        newBox = { x, y, width, height }
      }

      onAdjustBox(dragState.index, newBox)
    },
    [dragState, onAdjustBox, dimensions]
  )

  // Handle mouse up (end drag)
  const handleMouseUp = useCallback(() => {
    setDragState(null)
  }, [])

  // Add global mouse listeners when dragging
  useEffect(() => {
    if (!dragState) return

    const handleGlobalMouseMove = (e: MouseEvent) => {
      if (!dragState || !onAdjustBox) return

      const dx = (e.clientX - dragState.startX) / dimensions.contentWidth
      const dy = (e.clientY - dragState.startY) / dimensions.contentHeight

      let newBox: BoundingBox

      if (dragState.type === 'move') {
        newBox = {
          x: Math.max(0, Math.min(1 - dragState.startBox.width, dragState.startBox.x + dx)),
          y: Math.max(0, Math.min(1 - dragState.startBox.height, dragState.startBox.y + dy)),
          width: dragState.startBox.width,
          height: dragState.startBox.height,
        }
      } else {
        const { handle, startBox } = dragState
        let x = startBox.x
        let y = startBox.y
        let width = startBox.width
        let height = startBox.height

        if (handle?.includes('w')) {
          const newX = Math.max(0, Math.min(startBox.x + startBox.width - 0.02, startBox.x + dx))
          width = startBox.width - (newX - startBox.x)
          x = newX
        }
        if (handle?.includes('e')) {
          width = Math.max(0.02, Math.min(1 - startBox.x, startBox.width + dx))
        }
        if (handle?.includes('n')) {
          const newY = Math.max(0, Math.min(startBox.y + startBox.height - 0.02, startBox.y + dy))
          height = startBox.height - (newY - startBox.y)
          y = newY
        }
        if (handle?.includes('s')) {
          height = Math.max(0.02, Math.min(1 - startBox.y, startBox.height + dy))
        }

        newBox = { x, y, width, height }
      }

      onAdjustBox(dragState.index, newBox)
    }

    const handleGlobalMouseUp = () => {
      setDragState(null)
    }

    window.addEventListener('mousemove', handleGlobalMouseMove)
    window.addEventListener('mouseup', handleGlobalMouseUp)

    return () => {
      window.removeEventListener('mousemove', handleGlobalMouseMove)
      window.removeEventListener('mouseup', handleGlobalMouseUp)
    }
  }, [dragState, onAdjustBox, dimensions])

  // Don't render if we don't have valid dimensions
  if (dimensions.contentWidth === 0 || dimensions.contentHeight === 0) {
    return null
  }

  return (
    <div
      ref={containerRef}
      data-element="bounding-box-overlay"
      className={css({
        position: 'absolute',
        top: 0,
        left: 0,
        pointerEvents: 'none', // Allow clicks to pass through except on boxes
      })}
      style={{
        width: dimensions.elementWidth,
        height: dimensions.elementHeight,
      }}
    >
      <svg
        width={dimensions.elementWidth}
        height={dimensions.elementHeight}
        viewBox={`0 0 ${dimensions.elementWidth} ${dimensions.elementHeight}`}
        className={css({ display: 'block' })}
      >
        {/* Debug: show actual image content bounds */}
        {debug && (
          <rect
            x={dimensions.offsetX}
            y={dimensions.offsetY}
            width={dimensions.contentWidth}
            height={dimensions.contentHeight}
            fill="none"
            stroke="cyan"
            strokeWidth={2}
            strokeDasharray="8 4"
          />
        )}
        {/* Render boxes in two passes: unselected first, then selected on top */}
        {[false, true].map((renderSelected) =>
          problems.map((problem, index) => {
            if (!problem.problemBoundingBox) return null

            const isMarkedForReparse = selectedForReparse.has(index)

            // First pass: render unselected boxes
            // Second pass: render selected boxes (on top for drag/resize)
            if (renderSelected !== isMarkedForReparse) return null

            // Use adjusted box if available, otherwise original
            const box = getEffectiveBox(index, problem)
            const pixels = toPixels(box)
            const isSelected = selectedIndex === index
            const isCorrect = problem.studentAnswer === problem.correctAnswer
            const hasAnswer = problem.studentAnswer != null
            const isAdjusted = adjustedBoxes.has(index)
            const canDrag = isMarkedForReparse && onAdjustBox
            const isHovered = hoveredIndex === index
            const hasAnySelections = selectedForReparse.size > 0

            // Determine box color based on status
            let strokeColor: string
            let fillColor: string
            if (isMarkedForReparse) {
              // Orange for problems marked for re-parsing
              strokeColor = '#f97316' // orange-500
              fillColor = 'rgba(249, 115, 22, 0.2)'
            } else if (isSelected) {
              strokeColor = '#3b82f6' // blue-500
              fillColor = 'rgba(59, 130, 246, 0.15)'
            } else if (!hasAnswer) {
              strokeColor = '#6b7280' // gray-500
              fillColor = 'rgba(107, 114, 128, 0.08)'
            } else if (isCorrect) {
              strokeColor = '#22c55e' // green-500
              fillColor = 'rgba(34, 197, 94, 0.08)'
            } else {
              strokeColor = '#ef4444' // red-500
              fillColor = 'rgba(239, 68, 68, 0.08)'
            }

            const handleBoxClick = (e: React.MouseEvent) => {
              e.stopPropagation()
              // Toggle highlight selection (for viewing problem details)
              onSelectProblem(isSelected ? null : index)
            }

            const handleCheckboxClick = (e: React.MouseEvent) => {
              e.stopPropagation()
              if (onToggleReparse) {
                onToggleReparse(index)
              }
            }

            // Resize handle size
            const handleSize = 10

            // Handle positions for resize handles (corners only for simplicity)
            const handles: Array<{
              pos: HandlePosition
              x: number
              y: number
              cursor: string
            }> = [
              { pos: 'nw', x: pixels.x, y: pixels.y, cursor: 'nwse-resize' },
              {
                pos: 'ne',
                x: pixels.x + pixels.width,
                y: pixels.y,
                cursor: 'nesw-resize',
              },
              {
                pos: 'sw',
                x: pixels.x,
                y: pixels.y + pixels.height,
                cursor: 'nesw-resize',
              },
              {
                pos: 'se',
                x: pixels.x + pixels.width,
                y: pixels.y + pixels.height,
                cursor: 'nwse-resize',
              },
            ]

            return (
              <g
                key={`${renderSelected ? 'selected' : 'unselected'}-${problem.problemNumber ?? index}`}
              >
                {/* Background fill */}
                <rect
                  x={pixels.x}
                  y={pixels.y}
                  width={pixels.width}
                  height={pixels.height}
                  fill={fillColor}
                  rx={4}
                  ry={4}
                />
                {/* Border - draggable when selected for reparse */}
                <rect
                  x={pixels.x}
                  y={pixels.y}
                  width={pixels.width}
                  height={pixels.height}
                  fill="none"
                  stroke={strokeColor}
                  strokeWidth={isMarkedForReparse ? 3 : isSelected ? 3 : 1.5}
                  strokeDasharray={
                    isAdjusted ? 'none' : isMarkedForReparse || isSelected ? 'none' : '4 2'
                  }
                  rx={4}
                  ry={4}
                  style={{
                    pointerEvents: 'all',
                    cursor: canDrag ? 'move' : 'pointer',
                  }}
                  onClick={canDrag ? undefined : handleBoxClick}
                  onMouseDown={canDrag ? (e) => handleMouseDown(e, index) : undefined}
                  onMouseEnter={() => setHoveredIndex(index)}
                  onMouseLeave={() => setHoveredIndex((prev) => (prev === index ? null : prev))}
                />
                {/* Resize handles for selected boxes */}
                {canDrag &&
                  handles.map((handle) => (
                    <rect
                      key={handle.pos}
                      x={handle.x - handleSize / 2}
                      y={handle.y - handleSize / 2}
                      width={handleSize}
                      height={handleSize}
                      fill="#f97316"
                      stroke="#ea580c"
                      strokeWidth={1}
                      rx={2}
                      ry={2}
                      style={{ pointerEvents: 'all', cursor: handle.cursor }}
                      onMouseDown={(e) => handleMouseDown(e, index, handle.pos)}
                    />
                  ))}
                {/* Adjusted indicator */}
                {isAdjusted && isMarkedForReparse && (
                  <text
                    x={pixels.x + pixels.width - 4}
                    y={pixels.y + 14}
                    fill="#f97316"
                    fontSize={10}
                    fontWeight="bold"
                    textAnchor="end"
                    style={{ pointerEvents: 'none' }}
                  >

                  </text>
                )}
                {/* Checkbox indicator - show on hover or if selected */}
                {onToggleReparse && (isHovered || isMarkedForReparse || hasAnySelections) && (
                  <g
                    style={{
                      opacity: isMarkedForReparse || isHovered ? 1 : 0.5,
                    }}
                    onMouseEnter={() => setHoveredIndex(index)}
                    onMouseLeave={() => setHoveredIndex((prev) => (prev === index ? null : prev))}
                  >
                    <rect
                      x={pixels.x + pixels.width - 22}
                      y={pixels.y + 4}
                      width={18}
                      height={18}
                      fill={isMarkedForReparse ? '#f97316' : 'rgba(0, 0, 0, 0.6)'}
                      stroke={isMarkedForReparse ? '#ea580c' : '#9ca3af'}
                      strokeWidth={2}
                      rx={3}
                      ry={3}
                      style={{ pointerEvents: 'all', cursor: 'pointer' }}
                      onClick={handleCheckboxClick}
                    />
                    {isMarkedForReparse && (
                      <text
                        x={pixels.x + pixels.width - 13}
                        y={pixels.y + 17}
                        fill="white"
                        fontSize={12}
                        fontWeight="bold"
                        textAnchor="middle"
                        style={{ pointerEvents: 'none' }}
                      >

                      </text>
                    )}
                  </g>
                )}
                {/* Problem number label */}
                <text
                  x={pixels.x + 4}
                  y={pixels.y + 14}
                  fill={strokeColor}
                  fontSize={12}
                  fontWeight={isMarkedForReparse || isSelected ? 'bold' : 'normal'}
                  fontFamily="monospace"
                  style={{ pointerEvents: 'none' }}
                >
                  #{index + 1}
                </text>
              </g>
            )
          })
        )}
      </svg>

      {/* Debug panel showing dimensions and selected box coordinates */}
      {debug && (
        <div
          data-element="bbox-debug-panel"
          className={css({
            position: 'absolute',
            bottom: 0,
            left: 0,
            right: 0,
            padding: 2,
            backgroundColor: 'rgba(0, 0, 0, 0.85)',
            color: 'white',
            fontSize: 'xs',
            fontFamily: 'mono',
            maxHeight: '150px',
            overflow: 'auto',
            pointerEvents: 'auto',
          })}
        >
          <div className={css({ marginBottom: 1 })}>
            <strong>Image Debug:</strong> natural={dimensions.naturalWidth}x
            {dimensions.naturalHeight} | element={dimensions.elementWidth}x
            {dimensions.elementHeight} | content=
            {Math.round(dimensions.contentWidth)}x{Math.round(dimensions.contentHeight)} | offset=(
            {Math.round(dimensions.offsetX)},{Math.round(dimensions.offsetY)})
          </div>
          {selectedIndex !== null && problems[selectedIndex] && (
            <div>
              <strong>Selected #{selectedIndex + 1}:</strong> raw=(
              {problems[selectedIndex].problemBoundingBox.x.toFixed(3)},{' '}
              {problems[selectedIndex].problemBoundingBox.y.toFixed(3)},{' '}
              {problems[selectedIndex].problemBoundingBox.width.toFixed(3)},{' '}
              {problems[selectedIndex].problemBoundingBox.height.toFixed(3)}) | pixels=(
              {Math.round(toPixels(problems[selectedIndex].problemBoundingBox).x)},{' '}
              {Math.round(toPixels(problems[selectedIndex].problemBoundingBox).y)},{' '}
              {Math.round(toPixels(problems[selectedIndex].problemBoundingBox).width)}x
              {Math.round(toPixels(problems[selectedIndex].problemBoundingBox).height)})
            </div>
          )}
          <div className={css({ marginTop: 1, color: 'cyan' })}>
            Cyan dashed border = actual image content bounds (accounting for object-fit: contain)
          </div>
        </div>
      )}
    </div>
  )
}

export default BoundingBoxOverlay