Spaces:
Running
Running
Download frontend/src/components/ScanTrace.js from xenecode/Jaguar_Project: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/spaces/xenecode/Jaguar_Project/resolve/main/frontend/src/components/ScanTrace.js
- Command line
-
hf download hf://spaces/xenecode/Jaguar_Project/frontend/src/components/ScanTrace.js
-
curl -L -o ScanTrace.js https://huggingface.co/spaces/xenecode/Jaguar_Project/resolve/main/frontend/src/components/ScanTrace.js
10.4 kB
| 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 }) => ( | |
| <div className="flex items-center justify-between gap-4"> | |
| <span> | |
| <span className="font-mono font-semibold">{index}</span>{' '} | |
| {nowIgnored ? 'ignored' : 'restored to scan'} | |
| </span> | |
| <button | |
| type="button" | |
| onClick={() => { | |
| toggleIgnore(index); | |
| closeToast(); | |
| }} | |
| className="min-h-[40px] shrink-0 border border-hmi-accent px-3 text-sm font-semibold uppercase tracking-wider text-hmi-accent active:bg-hmi-accent active:text-hmi-bg" | |
| > | |
| Undo | |
| </button> | |
| </div> | |
| ), | |
| { 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 ( | |
| <div className="flex h-full min-h-0 flex-col"> | |
| <ToastContainer | |
| position="bottom-right" | |
| autoClose={3000} | |
| newestOnTop | |
| closeOnClick={false} | |
| pauseOnHover | |
| theme="dark" | |
| closeButton={false} | |
| /> | |
| {/* Title and legend */} | |
| <div className="flex flex-wrap items-center justify-between gap-x-6 gap-y-2 border-b border-hmi-line px-4 py-2.5"> | |
| <div className="flex items-baseline gap-3"> | |
| <span className="text-sm font-semibold uppercase tracking-[0.14em]">Scan trace</span> | |
| {ignored.length > 0 && ( | |
| <span className="font-mono text-xs text-hmi-muted">{ignored.length} points ignored</span> | |
| )} | |
| </div> | |
| <ul className="flex flex-wrap items-center gap-x-4 gap-y-1"> | |
| {LEGEND_ORDER.map((key) => { | |
| const state = CELL_STATES[key]; | |
| return ( | |
| <li key={key} className="flex items-center gap-1.5 text-sm text-hmi-muted"> | |
| <span | |
| className={`flex h-5 w-5 items-center justify-center border text-[10px] font-bold leading-none ${state.className.replace('hmi-active-ring', '')}`} | |
| aria-hidden="true" | |
| > | |
| {state.icon} | |
| </span> | |
| {state.label} | |
| </li> | |
| ); | |
| })} | |
| </ul> | |
| </div> | |
| {/* 8x8 grid: scales as a square relative to the panel's short edge, never overflows */} | |
| <div className="flex min-h-0 flex-1 items-center justify-center px-3 py-3" style={{ containerType: 'size' }}> | |
| <div | |
| className="grid gap-1.5" | |
| style={{ | |
| gridTemplateColumns: `repeat(${GRID_SIZE}, minmax(0, 1fr))`, | |
| gridTemplateRows: `repeat(${GRID_SIZE}, minmax(0, 1fr))`, | |
| width: 'min(100cqw, 100cqh)', | |
| height: 'min(100cqw, 100cqh)', | |
| fontSize: `calc(min(100cqw, 100cqh) / ${GRID_SIZE} * 0.34)`, | |
| }} | |
| > | |
| {Array.from({ length: CELL_COUNT }, (_, index) => { | |
| const key = cellState(index); | |
| const state = CELL_STATES[key]; | |
| const pressed = pressedIndex === index; | |
| return ( | |
| <button | |
| key={index} | |
| type="button" | |
| aria-label={`Point ${index}: ${state.label}`} | |
| onPointerDown={(event) => handlePointerDown(event, index)} | |
| onPointerUp={(event) => handlePointerUp(event, index)} | |
| onPointerCancel={resetPress} | |
| onContextMenu={(event) => event.preventDefault()} | |
| className={`relative flex select-none items-center justify-center overflow-hidden border-2 font-mono font-bold leading-none touch-manipulation transition-[filter,transform] duration-100 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-hmi-accent [@media(hover:hover)]:hover:brightness-110 ${state.className} ${pressed ? 'scale-[0.94] brightness-90' : ''}`} | |
| > | |
| {index} | |
| {state.icon && ( | |
| <span className="absolute right-[6%] top-[4%] text-[0.45em] leading-none" aria-hidden="true"> | |
| {state.icon} | |
| </span> | |
| )} | |
| {/* Long-press progress: when it fills, the index is set */} | |
| {pressed && ( | |
| <span | |
| className={`absolute inset-x-0 bottom-0 h-1.5 ${longPressed ? 'bg-hmi-text' : 'bg-hmi-accent hmi-press-progress'}`} | |
| style={{ animationDuration: `${LONG_PRESS_MS}ms` }} | |
| aria-hidden="true" | |
| /> | |
| )} | |
| </button> | |
| ); | |
| })} | |
| </div> | |
| </div> | |
| <div className="border-t border-hmi-line px-4 py-2 text-sm text-hmi-muted"> | |
| <span className="font-semibold text-hmi-text">Tap:</span> ignore / undo | |
| <span className="mx-3 text-hmi-line">|</span> | |
| <span className="font-semibold text-hmi-text">Long-press:</span> set index | |
| </div> | |
| </div> | |
| ); | |
| }; | |
| export default ScanTrace; | |