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 | 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 1x 1x 26x 26x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 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 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 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 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 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 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 27x 47x 47x 47x 47x 47x 47x 47x 47x 27x 27x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 2x 1x 47x 47x 4x 4x 4x 4x 4x 47x 47x 47x 6x 6x 6x 6x 6x 47x 47x 47x 3x 3x 3x 3x 3x 47x 47x 47x 3x 3x 3x 3x 3x 47x 47x 47x 1x 1x 1x 1x 1x 47x 47x 47x 47x 47x 47x 2x 47x 47x 1x 47x 47x 47x 47x 47x 47x 5x 47x 47x 47x 5x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 1x 1x 51x 51x 4x 4x 47x 47x | 'use client'
import type React from 'react'
import {
createContext,
type MutableRefObject,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from 'react'
import type { ColumnImageData } from '@/lib/vision/trainingData'
import { imageDataToBase64Png } from '@/lib/vision/trainingData'
import type { CalibrationGrid } from '@/types/vision'
/**
* Camera source type for vision
*/
export type CameraSourceType = 'local' | 'phone'
/**
* Configuration for abacus vision (camera-based input)
*/
export interface VisionConfig {
/** Whether vision mode is enabled */
enabled: boolean
/** Selected camera device ID */
cameraDeviceId: string | null
/** Saved calibration grid for cropping */
calibration: CalibrationGrid | null
/** Remote phone camera session ID (for phone-as-camera mode) */
remoteCameraSessionId: string | null
/** Currently active camera source - tracks which camera is in use */
activeCameraSource: CameraSourceType | null
/** Whether to show digital abacus mirror instead of rectified video (persisted preference) */
showMirrorMode?: boolean
}
const DEFAULT_VISION_CONFIG: VisionConfig = {
enabled: false,
cameraDeviceId: null,
calibration: null,
remoteCameraSessionId: null,
activeCameraSource: null,
}
const VISION_CONFIG_STORAGE_KEY = 'abacus-vision-config'
/**
* Load vision config from localStorage
*/
function loadVisionConfig(): VisionConfig {
if (typeof window === 'undefined') return DEFAULT_VISION_CONFIG
try {
const stored = localStorage.getItem(VISION_CONFIG_STORAGE_KEY)
if (stored) {
const parsed = JSON.parse(stored)
// Infer activeCameraSource if not set but we have camera config
// This handles configs saved before activeCameraSource was added
let activeCameraSource = parsed.activeCameraSource ?? null
if (activeCameraSource === null) {
if (parsed.remoteCameraSessionId) {
activeCameraSource = 'phone'
} else if (parsed.cameraDeviceId) {
activeCameraSource = 'local'
}
}
return {
...DEFAULT_VISION_CONFIG,
...parsed,
activeCameraSource,
// Always start with vision disabled - user must re-enable
enabled: false,
}
}
} catch (e) {
console.error('[MyAbacusContext] Failed to load vision config:', e)
}
return DEFAULT_VISION_CONFIG
}
/**
* Save vision config to localStorage
*/
function saveVisionConfig(config: VisionConfig): void {
if (typeof window === 'undefined') return
try {
localStorage.setItem(VISION_CONFIG_STORAGE_KEY, JSON.stringify(config))
} catch (e) {
console.error('[MyAbacusContext] Failed to save vision config:', e)
}
}
/**
* Configuration for a docked abacus
* Props align with AbacusReact from @soroban/abacus-react
*/
export interface DockConfig {
/** The DOM element to render the abacus into */
element: HTMLElement
/** Optional identifier for debugging */
id?: string
/** Number of columns (default: 5) */
columns?: number
/** Whether the abacus is interactive (default: true) */
interactive?: boolean
/** Whether to show numbers below columns (default: true) */
showNumbers?: boolean
/** Whether to animate bead movements (default: true) */
animated?: boolean
/** Scale factor for the abacus (default: auto-fit to container) */
scaleFactor?: number
/** Whether the dock is currently visible in the viewport */
isVisible?: boolean
/** Controlled value - when provided, dock controls the abacus value */
value?: number
/** Default value for uncontrolled mode */
defaultValue?: number
/** Callback when value changes (for controlled mode) */
onValueChange?: (newValue: number) => void
/** Hide the undock button (default: false) */
hideUndock?: boolean
}
/**
* Animation state for dock transitions
*/
export interface DockAnimationState {
phase: 'docking' | 'undocking'
/** Viewport rect of the starting position */
fromRect: { x: number; y: number; width: number; height: number }
/** Viewport rect of the target position */
toRect: { x: number; y: number; width: number; height: number }
/** Scale of the abacus at start */
fromScale: number
/** Scale of the abacus at end */
toScale: number
}
/**
* Vision frame data for broadcasting
*/
export interface VisionFrameData {
/** Base64-encoded JPEG image data */
imageData: string
/** Detected abacus value (null if not yet detected) */
detectedValue: number | null
/** Detection confidence (0-1) */
confidence: number
}
/**
* Callback type for vision frame broadcasting
*/
export type VisionFrameCallback = (frame: VisionFrameData) => void
/**
* Storybook-only state override for testing mirror mode layout.
* Only used when testing - production code should not use this.
*/
export interface VisionStorybookState {
/** Force mirror mode on */
showAbacusMirror: true
/** Fake detected digits */
columnDigits: number[]
/** Fake detected value */
detectedValue: number
/** Fake confidence */
confidence: number
/** Fake video stream to display in PIP */
videoStream: MediaStream | null
}
interface MyAbacusContextValue {
isOpen: boolean
open: () => void
close: () => void
toggle: () => void
/** Temporarily hide the abacus (e.g., when virtual keyboard is shown) */
isHidden: boolean
setIsHidden: (hidden: boolean) => void
/** Bottom offset for abacus button (to position above on-screen keyboards in portrait) */
bottomOffset: number
setBottomOffset: (offset: number) => void
/** Right offset for abacus button (to position left of on-screen keyboards in landscape) */
rightOffset: number
setRightOffset: (offset: number) => void
/** Opt-in to show the abacus while in a game (games hide it by default) */
showInGame: boolean
setShowInGame: (show: boolean) => void
/** Currently registered dock (if any) */
dock: DockConfig | null
/** Register a dock for the abacus to render into */
registerDock: (config: DockConfig) => void
/** Unregister a dock (should be called on unmount) */
unregisterDock: (element: HTMLElement) => void
/** Update dock visibility status */
updateDockVisibility: (element: HTMLElement, isVisible: boolean) => void
/** Update dock configuration without re-registering */
updateDockConfig: (element: HTMLElement, config: Partial<Omit<DockConfig, 'element'>>) => void
/** Whether the abacus is currently docked (user chose to dock it) */
isDockedByUser: boolean
/** Dock the abacus into the current dock */
dockInto: () => void
/** Undock the abacus (return to button mode) */
undock: () => void
/** Current dock animation state (null when not animating) */
dockAnimationState: DockAnimationState | null
/** Ref to the button element for measuring position */
buttonRef: MutableRefObject<HTMLDivElement | null>
/** Start the docking animation (called internally by MyAbacus when it measures rects) */
startDockAnimation: (animState: DockAnimationState) => void
/** Complete the docking animation (switches to docked state) */
completeDockAnimation: () => void
/** Start the undocking animation (called internally by MyAbacus when it measures rects) */
startUndockAnimation: (animState: DockAnimationState) => void
/** Complete the undocking animation (switches to button state) */
completeUndockAnimation: () => void
/** Request to dock with animation (like clicking the MyAbacus button) */
requestDock: () => void
/** Pending dock request flag (MyAbacus watches this) */
pendingDockRequest: boolean
/** Clear the pending dock request (called by MyAbacus after handling) */
clearDockRequest: () => void
/** Set the value on the docked abacus (only works when docked) */
setDockedValue: (value: number) => void
/** Current abacus value (for reading) */
abacusValue: number
// Vision-related state
/** Current vision configuration */
visionConfig: VisionConfig
/** Whether vision setup is complete (has camera and calibration) */
isVisionSetupComplete: boolean
/** Set whether vision is enabled */
setVisionEnabled: (enabled: boolean) => void
/** Set the selected camera device ID */
setVisionCamera: (deviceId: string | null) => void
/** Set the calibration grid */
setVisionCalibration: (calibration: CalibrationGrid | null) => void
/** Set the remote camera session ID */
setVisionRemoteSession: (sessionId: string | null) => void
/** Set the active camera source */
setVisionCameraSource: (source: CameraSourceType | null) => void
/** Set whether to show digital abacus mirror instead of rectified video */
setVisionMirrorMode: (showMirror: boolean) => void
/** Whether the vision setup modal is open */
isVisionSetupOpen: boolean
/** Open the vision setup modal */
openVisionSetup: () => void
/** Close the vision setup modal */
closeVisionSetup: () => void
/** Set a callback for receiving vision frames (for broadcasting to observers) */
setVisionFrameCallback: (callback: VisionFrameCallback | null) => void
/** Emit a vision frame (called by DockedVisionFeed) */
emitVisionFrame: (frame: VisionFrameData) => void
/** Ref for DockedVisionFeed to register its video/image source for training data capture */
visionSourceRef: MutableRefObject<VisionSourceRef | null>
/** Capture column images from the current vision source for training data */
captureTrainingColumns: (columnCount: number) => ColumnImageData[] | null
}
/**
* Vision source reference for training data capture
*/
export interface VisionSourceRef {
type: 'video' | 'image'
element: HTMLVideoElement | HTMLImageElement
}
const MyAbacusContext = createContext<MyAbacusContextValue | undefined>(undefined)
export function MyAbacusProvider({ children }: { children: React.ReactNode }) {
const [isOpen, setIsOpen] = useState(false)
const [isHidden, setIsHidden] = useState(false)
const [bottomOffset, setBottomOffset] = useState(0)
const [rightOffset, setRightOffset] = useState(0)
const [showInGame, setShowInGame] = useState(false)
const [dock, setDock] = useState<DockConfig | null>(null)
const [isDockedByUser, setIsDockedByUser] = useState(false)
const [dockAnimationState, setDockAnimationState] = useState<DockAnimationState | null>(null)
const buttonRef = useRef<HTMLDivElement | null>(null)
const [pendingDockRequest, setPendingDockRequest] = useState(false)
const [abacusValue, setAbacusValue] = useState(0)
// Ref to track dock existence for stable requestDock callback
const dockRef = useRef<DockConfig | null>(null)
useEffect(() => {
dockRef.current = dock
}, [dock])
// Vision state
const [visionConfig, setVisionConfig] = useState<VisionConfig>(DEFAULT_VISION_CONFIG)
const [isVisionSetupOpen, setIsVisionSetupOpen] = useState(false)
// Load vision config from localStorage on mount
useEffect(() => {
const loaded = loadVisionConfig()
setVisionConfig(loaded)
}, [])
const open = useCallback(() => setIsOpen(true), [])
const close = useCallback(() => setIsOpen(false), [])
const toggle = useCallback(() => setIsOpen((prev) => !prev), [])
const registerDock = useCallback((config: DockConfig) => {
setDock(config)
}, [])
const unregisterDock = useCallback((element: HTMLElement) => {
setDock((current) => {
if (current?.element === element) {
// NOTE: Do NOT set isDockedByUser to false here!
// This gets called during React re-renders when AbacusDock unmounts/remounts.
// Setting isDockedByUser=false would cause unwanted undocking during problem transitions.
// Users should only be undocked via explicit undock() call.
return null
}
return current
})
}, [])
const updateDockVisibility = useCallback((element: HTMLElement, isVisible: boolean) => {
setDock((current) => {
if (current?.element === element) {
return { ...current, isVisible }
}
return current
})
}, [])
const updateDockConfig = useCallback(
(element: HTMLElement, config: Partial<Omit<DockConfig, 'element'>>) => {
setDock((current) => {
if (current?.element === element) {
return { ...current, ...config }
}
return current
})
},
[]
)
const dockInto = useCallback(() => {
if (dock) {
setIsDockedByUser(true)
setIsOpen(false)
}
}, [dock])
const undock = useCallback(() => {
setIsDockedByUser(false)
}, [])
// Animation callbacks
const startDockAnimation = useCallback((animState: DockAnimationState) => {
setDockAnimationState(animState)
}, [])
const completeDockAnimation = useCallback(() => {
setDockAnimationState(null)
setIsDockedByUser(true)
setIsOpen(false)
}, [])
const startUndockAnimation = useCallback((animState: DockAnimationState) => {
setDockAnimationState(animState)
setIsDockedByUser(false) // Remove from portal immediately so we can animate the overlay
}, [])
const completeUndockAnimation = useCallback(() => {
setDockAnimationState(null)
}, [])
// Request to dock with animation (triggers MyAbacus to animate into dock)
// Uses ref to avoid recreating callback when dock config changes
const requestDock = useCallback(() => {
if (dockRef.current) {
setPendingDockRequest(true)
}
}, [])
// Clear the pending dock request after MyAbacus handles it
const clearDockRequest = useCallback(() => {
setPendingDockRequest(false)
}, [])
// Set the value on the docked abacus
const setDockedValue = useCallback((value: number) => {
setAbacusValue(value)
}, [])
// Vision callbacks
// Setup is complete if an active camera source is set and configured:
// - Local camera: has camera device (calibration is optional - auto-crop works without it)
// - Remote camera: has remote session ID (phone handles calibration)
const isVisionSetupComplete =
visionConfig.activeCameraSource !== null &&
((visionConfig.activeCameraSource === 'local' && visionConfig.cameraDeviceId !== null) ||
(visionConfig.activeCameraSource === 'phone' && visionConfig.remoteCameraSessionId !== null))
const setVisionEnabled = useCallback((enabled: boolean) => {
setVisionConfig((prev) => {
const updated = { ...prev, enabled }
saveVisionConfig(updated)
return updated
})
}, [])
const setVisionCamera = useCallback((deviceId: string | null) => {
setVisionConfig((prev) => {
const updated = { ...prev, cameraDeviceId: deviceId }
saveVisionConfig(updated)
return updated
})
}, [])
const setVisionCalibration = useCallback((calibration: CalibrationGrid | null) => {
setVisionConfig((prev) => {
const updated = { ...prev, calibration }
saveVisionConfig(updated)
return updated
})
}, [])
const setVisionRemoteSession = useCallback((sessionId: string | null) => {
setVisionConfig((prev) => {
const updated = { ...prev, remoteCameraSessionId: sessionId }
saveVisionConfig(updated)
return updated
})
}, [])
const setVisionCameraSource = useCallback((source: CameraSourceType | null) => {
setVisionConfig((prev) => {
const updated = { ...prev, activeCameraSource: source }
saveVisionConfig(updated)
return updated
})
}, [])
const setVisionMirrorMode = useCallback((showMirror: boolean) => {
setVisionConfig((prev) => {
const updated = { ...prev, showMirrorMode: showMirror }
saveVisionConfig(updated)
return updated
})
}, [])
const openVisionSetup = useCallback(() => {
setIsVisionSetupOpen(true)
}, [])
const closeVisionSetup = useCallback(() => {
setIsVisionSetupOpen(false)
}, [])
// Vision frame broadcasting
const visionFrameCallbackRef = useRef<VisionFrameCallback | null>(null)
const setVisionFrameCallback = useCallback((callback: VisionFrameCallback | null) => {
visionFrameCallbackRef.current = callback
}, [])
const emitVisionFrame = useCallback((frame: VisionFrameData) => {
visionFrameCallbackRef.current?.(frame)
}, [])
// Vision source ref for training data capture
// We need to explicitly type this to get MutableRefObject instead of RefObject
const visionSourceRef: MutableRefObject<VisionSourceRef | null> = useRef<VisionSourceRef | null>(
null
)
// Capture training columns from current vision source
const captureTrainingColumns = useCallback(
(columnCount: number): ColumnImageData[] | null => {
const source = visionSourceRef.current
if (!source) return null
try {
// Dynamically import frameProcessor (client-side only)
// eslint-disable-next-line @typescript-eslint/no-require-imports
const {
processVideoFrame,
processImageFrame,
toGrayscale,
resizeImageData,
sliceIntoColumns,
} = require('@/lib/vision/frameProcessor')
let columnImages: ImageData[]
if (source.type === 'video') {
const video = source.element as HTMLVideoElement
if (!video || video.readyState < 2) return null
if (visionConfig.calibration) {
columnImages = processVideoFrame(video, visionConfig.calibration)
} else {
// Fallback: slice entire frame into columns
const canvas = document.createElement('canvas')
canvas.width = video.videoWidth
canvas.height = video.videoHeight
const ctx = canvas.getContext('2d')!
ctx.drawImage(video, 0, 0)
const roiData = ctx.getImageData(0, 0, canvas.width, canvas.height)
const syntheticCalibration = {
roi: { x: 0, y: 0, width: canvas.width, height: canvas.height },
columnCount,
columnDividers: Array.from(
{ length: columnCount - 1 },
(_, i) => (i + 1) / columnCount
),
rotation: 0,
}
const cols = sliceIntoColumns(roiData, syntheticCalibration)
columnImages = cols.map((col: ImageData) => {
const gray = toGrayscale(col)
return resizeImageData(gray, 64, 128)
})
}
} else {
const image = source.element as HTMLImageElement
if (!image || !image.complete || image.naturalWidth === 0) return null
// Phone camera - no calibration needed
columnImages = processImageFrame(image, null, columnCount)
}
if (columnImages.length === 0) return null
// Convert to base64 PNG
return columnImages.map((imgData: ImageData, index: number) => ({
columnIndex: index,
imageData: imageDataToBase64Png(imgData),
}))
} catch (error) {
console.error('[MyAbacusContext] Failed to capture training columns:', error)
return null
}
},
[visionConfig.calibration]
)
return (
<MyAbacusContext.Provider
value={{
isOpen,
open,
close,
toggle,
isHidden,
setIsHidden,
bottomOffset,
setBottomOffset,
rightOffset,
setRightOffset,
showInGame,
setShowInGame,
dock,
registerDock,
unregisterDock,
updateDockVisibility,
updateDockConfig,
isDockedByUser,
dockInto,
undock,
dockAnimationState,
buttonRef,
startDockAnimation,
completeDockAnimation,
startUndockAnimation,
completeUndockAnimation,
requestDock,
pendingDockRequest,
clearDockRequest,
setDockedValue,
abacusValue,
// Vision
visionConfig,
isVisionSetupComplete,
setVisionEnabled,
setVisionCamera,
setVisionCalibration,
setVisionRemoteSession,
setVisionCameraSource,
setVisionMirrorMode,
isVisionSetupOpen,
openVisionSetup,
closeVisionSetup,
setVisionFrameCallback,
emitVisionFrame,
visionSourceRef,
captureTrainingColumns,
}}
>
{children}
</MyAbacusContext.Provider>
)
}
export function useMyAbacus() {
const context = useContext(MyAbacusContext)
if (!context) {
throw new Error('useMyAbacus must be used within MyAbacusProvider')
}
return context
}
|