All files / web/src/components/vision VisionDvrControls.tsx

11.72% Statements 34/290
100% Branches 0/0
0% Functions 0/1
11.72% Lines 34/290

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 2911x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
'use client'
 
import { useState, useCallback, useEffect, useRef } from 'react'
import { css } from '../../../styled-system/css'
 
interface VisionDvrControlsProps {
  /** Session ID for DVR requests */
  sessionId: string
  /** Whether DVR is available (buffer has data) */
  isAvailable: boolean
  /** Available time range in ms from recording start */
  availableFromMs?: number
  availableToMs?: number
  /** Current problem start time in ms from recording start (for per-problem scrubbing) */
  currentProblemStartMs?: number | null
  /** Current problem number (for display) */
  currentProblemNumber?: number | null
  /** Callback to request a frame at offset */
  onScrub: (offsetMs: number) => void
  /** Callback when returning to live */
  onGoLive: () => void
  /** Whether currently showing live feed */
  isLive: boolean
}
 
/**
 * DVR controls for live vision feed observation.
 *
 * Allows observers to:
 * - Scrub back within the current problem only
 * - Return to live feed
 * - See buffer availability for current problem
 */
export function VisionDvrControls({
  sessionId,
  isAvailable,
  availableFromMs = 0,
  availableToMs = 0,
  currentProblemStartMs,
  currentProblemNumber,
  onScrub,
  onGoLive,
  isLive,
}: VisionDvrControlsProps) {
  const [scrubPosition, setScrubPosition] = useState(100) // Percentage (100 = live)
  const [isDragging, setIsDragging] = useState(false)
  const sliderRef = useRef<HTMLDivElement>(null)

  // Use current problem start as the effective scrub start (if available)
  // This constrains scrubbing to the current problem only
  const effectiveFromMs =
    currentProblemStartMs != null
      ? Math.max(availableFromMs, currentProblemStartMs)
      : availableFromMs

  // Duration available for scrubbing (within current problem)
  const bufferDuration = availableToMs - effectiveFromMs
  const bufferSeconds = Math.floor(bufferDuration / 1000)

  // Handle slider interaction
  const handleSliderChange = useCallback(
    (clientX: number) => {
      if (!sliderRef.current || !isAvailable) return

      const rect = sliderRef.current.getBoundingClientRect()
      const percentage = Math.max(0, Math.min(100, ((clientX - rect.left) / rect.width) * 100))
      setScrubPosition(percentage)

      // Calculate offset from recording start (constrained to current problem)
      const offsetMs = effectiveFromMs + (percentage / 100) * (availableToMs - effectiveFromMs)
      onScrub(offsetMs)
    },
    [isAvailable, effectiveFromMs, availableToMs, onScrub]
  )

  // Mouse/touch handlers
  const handleMouseDown = useCallback(
    (e: React.MouseEvent) => {
      if (!isAvailable) return
      setIsDragging(true)
      handleSliderChange(e.clientX)
    },
    [isAvailable, handleSliderChange]
  )

  const handleMouseMove = useCallback(
    (e: MouseEvent) => {
      if (isDragging) {
        handleSliderChange(e.clientX)
      }
    },
    [isDragging, handleSliderChange]
  )

  const handleMouseUp = useCallback(() => {
    setIsDragging(false)
  }, [])

  // Global mouse handlers for dragging
  useEffect(() => {
    if (isDragging) {
      document.addEventListener('mousemove', handleMouseMove)
      document.addEventListener('mouseup', handleMouseUp)
      return () => {
        document.removeEventListener('mousemove', handleMouseMove)
        document.removeEventListener('mouseup', handleMouseUp)
      }
    }
  }, [isDragging, handleMouseMove, handleMouseUp])

  // Go live handler
  const handleGoLive = useCallback(() => {
    setScrubPosition(100)
    onGoLive()
  }, [onGoLive])

  // Format time for display
  const formatTime = (ms: number) => {
    const seconds = Math.floor(ms / 1000)
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return mins > 0 ? `${mins}:${secs.toString().padStart(2, '0')}` : `${secs}s`
  }

  // Calculate current offset for display (relative to current problem)
  const currentOffsetMs =
    effectiveFromMs + (scrubPosition / 100) * (availableToMs - effectiveFromMs)
  const secondsAgo = Math.floor((availableToMs - currentOffsetMs) / 1000)

  if (!isAvailable) {
    return (
      <div
        data-component="vision-dvr-controls"
        data-status="unavailable"
        className={css({
          display: 'flex',
          alignItems: 'center',
          gap: 2,
          px: 2,
          py: 1,
          bg: 'rgba(0, 0, 0, 0.6)',
          borderRadius: 'md',
          fontSize: 'xs',
          color: 'gray.500',
        })}
      >
        <span>DVR not available</span>
      </div>
    )
  }

  return (
    <div
      data-component="vision-dvr-controls"
      data-status={isLive ? 'live' : 'scrubbing'}
      className={css({
        display: 'flex',
        flexDirection: 'column',
        gap: 1,
        p: 2,
        bg: 'rgba(0, 0, 0, 0.7)',
        backdropFilter: 'blur(4px)',
        borderRadius: 'md',
      })}
    >
      {/* Scrub slider */}
      <div
        ref={sliderRef}
        data-element="scrub-slider"
        className={css({
          position: 'relative',
          height: '20px',
          cursor: 'pointer',
          touchAction: 'none',
        })}
        onMouseDown={handleMouseDown}
      >
        {/* Track */}
        <div
          className={css({
            position: 'absolute',
            top: '50%',
            left: 0,
            right: 0,
            height: '4px',
            bg: 'gray.700',
            borderRadius: 'full',
            transform: 'translateY(-50%)',
          })}
        />

        {/* Buffer fill */}
        <div
          className={css({
            position: 'absolute',
            top: '50%',
            left: 0,
            height: '4px',
            bg: 'cyan.600',
            borderRadius: 'full',
            transform: 'translateY(-50%)',
          })}
          style={{ width: `${scrubPosition}%` }}
        />

        {/* Thumb */}
        <div
          className={css({
            position: 'absolute',
            top: '50%',
            width: '12px',
            height: '12px',
            bg: 'white',
            borderRadius: 'full',
            transform: 'translate(-50%, -50%)',
            boxShadow: 'md',
            transition: isDragging ? 'none' : 'left 0.1s',
          })}
          style={{ left: `${scrubPosition}%` }}
        />
      </div>

      {/* Controls row */}
      <div
        className={css({
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          fontSize: 'xs',
        })}
      >
        {/* Buffer info - shows time available for current problem */}
        <span className={css({ color: 'gray.400' })}>
          {currentProblemNumber != null
            ? `Q${currentProblemNumber}: -${bufferSeconds}s`
            : `-${bufferSeconds}s available`}
        </span>

        {/* Current position / Live button */}
        {isLive ? (
          <div
            className={css({
              display: 'flex',
              alignItems: 'center',
              gap: 1,
              color: 'green.400',
            })}
          >
            <div
              className={css({
                w: '6px',
                h: '6px',
                borderRadius: 'full',
                bg: 'green.500',
                animation: 'pulse 2s infinite',
              })}
            />
            <span>LIVE</span>
          </div>
        ) : (
          <div
            className={css({
              display: 'flex',
              alignItems: 'center',
              gap: 2,
            })}
          >
            <span className={css({ color: 'yellow.400' })}>-{secondsAgo}s ago</span>
            <button
              onClick={handleGoLive}
              className={css({
                px: 2,
                py: 0.5,
                bg: 'green.600',
                color: 'white',
                borderRadius: 'md',
                fontSize: 'xs',
                fontWeight: 'medium',
                cursor: 'pointer',
                _hover: { bg: 'green.500' },
              })}
            >
              Go Live
            </button>
          </div>
        )}
      </div>
    </div>
  )
}