-
-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathSimulatorCanvas.tsx
More file actions
3011 lines (2813 loc) · 122 KB
/
SimulatorCanvas.tsx
File metadata and controls
3011 lines (2813 loc) · 122 KB
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useSimulatorStore, getEsp32Bridge } from '../../store/useSimulatorStore';
import { useElectricalStore } from '../../store/useElectricalStore';
import React, { useEffect, useState, useRef, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Undo2, Redo2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { ESP32_ADC_PIN_MAP } from '../velxio-components/Esp32Element';
import { ComponentPickerModal } from '../ComponentPickerModal';
import { ComponentPropertyDialog } from './ComponentPropertyDialog';
import { CustomChipDialog } from '../customChips/CustomChipDialog';
import { SensorControlPanel } from './SensorControlPanel';
import { SENSOR_CONTROLS } from '../../simulation/sensorControlConfig';
import { DynamicComponent, createComponentFromMetadata } from '../DynamicComponent';
import { InstrumentComponent } from '../components-instruments/InstrumentComponent';
import { ComponentRegistry } from '../../services/ComponentRegistry';
import { getTabSessionId } from '../../simulation/Esp32Bridge';
import { CameraToggle } from './CameraToggle';
import { WireLayer } from './WireLayer';
import type { SegmentHandle, WaypointHandle, AlignmentGuide } from './WireLayer';
import { ElectricalOverlay } from '../analog-ui/ElectricalOverlay';
import { BoardOnCanvas } from './BoardOnCanvas';
import { CanvasMinimap } from './CanvasMinimap';
import { PartSimulationRegistry } from '../../simulation/parts';
import { PROPERTY_CHANGE_EVENT, type PropertyChangeDetail } from '../../simulation/parts/partUtils';
import { isSpiceMapped } from '../../simulation/spice/componentToSpice';
import { PinOverlay } from './PinOverlay';
import { isBoardComponent, boardPinToNumber } from '../../utils/boardPinMapping';
import { autoWireColor, WIRE_KEY_COLORS } from '../../utils/wireUtils';
import {
findWireNearPoint,
findSegmentNearPoint,
getRenderedPoints,
getRenderedSegments,
moveSegment,
renderedToWaypoints,
renderedPointsToPath,
simplifyOrthogonalPath,
insertWaypointAtSegment,
collectAlignmentTargets,
snapToNearest,
} from '../../utils/wireHitDetection';
import { useIsCoarsePointer } from '../../utils/useTouchDevice';
import type { ComponentMetadata } from '../../types/component-metadata';
import type { BoardKind } from '../../types/board';
import { BOARD_KIND_LABELS } from '../../types/board';
import { isEsp32Family } from '../../types/boardOptions';
import { BoardOptionsModal } from './BoardOptionsModal';
import { useOscilloscopeStore } from '../../store/useOscilloscopeStore';
import {
trackSelectBoard,
trackAddComponent,
trackCreateWire,
trackToggleSerialMonitor,
} from '../../utils/analytics';
import { SelectionActionBar } from './SelectionActionBar';
import { WireModeBanner } from './WireModeBanner';
import { PinPickerDialog } from './PinPickerDialog';
import './SimulatorCanvas.css';
/** World-units of tolerance for alignment snap (scales with zoom). */
const ALIGN_SNAP_PX = 6;
/** Long-press duration for touch context menu (ms). */
const LONG_PRESS_MS = 500;
/** Max movement during long-press before it cancels (px). */
const LONG_PRESS_MOVE_TOLERANCE = 8;
/**
* Distance (px, screen) a touch must drift before a passthrough-to-
* wokwi-element touch is promoted to a component drag. Set just above
* normal tap jitter so accidental drags from a finger press are rare.
*/
const DRAG_PROMOTE_THRESHOLD_PX = 8;
/** Check if a board kind is an ESP32-family board. */
function isEsp32Kind(kind: BoardKind): boolean {
return (
kind.startsWith('esp32') ||
kind === 'xiao-esp32-s3' ||
kind === 'xiao-esp32-c3' ||
kind === 'arduino-nano-esp32' ||
kind === 'aitewinrobot-esp32c3-supermini' ||
kind === 'esp32-cam' ||
kind === 'wemos-lolin32-lite' ||
kind === 'esp32-devkit-c-v4'
);
}
interface SimulatorCanvasProps {
/**
* Optional DOM element to portal the canvas header (board selector,
* Serial/Scope toggles, zoom controls, Add component button) into. When
* provided, the header renders into the slot instead of in place — used by
* EditorPage to merge it with the editor toolbar into a single full-width
* top bar that doesn't reflow when the editor/canvas splitter moves.
*/
headerSlot?: HTMLElement | null;
}
export const SimulatorCanvas = ({ headerSlot }: SimulatorCanvasProps = {}) => {
const { t } = useTranslation();
const isTouchDevice = useIsCoarsePointer();
// Mirror to a ref so the long-lived touch handler effect (deps deliberately
// narrow to avoid rebinding listeners on every render) can read the latest
// value without listing it as a dep.
const isTouchDeviceRef = useRef(isTouchDevice);
isTouchDeviceRef.current = isTouchDevice;
const {
boards,
activeBoardId,
setBoardPosition,
addBoard,
components,
running,
pinManager,
initSimulator,
updateComponentState,
removeBoard,
updateBoard,
updateComponent,
serialMonitorOpen,
toggleSerialMonitor,
} = useSimulatorStore();
// `addComponent` / `removeComponent` / `removeWire` are no longer used here —
// every user-initiated mutation routes through the record* actions below
// so it can be undone. Raw mutators are still available for transient
// operations (e.g. drag preview frames) but those don't live in this file.
// Active board (for WiFi/BLE status display)
const activeBoard = boards.find((b) => b.id === activeBoardId) ?? null;
// Legacy derived values for components that still use them
const boardType = useSimulatorStore((s) => s.boardType);
const boardPosition = useSimulatorStore((s) => s.boardPosition);
// Wire management from store
const startWireCreation = useSimulatorStore((s) => s.startWireCreation);
const updateWireInProgress = useSimulatorStore((s) => s.updateWireInProgress);
const addWireWaypoint = useSimulatorStore((s) => s.addWireWaypoint);
const setWireInProgressColor = useSimulatorStore((s) => s.setWireInProgressColor);
const finishWireCreation = useSimulatorStore((s) => s.finishWireCreation);
const cancelWireCreation = useSimulatorStore((s) => s.cancelWireCreation);
const wireInProgress = useSimulatorStore((s) => s.wireInProgress);
const recalculateAllWirePositions = useSimulatorStore((s) => s.recalculateAllWirePositions);
const selectedWireId = useSimulatorStore((s) => s.selectedWireId);
const setSelectedWire = useSimulatorStore((s) => s.setSelectedWire);
const updateWire = useSimulatorStore((s) => s.updateWire);
const wires = useSimulatorStore((s) => s.wires);
// Recorded canvas actions — these wrap the raw mutators above with an
// undoable CanvasCommand. Use these at the *commit* point of a user
// interaction (drag-end, click finish, picker confirm); use the raw
// mutators for transient state during the interaction (drag preview).
const recordAddComponent = useSimulatorStore((s) => s.recordAddComponent);
const recordRemoveComponent = useSimulatorStore((s) => s.recordRemoveComponent);
const recordMove = useSimulatorStore((s) => s.recordMove);
const recordRotate = useSimulatorStore((s) => s.recordRotate);
const recordSetProperty = useSimulatorStore((s) => s.recordSetProperty);
const recordRemoveWire = useSimulatorStore((s) => s.recordRemoveWire);
// Subscribe to history shape so the undo/redo buttons reactively
// enable/disable and their tooltips reflect the next command.
const history = useSimulatorStore((s) => s.history);
const historyIndex = useSimulatorStore((s) => s.historyIndex);
const undo = useSimulatorStore((s) => s.undo);
const redo = useSimulatorStore((s) => s.redo);
// Oscilloscope
const oscilloscopeOpen = useOscilloscopeStore((s) => s.open);
const toggleOscilloscope = useOscilloscopeStore((s) => s.toggleOscilloscope);
// ESP32 crash notification
const esp32CrashBoardId = useSimulatorStore((s) => s.esp32CrashBoardId);
const dismissEsp32Crash = useSimulatorStore((s) => s.dismissEsp32Crash);
// Component picker modal
const [showComponentPicker, setShowComponentPicker] = useState(false);
const [registry] = useState(() => ComponentRegistry.getInstance());
const [registryLoaded, setRegistryLoaded] = useState(registry.isLoaded);
// Wait for registry to finish loading before rendering components
useEffect(() => {
if (!registryLoaded) {
registry.loadPromise.then(() => setRegistryLoaded(true));
}
}, [registry, registryLoaded]);
// Component selection
const [selectedComponentId, setSelectedComponentId] = useState<string | null>(null);
// Hover tracking — drives the conditional pin overlay so the canvas isn't
// permanently covered in pin chips. Pins show for the hovered/selected
// component or board, plus all elements while a wire is in progress.
const [hoveredComponentId, setHoveredComponentId] = useState<string | null>(null);
const [hoveredBoardId, setHoveredBoardId] = useState<string | null>(null);
// Touch-friendly pin picker — shown when the user taps a component or board
// body (not a tiny pin overlay) and we want to let them pick a pin from a
// list. `kind` distinguishes board vs component so we can pull the right
// metadata for the dialog title.
const [pinPicker, setPinPicker] = useState<
{ kind: 'component' | 'board'; targetId: string } | null
>(null);
// Component property dialog
const [showPropertyDialog, setShowPropertyDialog] = useState(false);
const [propertyDialogComponentId, setPropertyDialogComponentId] = useState<string | null>(null);
/** When non-null, the Custom Chip designer dialog is open for this component. */
const [customChipComponentId, setCustomChipComponentId] = useState<string | null>(null);
const [propertyDialogPosition, setPropertyDialogPosition] = useState({ x: 0, y: 0 });
// Sensor control panel (shown instead of property dialog for sensor components during simulation)
const [sensorControlComponentId, setSensorControlComponentId] = useState<string | null>(null);
const [sensorControlMetadataId, setSensorControlMetadataId] = useState<string | null>(null);
// Board built-in LED states (pin 13 for AVR, GPIO25 for RP2040, etc.)
// Tracks directly from pinManager — independent of any led-builtin component.
const [boardLedStates, setBoardLedStates] = useState<Record<string, boolean>>({});
// Board context menu (right-click)
const [boardContextMenu, setBoardContextMenu] = useState<{
boardId: string;
x: number;
y: number;
} | null>(null);
// Board removal confirmation dialog
const [boardToRemove, setBoardToRemove] = useState<string | null>(null);
// Board Options modal — id of the board whose options are being edited.
const [boardOptionsModalFor, setBoardOptionsModalFor] = useState<string | null>(null);
// Click vs drag detection
const [clickStartTime, setClickStartTime] = useState<number>(0);
const [clickStartPos, setClickStartPos] = useState({ x: 0, y: 0 });
// Component dragging state
const [draggedComponentId, setDraggedComponentId] = useState<string | null>(null);
// Captures (x, y) of the dragged component at mousedown so a drag-end
// can record the diff as a single undoable Move. Boards are intentionally
// skipped — board moves don't go through component history.
const dragStartPosRef = useRef<{ x: number; y: number } | null>(null);
const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
// Canvas ref for coordinate calculations
const canvasRef = useRef<HTMLDivElement>(null);
// Pan & zoom state
const [pan, setPan] = useState({ x: 0, y: 0 });
const [zoom, setZoom] = useState(1);
// Use refs during active pan to avoid setState lag
const isPanningRef = useRef(false);
const panStartRef = useRef({ mouseX: 0, mouseY: 0, panX: 0, panY: 0 });
const panRef = useRef({ x: 0, y: 0 });
const zoomRef = useRef(1);
// Board-less SPICE circuits (analog / digital examples with no MCU on
// the canvas) have no concept of a board to "start", so `running` is
// always false. But the simulation IS effectively live the moment the
// engine has solved at least once — switches and buttons should toggle
// their own state on click instead of opening the property dialog.
// We treat board-less + un-paused as "interaction-running" so the same
// gating logic that suppresses the dialog for MCU-running mode also
// covers board-less circuits.
const electricalPaused = useElectricalStore((s) => s.paused);
const interactionRunning = running || (boards.length === 0 && !electricalPaused);
// Refs that mirror state/props for use inside touch event closures
// (touch listeners are added imperatively and can't access current React state)
const runningRef = useRef(running);
runningRef.current = running;
const interactionRunningRef = useRef(interactionRunning);
interactionRunningRef.current = interactionRunning;
const componentsRef = useRef(components);
componentsRef.current = components;
const boardPositionRef = useRef(boardPosition);
boardPositionRef.current = boardPosition;
const boardsRef = useRef(boards);
boardsRef.current = boards;
// Wire interaction state (canvas-level hit detection — bypasses SVG pointer-events issues)
const [hoveredWireId, setHoveredWireId] = useState<string | null>(null);
const [segmentDragPreview, setSegmentDragPreview] = useState<{
wireId: string;
overridePath: string;
} | null>(null);
const segmentDragRef = useRef<{
wireId: string;
segIndex: number;
axis: 'horizontal' | 'vertical';
renderedPts: { x: number; y: number }[];
isDragging: boolean;
} | null>(null);
/** Active waypoint drag (free 2D move of a single bend point). */
const waypointDragRef = useRef<{
wireId: string;
waypointIndex: number;
originalWaypoints: { x: number; y: number }[];
isDragging: boolean;
} | null>(null);
const [waypointDragPreview, setWaypointDragPreview] = useState<{
wireId: string;
waypoints: { x: number; y: number }[];
} | null>(null);
const [alignmentGuides, setAlignmentGuides] = useState<AlignmentGuide[]>([]);
/** Set to true during mouseup if a segment/waypoint drag committed, so onClick can skip selection. */
const segmentDragJustCommittedRef = useRef(false);
const wiresRef = useRef(wires);
wiresRef.current = wires;
// Compute midpoint handles for the selected wire's segments
const segmentHandles = React.useMemo<SegmentHandle[]>(() => {
if (!selectedWireId) return [];
const wire = wires.find((w) => w.id === selectedWireId);
if (!wire) return [];
return getRenderedSegments(wire).map((seg, i) => ({
segIndex: i,
axis: seg.axis,
mx: (seg.x1 + seg.x2) / 2,
my: (seg.y1 + seg.y2) / 2,
}));
}, [selectedWireId, wires]);
// Compute bend-point handles (one per waypoint) for the selected wire
const waypointHandles = React.useMemo<WaypointHandle[]>(() => {
if (!selectedWireId) return [];
const wire = wires.find((w) => w.id === selectedWireId);
if (!wire) return [];
// While the user is dragging a waypoint, render handles at the live preview
// positions so the dot tracks the cursor instead of jumping at commit.
const activeDrag = waypointDragPreview?.wireId === wire.id ? waypointDragPreview : null;
const wps = activeDrag ? activeDrag.waypoints : (wire.waypoints ?? []);
return wps.map((wp, i) => ({ index: i, x: wp.x, y: wp.y }));
}, [selectedWireId, wires, waypointDragPreview]);
// Touch-specific state refs (for single-finger drag and pinch-to-zoom)
const touchDraggedComponentIdRef = useRef<string | null>(null);
const touchDragOffsetRef = useRef({ x: 0, y: 0 });
const touchClickStartTimeRef = useRef(0);
const touchClickStartPosRef = useRef({ x: 0, y: 0 });
const pinchStartDistRef = useRef(0);
const pinchStartZoomRef = useRef(1);
const pinchStartMidRef = useRef({ x: 0, y: 0 });
const pinchStartPanRef = useRef({ x: 0, y: 0 });
// Refs for touch-based wire creation, selection, and interactive passthrough
const wireInProgressRef = useRef(wireInProgress);
wireInProgressRef.current = wireInProgress;
const selectedWireIdRef = useRef(selectedWireId);
selectedWireIdRef.current = selectedWireId;
const touchPassthroughRef = useRef(false);
// While `touchPassthroughRef` is true (touch let through to an interactive
// wokwi-element while the simulation runs), we still remember which
// component the touch started on. If the finger drifts past
// DRAG_PROMOTE_THRESHOLD_PX, we cancel the passthrough and start a real
// drag — so the user can rearrange interactive parts live without first
// pausing the simulation.
const pendingTouchDragRef = useRef<
{ componentId: string; startX: number; startY: number } | null
>(null);
const touchOnPinRef = useRef(false);
const lastTapTimeRef = useRef(0);
// Long-press (touch-equivalent of right-click) — opens board context menu on
// touch devices since right-click isn't available there.
const longPressTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const longPressFiredRef = useRef(false);
const cancelLongPress = useCallback(() => {
if (longPressTimerRef.current) {
clearTimeout(longPressTimerRef.current);
longPressTimerRef.current = null;
}
}, []);
// Convert viewport coords to world (canvas) coords
const toWorld = useCallback((screenX: number, screenY: number) => {
const rect = canvasRef.current?.getBoundingClientRect();
if (!rect) return { x: screenX, y: screenY };
return {
x: (screenX - rect.left - panRef.current.x) / zoomRef.current,
y: (screenY - rect.top - panRef.current.y) / zoomRef.current,
};
}, []);
// Initialize simulator on mount
useEffect(() => {
initSimulator();
}, [initSimulator]);
// Runtime parts (pots, switches, sensor panels) emit
// `velxio:property-change` instead of writing the store directly — one
// listener here routes every mutation through `updateComponent()`, which
// is the same path the Property Dialog uses. Keeps parts decoupled from
// Zustand and guarantees the SPICE netlist memo invalidates on every
// user-driven property change.
useEffect(() => {
const onPropertyChange = (evt: Event) => {
const { componentId, propName, value } = (evt as CustomEvent<PropertyChangeDetail>).detail;
const state = useSimulatorStore.getState();
const comp = state.components.find((c) => c.id === componentId);
if (!comp) return;
if (String(comp.properties?.[propName]) === String(value)) return;
state.updateComponent(componentId, {
properties: { ...comp.properties, [propName]: value },
});
};
window.addEventListener(PROPERTY_CHANGE_EVENT, onPropertyChange);
return () => window.removeEventListener(PROPERTY_CHANGE_EVENT, onPropertyChange);
}, []);
// Auto-start/stop Pi bridges when simulation state changes
const startBoard = useSimulatorStore((s) => s.startBoard);
const stopBoard = useSimulatorStore((s) => s.stopBoard);
useEffect(() => {
const remoteBoards = boards.filter(
(b) =>
b.boardKind === 'raspberry-pi-3' ||
b.boardKind === 'esp32' ||
b.boardKind === 'esp32-s3' ||
b.boardKind === 'esp32-c3',
);
remoteBoards.forEach((b) => {
if (running && !b.running) startBoard(b.id);
else if (!running && b.running) stopBoard(b.id);
});
}, [running, boards, startBoard, stopBoard]);
// Attach wheel listener as non-passive so preventDefault() works
useEffect(() => {
const el = canvasRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
e.preventDefault();
const rect = el.getBoundingClientRect();
const factor = e.deltaY < 0 ? 1.1 : 0.9;
const newZoom = Math.min(5, Math.max(0.1, zoomRef.current * factor));
const mx = e.clientX - rect.left;
const my = e.clientY - rect.top;
const worldX = (mx - panRef.current.x) / zoomRef.current;
const worldY = (my - panRef.current.y) / zoomRef.current;
const newPan = { x: mx - worldX * newZoom, y: my - worldY * newZoom };
zoomRef.current = newZoom;
panRef.current = newPan;
setZoom(newZoom);
setPan(newPan);
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
// Attach touch listeners as non-passive so preventDefault() works, enabling
// single-finger pan, component drag, wire creation/selection, and two-finger pinch-to-zoom.
useEffect(() => {
const el = canvasRef.current;
if (!el) return;
const onTouchStart = (e: TouchEvent) => {
// Reset per-gesture flags
touchOnPinRef.current = false;
touchPassthroughRef.current = false;
pendingTouchDragRef.current = null;
pinchStartDistRef.current = 0;
if (e.touches.length === 2) {
e.preventDefault();
// Cancel wire in progress and any pending long-press on two-finger gesture
cancelLongPress();
if (wireInProgressRef.current) {
useSimulatorStore.getState().cancelWireCreation();
}
// Cancel any active drag/pan and prepare zoom
isPanningRef.current = false;
touchDraggedComponentIdRef.current = null;
const dx = e.touches[0].clientX - e.touches[1].clientX;
const dy = e.touches[0].clientY - e.touches[1].clientY;
pinchStartDistRef.current = Math.sqrt(dx * dx + dy * dy);
pinchStartZoomRef.current = zoomRef.current;
pinchStartPanRef.current = { ...panRef.current };
const rect = el.getBoundingClientRect();
pinchStartMidRef.current = {
x: (e.touches[0].clientX + e.touches[1].clientX) / 2 - rect.left,
y: (e.touches[0].clientY + e.touches[1].clientY) / 2 - rect.top,
};
return;
}
if (e.touches.length !== 1) return;
const touch = e.touches[0];
// Identify what element was touched
const target = document.elementFromPoint(touch.clientX, touch.clientY);
// ── 1. Pin overlay → let pin's onTouchEnd React handler call handlePinClick ──
if (target?.closest('[data-pin-overlay]')) {
e.preventDefault();
touchOnPinRef.current = true;
return;
}
// ── 1b. Wire segment/waypoint handle → let WireLayer's React handler claim the drag.
// We must skip the canvas-level pan/drag setup so the handle drag works in isolation.
if (target?.closest('[data-wire-handle]')) {
e.preventDefault();
touchPassthroughRef.current = true;
return;
}
// ── 2. Interactive web component during simulation → let browser synthesize mouse events ──
// (potentiometer knobs, button presses, etc. need mousedown/mouseup synthesis)
// touch-action:none on .canvas-content already prevents browser scroll/zoom.
// Board-less SPICE circuits piggy-back on the same path so a tap on
// a slide-switch reaches the wokwi element and triggers its toggle.
// We still remember the starting position + component id so that if
// the finger drifts past DRAG_PROMOTE_THRESHOLD_PX onTouchMove can
// cancel the passthrough and start a real drag, letting the user
// rearrange interactive parts live without pausing the simulation.
if (interactionRunningRef.current) {
const webComp = target?.closest('.web-component-container');
if (webComp) {
touchPassthroughRef.current = true;
const componentWrapper = target?.closest('[data-component-id]') as HTMLElement | null;
const cid = componentWrapper?.getAttribute('data-component-id') || null;
pendingTouchDragRef.current = cid
? { componentId: cid, startX: touch.clientX, startY: touch.clientY }
: null;
// Don't preventDefault → browser synthesizes mouse events for the component
return;
}
}
e.preventDefault();
touchClickStartTimeRef.current = Date.now();
touchClickStartPosRef.current = { x: touch.clientX, y: touch.clientY };
// ── 3. Wire in progress → track for waypoint, update preview ──
if (wireInProgressRef.current) {
const world = toWorld(touch.clientX, touch.clientY);
useSimulatorStore.getState().updateWireInProgress(world.x, world.y);
// Don't start pan/drag — let touchmove update wire preview, touchend add waypoint
return;
}
// ── 4. Component detection ──
const componentWrapper = target?.closest('[data-component-id]') as HTMLElement | null;
const boardOverlay = target?.closest('[data-board-overlay]') as HTMLElement | null;
if (componentWrapper) {
const componentId = componentWrapper.getAttribute('data-component-id');
if (componentId) {
const component = componentsRef.current.find((c) => c.id === componentId);
if (component) {
const world = toWorld(touch.clientX, touch.clientY);
touchDraggedComponentIdRef.current = componentId;
touchDragOffsetRef.current = {
x: world.x - component.x,
y: world.y - component.y,
};
setSelectedComponentId(componentId);
}
}
} else if (boardOverlay && !runningRef.current) {
// ── 5. Board overlay: use multi-board path ──
const boardId = boardOverlay.getAttribute('data-board-id');
const storeBoards = useSimulatorStore.getState().boards;
const boardInstance = boardId ? storeBoards.find((b) => b.id === boardId) : null;
if (boardInstance) {
const world = toWorld(touch.clientX, touch.clientY);
touchDraggedComponentIdRef.current = `__board__:${boardId}`;
touchDragOffsetRef.current = {
x: world.x - boardInstance.x,
y: world.y - boardInstance.y,
};
// Schedule long-press to open the board context menu (touch
// equivalent of right-click). Cancelled if the user moves enough
// to start a drag, ends touch quickly, or starts a pinch.
longPressFiredRef.current = false;
cancelLongPress();
const pressX = touch.clientX;
const pressY = touch.clientY;
const targetBoardId = boardInstance.id;
longPressTimerRef.current = setTimeout(() => {
longPressFiredRef.current = true;
// Cancel the implicit drag so finger lifting after the menu opens
// doesn't also fire the short-tap "set active board" branch.
touchDraggedComponentIdRef.current = null;
setBoardContextMenu({ boardId: targetBoardId, x: pressX, y: pressY });
}, LONG_PRESS_MS);
} else {
// Fallback to legacy single board
const board = boardPositionRef.current;
const world = toWorld(touch.clientX, touch.clientY);
touchDraggedComponentIdRef.current = '__board__';
touchDragOffsetRef.current = {
x: world.x - board.x,
y: world.y - board.y,
};
}
} else {
// ── 6. Empty canvas → start pan ──
isPanningRef.current = true;
panStartRef.current = {
mouseX: touch.clientX,
mouseY: touch.clientY,
panX: panRef.current.x,
panY: panRef.current.y,
};
}
};
const onTouchMove = (e: TouchEvent) => {
// Let interactive components handle their own touch (potentiometer drag, etc.)
// — UNLESS the finger has drifted past DRAG_PROMOTE_THRESHOLD_PX,
// in which case we cancel the passthrough and start a real component
// drag. Lets users rearrange parts during simulation without pausing.
if (touchPassthroughRef.current) {
const pending = pendingTouchDragRef.current;
if (pending && e.touches.length === 1) {
const t = e.touches[0];
const dx = t.clientX - pending.startX;
const dy = t.clientY - pending.startY;
if (dx * dx + dy * dy > DRAG_PROMOTE_THRESHOLD_PX * DRAG_PROMOTE_THRESHOLD_PX) {
const component = componentsRef.current.find((c) => c.id === pending.componentId);
if (component) {
const world = toWorld(t.clientX, t.clientY);
touchDraggedComponentIdRef.current = pending.componentId;
touchDragOffsetRef.current = {
x: world.x - component.x,
y: world.y - component.y,
};
// Snapshot the drag start position so touchend can fold the
// move into a single undoable Move command, mirroring the
// mouse-drag path.
dragStartPosRef.current = { x: component.x, y: component.y };
touchClickStartTimeRef.current = Date.now();
touchClickStartPosRef.current = { x: t.clientX, y: t.clientY };
// Release any pending press the wokwi-element registered when
// the browser synthesized the initial mousedown at touchstart.
// Without this the interactive part (button, switch knob) stays
// visually held until the user taps it again.
const target = document.elementFromPoint(pending.startX, pending.startY);
if (target) {
target.dispatchEvent(
new MouseEvent('mouseup', {
bubbles: true,
cancelable: true,
clientX: pending.startX,
clientY: pending.startY,
}),
);
target.dispatchEvent(
new MouseEvent('mouseleave', { bubbles: false }),
);
}
}
touchPassthroughRef.current = false;
pendingTouchDragRef.current = null;
e.preventDefault();
// Fall through to normal touch-drag handling below.
} else {
return;
}
} else {
return;
}
}
// Pin touch: no move processing needed
if (touchOnPinRef.current) {
e.preventDefault();
return;
}
// Cancel pending long-press if the finger drifts beyond tolerance.
if (longPressTimerRef.current && e.touches.length === 1) {
const t = e.touches[0];
const dx = t.clientX - touchClickStartPosRef.current.x;
const dy = t.clientY - touchClickStartPosRef.current.y;
if (dx * dx + dy * dy > LONG_PRESS_MOVE_TOLERANCE * LONG_PRESS_MOVE_TOLERANCE) {
cancelLongPress();
}
}
e.preventDefault();
if (e.touches.length === 2 && pinchStartDistRef.current > 0) {
// ── Two-finger pinch: update zoom ──
const dx = e.touches[0].clientX - e.touches[1].clientX;
const dy = e.touches[0].clientY - e.touches[1].clientY;
const dist = Math.sqrt(dx * dx + dy * dy);
const scale = dist / pinchStartDistRef.current;
const newZoom = Math.min(5, Math.max(0.1, pinchStartZoomRef.current * scale));
const mid = pinchStartMidRef.current;
const startPan = pinchStartPanRef.current;
const startZoom = pinchStartZoomRef.current;
const worldX = (mid.x - startPan.x) / startZoom;
const worldY = (mid.y - startPan.y) / startZoom;
const newPan = {
x: mid.x - worldX * newZoom,
y: mid.y - worldY * newZoom,
};
zoomRef.current = newZoom;
panRef.current = newPan;
const worldEl = el.querySelector('.canvas-world') as HTMLElement | null;
if (worldEl) {
worldEl.style.transform = `translate(${newPan.x}px, ${newPan.y}px) scale(${newZoom})`;
}
return;
}
if (e.touches.length !== 1) return;
const touch = e.touches[0];
// ── Segment drag (wire editing) via touch ──
if (segmentDragRef.current) {
const world = toWorld(touch.clientX, touch.clientY);
const sd = segmentDragRef.current;
sd.isDragging = true;
const newValue = sd.axis === 'horizontal' ? world.y : world.x;
const newPts = moveSegment(sd.renderedPts, sd.segIndex, sd.axis, newValue);
const overridePath = renderedPointsToPath(newPts);
setSegmentDragPreview({ wireId: sd.wireId, overridePath });
return;
}
// ── Wire preview: update position as finger moves ──
if (
wireInProgressRef.current &&
!isPanningRef.current &&
!touchDraggedComponentIdRef.current
) {
const world = toWorld(touch.clientX, touch.clientY);
useSimulatorStore.getState().updateWireInProgress(world.x, world.y);
return;
}
if (isPanningRef.current) {
// ── Single finger pan ──
const dx = touch.clientX - panStartRef.current.mouseX;
const dy = touch.clientY - panStartRef.current.mouseY;
const newPan = {
x: panStartRef.current.panX + dx,
y: panStartRef.current.panY + dy,
};
panRef.current = newPan;
const worldEl = el.querySelector('.canvas-world') as HTMLElement | null;
if (worldEl) {
worldEl.style.transform = `translate(${newPan.x}px, ${newPan.y}px) scale(${zoomRef.current})`;
}
} else if (touchDraggedComponentIdRef.current) {
// ── Single finger component/board drag ──
const world = toWorld(touch.clientX, touch.clientY);
const touchId = touchDraggedComponentIdRef.current;
if (touchId && touchId.startsWith('__board__:')) {
const boardId = touchId.slice('__board__:'.length);
setBoardPosition(
{
x: world.x - touchDragOffsetRef.current.x,
y: world.y - touchDragOffsetRef.current.y,
},
boardId,
);
} else if (touchId === '__board__') {
setBoardPosition({
x: world.x - touchDragOffsetRef.current.x,
y: world.y - touchDragOffsetRef.current.y,
});
} else {
updateComponent(touchDraggedComponentIdRef.current!, {
x: world.x - touchDragOffsetRef.current.x,
y: world.y - touchDragOffsetRef.current.y,
} as any);
}
}
};
const onTouchEnd = (e: TouchEvent) => {
// Always clear any pending long-press timer on touch release.
cancelLongPress();
// If the long-press fired and opened a context menu, swallow this
// touchend so we don't also fire the short-tap action below.
if (longPressFiredRef.current) {
longPressFiredRef.current = false;
touchDraggedComponentIdRef.current = null;
e.preventDefault();
return;
}
// Let interactive components handle their own touch
if (touchPassthroughRef.current) {
touchPassthroughRef.current = false;
pendingTouchDragRef.current = null;
return;
}
// Pin touch: let pin's onTouchEnd React handler deal with it
if (touchOnPinRef.current) {
touchOnPinRef.current = false;
e.preventDefault();
return;
}
e.preventDefault();
// ── Finish pinch zoom: commit values to React state ──
if (pinchStartDistRef.current > 0 && e.touches.length < 2) {
setZoom(zoomRef.current);
setPan({ ...panRef.current });
pinchStartDistRef.current = 0;
}
if (e.touches.length > 0) return; // Still fingers on screen
// ── Finish segment drag (wire editing) via touch ──
if (segmentDragRef.current) {
const sd = segmentDragRef.current;
if (sd.isDragging) {
segmentDragJustCommittedRef.current = true;
const changed = e.changedTouches[0];
if (changed) {
const world = toWorld(changed.clientX, changed.clientY);
const newValue = sd.axis === 'horizontal' ? world.y : world.x;
const newPts = moveSegment(sd.renderedPts, sd.segIndex, sd.axis, newValue);
updateWire(sd.wireId, { waypoints: renderedToWaypoints(newPts) });
}
}
segmentDragRef.current = null;
setSegmentDragPreview(null);
return;
}
// ── Finish panning ──
let wasPanning = false;
if (isPanningRef.current) {
isPanningRef.current = false;
setPan({ ...panRef.current });
wasPanning = true;
// Don't return — fall through so short taps can select wires
}
const changed = e.changedTouches[0];
if (!changed) return;
const elapsed = Date.now() - touchClickStartTimeRef.current;
const dx = changed.clientX - touchClickStartPosRef.current.x;
const dy = changed.clientY - touchClickStartPosRef.current.y;
const dist = Math.sqrt(dx * dx + dy * dy);
const isShortTap = dist < 20 && elapsed < 400;
// If we actually panned (moved significantly), don't process as tap
if (wasPanning && !isShortTap) return;
// ── Finish component/board drag ──
if (touchDraggedComponentIdRef.current) {
const touchId = touchDraggedComponentIdRef.current;
if (isShortTap) {
if (touchId.startsWith('__board__:')) {
// Short tap on board: first tap → make it active (so pins show);
// tap again on the same board → open the touch-friendly pin
// picker so the user can start a wire by name without poking at
// a tiny pin overlay with a finger.
const boardId = touchId.slice('__board__:'.length);
const state = useSimulatorStore.getState();
if (state.activeBoardId === boardId) {
setPinPicker({ kind: 'board', targetId: boardId });
} else {
state.setActiveBoardId(boardId);
}
} else if (touchId !== '__board__') {
// Short tap on component → open property dialog or sensor panel.
// While the simulator is running (MCU or board-less SPICE),
// components stay interactive — only sensor panels may open;
// property editing is disabled so the tap reaches the
// wokwi-element underneath and toggles it.
const component = componentsRef.current.find((c) => c.id === touchId);
if (component) {
if (interactionRunningRef.current) {
if (SENSOR_CONTROLS[component.metadataId] !== undefined) {
setSensorControlComponentId(touchId);
setSensorControlMetadataId(component.metadataId);
}
} else {
setPropertyDialogComponentId(touchId);
setPropertyDialogPosition({
x: component.x * zoomRef.current + panRef.current.x,
y: component.y * zoomRef.current + panRef.current.y,
});
setShowPropertyDialog(true);
}
}
}
}
recalculateAllWirePositions();
touchDraggedComponentIdRef.current = null;
return;
}
// ── Wire in progress: short tap adds waypoint OR opens pin picker ──
// If the user tapped on a component / board body (not a pin overlay),
// open the touch-friendly pin picker so they can finish the wire by
// tapping a pin name from a list — far more reliable than poking at a
// 12px overlay with a fingertip. Empty-canvas taps still drop waypoints.
if (wireInProgressRef.current) {
if (isShortTap) {
const tapTarget = document.elementFromPoint(changed.clientX, changed.clientY);
const componentWrapper = tapTarget?.closest('[data-component-id]');
const boardOverlay = tapTarget?.closest('[data-board-overlay]');
if (componentWrapper) {
const id = componentWrapper.getAttribute('data-component-id');
if (id) setPinPicker({ kind: 'component', targetId: id });
} else if (boardOverlay) {
const id = boardOverlay.getAttribute('data-board-id');
if (id) setPinPicker({ kind: 'board', targetId: id });
} else {
const world = toWorld(changed.clientX, changed.clientY);
useSimulatorStore.getState().addWireWaypoint(world.x, world.y);
}
}
return;
}
// ── Short tap on empty canvas: wire selection + double-tap inserts waypoint ──
if (isShortTap) {
const now = Date.now();
const world = toWorld(changed.clientX, changed.clientY);
const baseThreshold = isTouchDeviceRef.current ? 20 : 8;
const threshold = baseThreshold / zoomRef.current;
const wire = findWireNearPoint(wiresRef.current, world.x, world.y, threshold);
// Double-tap on a wire → insert draggable waypoint at the tap location
const timeSinceLastTap = now - lastTapTimeRef.current;
if (timeSinceLastTap < 350 && wire) {
const seg = findSegmentNearPoint(wire, world.x, world.y, threshold);
if (seg) {
const newWaypoints = insertWaypointAtSegment(
wire.waypoints ?? [],
seg,
world.x,
world.y,
);
useSimulatorStore.getState().updateWire(wire.id, { waypoints: newWaypoints });
useSimulatorStore.getState().setSelectedWire(wire.id);
}
lastTapTimeRef.current = 0;
return;
}
lastTapTimeRef.current = now;
if (wire) {
const curr = selectedWireIdRef.current;
useSimulatorStore.getState().setSelectedWire(curr === wire.id ? null : wire.id);
} else {
useSimulatorStore.getState().setSelectedWire(null);
setSelectedComponentId(null);
}
}
};
el.addEventListener('touchstart', onTouchStart, { passive: false });
el.addEventListener('touchmove', onTouchMove, { passive: false });
el.addEventListener('touchend', onTouchEnd, { passive: false });
return () => {
el.removeEventListener('touchstart', onTouchStart);
el.removeEventListener('touchmove', onTouchMove);
el.removeEventListener('touchend', onTouchEnd);
cancelLongPress();
};
}, [toWorld, setBoardPosition, updateComponent, recalculateAllWirePositions, cancelLongPress]);
// Recalculate wire positions after web components initialize their pinInfo
useEffect(() => {
const timer = setTimeout(() => {
recalculateAllWirePositions();
}, 500);
return () => clearTimeout(timer);
}, [recalculateAllWirePositions]);
// Connect components to pin manager
useEffect(() => {
const unsubscribers: (() => void)[] = [];
// Returns true if the component has at least one wire connected to a board
// GND or power-rail pin (boardPinToNumber returns -1 for these).
// Used to block output components from activating without a ground connection.
const componentHasGndWire = (component: any): boolean =>
wires.some((w) => {
const isSelfStart = w.start.componentId === component.id;
const isSelfEnd = w.end.componentId === component.id;
if (!isSelfStart && !isSelfEnd) return false;
const otherEndpoint = isSelfStart ? w.end : w.start;
if (!isBoardComponent(otherEndpoint.componentId)) return false;
const boardInstance = boards.find((b) => b.id === otherEndpoint.componentId);
const lookupKey = boardInstance ? boardInstance.boardKind : otherEndpoint.componentId;
return boardPinToNumber(lookupKey, otherEndpoint.pinName) === -1;
});
// Helper to add subscription