import React, { useCallback, useEffect, useRef, useState } from 'react'; import { apiService } from '../services/api.service'; import { toast, ToastContainer } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; const GRID_SIZE = 8; const CELL_COUNT = GRID_SIZE * GRID_SIZE; const LONG_PRESS_MS = 600; const COLOR_POLL_MS = 200; const EASTER_EGG = [19, 23, 20, 0, 2]; // Color code sent by the backend → cell state const STATE_BY_FILL = { yellow: 'active', gray: 'pending', green: 'pass', red: 'fail', }; // States are distinguished by color + icon (don't rely on color alone, for colorblindness) const CELL_STATES = { active: { label: 'Active', className: 'bg-hmi-warn border-hmi-warn text-hmi-bg hmi-active-ring', icon: '▶' }, pending: { label: 'Pending', className: 'bg-hmi-raised border-hmi-line text-hmi-text', icon: null }, pass: { label: 'Pass', className: 'bg-hmi-ok border-hmi-ok text-hmi-bg', icon: '✓' }, fail: { label: 'Fail', className: 'bg-hmi-err border-hmi-err text-hmi-bg', icon: '✕' }, ignored: { label: 'Ignore', className: 'hmi-hatch border-dashed border-hmi-muted text-hmi-muted', icon: '⊘' }, }; const LEGEND_ORDER = ['active', 'pending', 'pass', 'fail', 'ignored']; const ScanTrace = ({ onScan }) => { const [fills, setFills] = useState(() => Array(CELL_COUNT).fill('gray')); const [ignored, setIgnored] = useState([]); const [internalData, setInternalData] = useState('blank'); const [pressedIndex, setPressedIndex] = useState(null); const [longPressed, setLongPressed] = useState(false); // Ref so that delayed calls, like "Undo" in the toast, see the current list const ignoredRef = useRef([]); const seededRef = useRef(false); const pressRef = useRef({ index: null, timer: null, long: false }); // Poll cell colors periodically useEffect(() => { let cancelled = false; const fetchColors = async () => { try { const data = await apiService.getColors(); if (cancelled) return; const colors = data.colors || []; // Inherit the ignore list from the backend when the page refreshes if (!seededRef.current) { seededRef.current = true; const fromBackend = colors .map((color, index) => (color === 'black' ? index : null)) .filter((index) => index !== null); if (fromBackend.length && !ignoredRef.current.length) { ignoredRef.current = fromBackend; setIgnored(fromBackend); } } setFills(Array.from({ length: CELL_COUNT }, (_, i) => colors[i] || 'gray')); } catch (error) { console.log('An error occurred while retrieving colors:', error); } }; fetchColors(); const interval = setInterval(fetchColors, COLOR_POLL_MS); return () => { cancelled = true; clearInterval(interval); }; }, []); useEffect(() => { if (internalData !== 'blank') { onScan?.(internalData); } }, [internalData, onScan]); useEffect(() => () => clearTimeout(pressRef.current.timer), []); const toggleIgnore = useCallback((index) => { const current = ignoredRef.current; const wasIgnored = current.includes(index); const next = wasIgnored ? current.filter((i) => i !== index) : [...current, index]; if (JSON.stringify(current) === JSON.stringify(EASTER_EGG)) { toast.success('🎉 Easter egg discovered!'); setInternalData('Easter egg :)'); } else { setInternalData(''); } ignoredRef.current = next; setIgnored(next); apiService .controlScan({ ignored_index_list: next }) .catch((error) => toast.error(`Failed to send ignore list: ${error.message}`)); return !wasIgnored; }, []); const handleTap = useCallback((index) => { const nowIgnored = toggleIgnore(index); toast( ({ closeToast }) => (
{index}{' '} {nowIgnored ? 'ignored' : 'restored to scan'}
), { autoClose: 5000 } ); }, [toggleIgnore]); const handleSetIndex = useCallback(async (index) => { try { await apiService.setIndex(String(index)); toast.success(`Index ${index} set`); } catch (error) { toast.error(`Could not set index: ${error.message}`); } }, []); const resetPress = () => { clearTimeout(pressRef.current.timer); pressRef.current = { index: null, timer: null, long: false }; setPressedIndex(null); setLongPressed(false); }; // Pointer events handle mouse, pen, and touch together const handlePointerDown = (event, index) => { if (event.button !== 0) return; event.currentTarget.setPointerCapture?.(event.pointerId); clearTimeout(pressRef.current.timer); const timer = setTimeout(() => { pressRef.current.long = true; setLongPressed(true); navigator.vibrate?.(50); }, LONG_PRESS_MS); pressRef.current = { index, timer, long: false }; setPressedIndex(index); setLongPressed(false); }; const handlePointerUp = (event, index) => { const { index: pressed, long } = pressRef.current; const rect = event.currentTarget.getBoundingClientRect(); // Cancel the action if the finger slid outside the cell const inside = event.clientX >= rect.left && event.clientX <= rect.right && event.clientY >= rect.top && event.clientY <= rect.bottom; resetPress(); if (pressed !== index || !inside) return; if (long) { handleSetIndex(index); } else { handleTap(index); } }; const cellState = (index) => ignored.includes(index) ? 'ignored' : STATE_BY_FILL[fills[index]] || 'pending'; return (
{/* Title and legend */}
Scan trace {ignored.length > 0 && ( {ignored.length} points ignored )}
    {LEGEND_ORDER.map((key) => { const state = CELL_STATES[key]; return (
  • {state.label}
  • ); })}
{/* 8x8 grid: scales as a square relative to the panel's short edge, never overflows */}
{Array.from({ length: CELL_COUNT }, (_, index) => { const key = cellState(index); const state = CELL_STATES[key]; const pressed = pressedIndex === index; return ( ); })}
Tap: ignore / undo | Long-press: set index
); }; export default ScanTrace;