File size: 10,369 Bytes
aec3a91
fba4209
aec3a91
fba4209
aec3a91
 
 
 
 
 
 
6c68d01
aec3a91
 
 
 
 
 
 
6c68d01
aec3a91
6c68d01
 
 
 
 
aec3a91
 
 
fba4209
 
aec3a91
 
 
 
 
 
6c68d01
aec3a91
 
 
fba4209
6c68d01
fba4209
aec3a91
 
fba4209
 
 
aec3a91
 
 
6c68d01
aec3a91
 
 
 
 
 
 
 
 
 
 
 
fba4209
6c68d01
fba4209
 
 
 
aec3a91
 
 
 
 
fba4209
 
 
aec3a91
b225f7d
fba4209
 
 
aec3a91
fba4209
aec3a91
 
 
 
fba4209
aec3a91
6c68d01
aec3a91
 
 
fba4209
 
aec3a91
 
 
 
6c68d01
fba4209
aec3a91
 
fba4209
aec3a91
 
 
 
 
 
 
6c68d01
aec3a91
 
 
 
 
 
 
 
 
6c68d01
aec3a91
 
 
 
 
 
fba4209
aec3a91
 
 
6c68d01
aec3a91
6c68d01
fba4209
aec3a91
fba4209
aec3a91
 
 
 
 
fba4209
 
6c68d01
aec3a91
 
 
 
 
 
 
 
 
 
 
 
 
 
fba4209
 
aec3a91
 
 
6c68d01
aec3a91
 
 
 
 
 
 
 
 
 
fba4209
 
 
aec3a91
 
 
fba4209
aec3a91
fba4209
aec3a91
fba4209
aec3a91
 
 
fba4209
 
 
 
6c68d01
aec3a91
 
6c68d01
aec3a91
6c68d01
aec3a91
fba4209
aec3a91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fba4209
 
6c68d01
aec3a91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c68d01
aec3a91
 
 
 
 
 
 
 
 
 
 
 
 
6c68d01
aec3a91
 
 
 
 
 
 
 
 
 
 
fba4209
 
aec3a91
6c68d01
aec3a91
6c68d01
fba4209
 
 
 
 
 
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
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;