-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
795 lines (684 loc) · 26 KB
/
App.tsx
File metadata and controls
795 lines (684 loc) · 26 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
import React, { useState, useCallback, useEffect, useRef } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { Plus, Trash2, Save, FolderOpen, AlertTriangle, Undo2, Redo2, Sparkles } from 'lucide-react';
import { CircuitComponent, Wire, ComponentType, CircuitState, ICDefinition, Pin } from './types';
import { updateCircuitState } from './utils/circuitSolver';
import { generateCircuitBlueprint } from './utils/aiService';
import Sidebar from './components/Sidebar';
import Canvas from './components/Canvas';
import CreateICModal from './components/CreateICModal';
import AIChatModal from './components/AIChatModal';
const App: React.FC = () => {
const [circuit, setCircuit] = useState<CircuitState>({
components: [],
wires: [],
selection: [],
icDefinitions: []
});
// Undo/Redo History State
const [history, setHistory] = useState<{ past: CircuitState[]; future: CircuitState[] }>({
past: [],
future: []
});
// Clipboard State for Copy/Paste
const [clipboard, setClipboard] = useState<{
components: CircuitComponent[];
wires: Wire[];
} | null>(null);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isAIModalOpen, setIsAIModalOpen] = useState(false);
const [draggedItem, setDraggedItem] = useState<{ type: ComponentType | 'IC', icId?: string } | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [successMessage, setSuccessMessage] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
// Ref to store snapshot before drag starts
const dragStartSnapshotRef = useRef<CircuitState | null>(null);
// Ref to access latest circuit state in event handlers without re-binding listeners
const circuitRef = useRef(circuit);
useEffect(() => {
circuitRef.current = circuit;
}, [circuit]);
// Simulation Tick
useEffect(() => {
const interval = setInterval(() => {
setCircuit(prev => {
const newComponents = updateCircuitState(prev.components, prev.wires, prev.icDefinitions);
// We do NOT add simulation ticks to history
return { ...prev, components: newComponents };
});
}, 100); // 10Hz simulation rate
return () => clearInterval(interval);
}, []);
// Clear error message after 3 seconds
useEffect(() => {
if (errorMessage) {
const timer = setTimeout(() => setErrorMessage(null), 3000);
return () => clearTimeout(timer);
}
}, [errorMessage]);
useEffect(() => {
if (successMessage) {
const timer = setTimeout(() => setSuccessMessage(null), 4000);
return () => clearTimeout(timer);
}
}, [successMessage]);
// --- History Management ---
const addToHistory = useCallback((state: CircuitState) => {
setHistory(prev => {
const newPast = [...prev.past, state];
if (newPast.length > 30) newPast.shift(); // Limit history depth
return {
past: newPast,
future: [] // Clear future on new action
};
});
}, []);
const handleUndo = useCallback(() => {
setHistory(prev => {
if (prev.past.length === 0) return prev;
const previous = prev.past[prev.past.length - 1];
const newPast = prev.past.slice(0, -1);
// Update the main circuit state
setCircuit(previous);
return {
past: newPast,
future: [circuitRef.current, ...prev.future]
};
});
}, []);
const handleRedo = useCallback(() => {
setHistory(prev => {
if (prev.future.length === 0) return prev;
const next = prev.future[0];
const newFuture = prev.future.slice(1);
// Update the main circuit state
setCircuit(next);
return {
past: [...prev.past, circuitRef.current],
future: newFuture
};
});
}, []);
// --- Actions ---
const createComponentObject = (
id: string,
type: ComponentType,
x: number,
y: number,
icId?: string,
customLabel?: string
): CircuitComponent | null => {
let inputs: Pin[] = [];
let outputs: Pin[] = [];
let label: string = customLabel || type;
let state = {};
if (type === 'IC' && icId) {
const def = circuitRef.current.icDefinitions.find(d => d.id === icId);
if (!def) return null;
label = customLabel || def.name;
// Create pins based on definition
inputs = def.inputMap.map((m, i) => ({ id: uuidv4(), componentId: id, type: 'input', index: i, value: false, label: m.label }));
outputs = def.outputMap.map((m, i) => ({ id: uuidv4(), componentId: id, type: 'output', index: i, value: false, label: m.label }));
} else {
// Standard components
const createPin = (type: 'input' | 'output', index: number) => ({ id: uuidv4(), componentId: id, type, index, value: false });
if (['AND', 'OR', 'NAND', 'NOR', 'XOR'].includes(type)) {
inputs = [createPin('input', 0), createPin('input', 1)];
outputs = [createPin('output', 0)];
} else if (type === 'NOT') {
inputs = [createPin('input', 0)];
outputs = [createPin('output', 0)];
} else if (type === 'LEVER' || type === 'BUTTON') {
inputs = [];
outputs = [createPin('output', 0)];
label = customLabel || (type === 'LEVER' ? 'Input' : 'Btn');
state = { isOn: false, isPressed: false };
} else if (type === 'BULB') {
inputs = [createPin('input', 0)];
outputs = [];
label = customLabel || 'Output';
}
}
return {
id,
type,
x,
y,
label,
inputs,
outputs,
state,
icDefinitionId: icId
};
};
const addComponent = (type: ComponentType, x: number, y: number, icId?: string) => {
addToHistory(circuitRef.current);
const id = uuidv4();
const newComponent = createComponentObject(id, type, x, y, icId);
if (newComponent) {
setCircuit(prev => ({
...prev,
components: [...prev.components, newComponent]
}));
}
};
const handleDrop = (e: React.DragEvent, x: number, y: number) => {
e.preventDefault();
if (draggedItem) {
addComponent(draggedItem.type, x, y, draggedItem.icId);
setDraggedItem(null);
}
};
const handleToggleState = (componentId: string) => {
addToHistory(circuitRef.current);
setCircuit(prev => ({
...prev,
components: prev.components.map(c => {
if (c.id === componentId) {
if (c.type === 'LEVER') return { ...c, state: { ...c.state, isOn: !c.state.isOn } };
}
return c;
})
}));
};
const handleButtonPress = (componentId: string, isPressed: boolean) => {
setCircuit(prev => ({
...prev,
components: prev.components.map(c => {
if (c.id === componentId && c.type === 'BUTTON') {
return { ...c, state: { ...c.state, isPressed } };
}
return c;
})
}));
}
const handleConnect = (sourcePinId: string, targetPinId: string) => {
if (circuit.wires.some(w => w.targetPinId === targetPinId && w.sourcePinId === sourcePinId)) return;
addToHistory(circuitRef.current);
const targetAlreadyConnected = circuit.wires.some(w => w.targetPinId === targetPinId);
if (targetAlreadyConnected) {
setCircuit(prev => ({
...prev,
wires: prev.wires.filter(w => w.targetPinId !== targetPinId).concat({ id: uuidv4(), sourcePinId, targetPinId })
}));
} else {
setCircuit(prev => ({
...prev,
wires: [...prev.wires, { id: uuidv4(), sourcePinId, targetPinId }]
}));
}
};
const handleDelete = useCallback(() => {
if (circuitRef.current.selection.length === 0) return;
addToHistory(circuitRef.current);
setCircuit(prev => {
const ids = new Set(prev.selection);
const newComponents = prev.components.filter(c => !ids.has(c.id));
const newWires = prev.wires.filter(w => {
if (ids.has(w.id)) return false;
const sourceComp = prev.components.find(c => c.outputs.some(p => p.id === w.sourcePinId));
const targetComp = prev.components.find(c => c.inputs.some(p => p.id === w.targetPinId));
if (sourceComp && ids.has(sourceComp.id)) return false;
if (targetComp && ids.has(targetComp.id)) return false;
return true;
});
return {
...prev,
components: newComponents,
wires: newWires,
selection: []
};
});
}, [addToHistory]);
const handleCopy = useCallback(() => {
const currentCircuit = circuitRef.current;
const selectedIds = new Set(currentCircuit.selection);
if (selectedIds.size === 0) return;
const componentsToCopy = currentCircuit.components.filter(c => selectedIds.has(c.id));
const validPinIds = new Set<string>();
componentsToCopy.forEach(c => {
c.inputs.forEach(p => validPinIds.add(p.id));
c.outputs.forEach(p => validPinIds.add(p.id));
});
const wiresToCopy = currentCircuit.wires.filter(w =>
validPinIds.has(w.sourcePinId) && validPinIds.has(w.targetPinId)
);
setClipboard({
components: JSON.parse(JSON.stringify(componentsToCopy)),
wires: JSON.parse(JSON.stringify(wiresToCopy))
});
}, []);
const handlePaste = useCallback(() => {
if (!clipboard) return;
addToHistory(circuitRef.current);
const compIdMap = new Map<string, string>();
const pinIdMap = new Map<string, string>();
const newComponents = clipboard.components.map(comp => {
const newId = uuidv4();
compIdMap.set(comp.id, newId);
const newInputs = comp.inputs.map(p => {
const newPinId = uuidv4();
pinIdMap.set(p.id, newPinId);
return { ...p, id: newPinId, componentId: newId, value: false };
});
const newOutputs = comp.outputs.map(p => {
const newPinId = uuidv4();
pinIdMap.set(p.id, newPinId);
return { ...p, id: newPinId, componentId: newId, value: false };
});
return {
...comp,
id: newId,
x: comp.x + 20,
y: comp.y + 20,
inputs: newInputs,
outputs: newOutputs,
};
});
const newWires = clipboard.wires.map(w => {
const newSource = pinIdMap.get(w.sourcePinId);
const newTarget = pinIdMap.get(w.targetPinId);
if (newSource && newTarget) {
return { id: uuidv4(), sourcePinId: newSource, targetPinId: newTarget };
}
return null;
}).filter((w): w is Wire => w !== null);
setCircuit(prev => ({
...prev,
components: [...prev.components, ...newComponents],
wires: [...prev.wires, ...newWires],
selection: newComponents.map(c => c.id)
}));
}, [clipboard, addToHistory]);
const handleCut = useCallback(() => {
handleCopy();
handleDelete();
}, [handleCopy, handleDelete]);
// Dragging History Wrappers
const handleComponentDragStart = () => {
dragStartSnapshotRef.current = circuitRef.current;
};
const handleComponentDragEnd = () => {
if (dragStartSnapshotRef.current) {
addToHistory(dragStartSnapshotRef.current);
dragStartSnapshotRef.current = null;
}
};
// Keyboard shortcuts
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (document.activeElement instanceof HTMLInputElement || document.activeElement instanceof HTMLTextAreaElement) {
return;
}
if (e.key === 'Delete' || e.key === 'Backspace') {
handleDelete();
}
const isCtrlOrMeta = e.ctrlKey || e.metaKey;
if (isCtrlOrMeta) {
if (e.key.toLowerCase() === 'z') {
e.preventDefault();
if (e.shiftKey) {
handleRedo();
} else {
handleUndo();
}
}
if (e.key.toLowerCase() === 'y') {
e.preventDefault();
handleRedo();
}
if (e.key.toLowerCase() === 'c') {
e.preventDefault();
handleCopy();
}
if (e.key.toLowerCase() === 'v') {
e.preventDefault();
handlePaste();
}
if (e.key.toLowerCase() === 'x') {
e.preventDefault();
handleCut();
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleDelete, handleCopy, handlePaste, handleCut, handleUndo, handleRedo]);
const validateSelectionForIC = () => {
if (circuit.selection.length === 0) {
setErrorMessage("Select components to create an IC.");
return false;
}
const selectedComponents = circuit.components.filter(c => circuit.selection.includes(c.id));
const inputs = selectedComponents.filter(c => c.type === 'LEVER');
const outputs = selectedComponents.filter(c => c.type === 'BULB');
if (inputs.length === 0 && outputs.length === 0) {
setErrorMessage("IC must have at least one Input (Lever) or Output (Bulb).");
return false;
}
// Validate Inputs
const inputNames = inputs.map(c => c.label.trim());
if (inputNames.some(n => n === '')) {
setErrorMessage("All Input Levers must have a name.");
return false;
}
if (new Set(inputNames).size !== inputNames.length) {
setErrorMessage("All Input Levers must have unique names.");
return false;
}
// Validate Outputs
const outputNames = outputs.map(c => c.label.trim());
if (outputNames.some(n => n === '')) {
setErrorMessage("All Output Bulbs must have a name.");
return false;
}
if (new Set(outputNames).size !== outputNames.length) {
setErrorMessage("All Output Bulbs must have unique names.");
return false;
}
const allNames = [...inputNames, ...outputNames];
if (new Set(allNames).size !== allNames.length) {
setErrorMessage("Input and Output names must not overlap.");
return false;
}
return true;
};
const onOpenCreateICModal = () => {
if (validateSelectionForIC()) {
setIsModalOpen(true);
}
};
const handleCreateIC = (name: string) => {
addToHistory(circuitRef.current);
const selectedComponents = circuit.components.filter(c => circuit.selection.includes(c.id));
// Sort inputs and outputs by Y position
const inputs = selectedComponents
.filter(c => c.type === 'LEVER')
.sort((a, b) => a.y - b.y);
const outputs = selectedComponents
.filter(c => c.type === 'BULB')
.sort((a, b) => a.y - b.y);
const selectedIds = new Set(circuit.selection);
const internalWires = circuit.wires.filter(w => {
const sourceComp = circuit.components.find(c => c.outputs.some(p => p.id === w.sourcePinId));
const targetComp = circuit.components.find(c => c.inputs.some(p => p.id === w.targetPinId));
return sourceComp && selectedIds.has(sourceComp.id) && targetComp && selectedIds.has(targetComp.id);
});
const newIC: ICDefinition = {
id: uuidv4(),
name,
components: selectedComponents,
wires: internalWires,
inputMap: inputs.map((c, idx) => ({ internalComponentId: c.id, pinIndex: 0, label: c.label })),
outputMap: outputs.map((c, idx) => ({ internalComponentId: c.id, pinIndex: 0, label: c.label }))
};
setCircuit(prev => ({
...prev,
icDefinitions: [...prev.icDefinitions, newIC],
selection: []
}));
setIsModalOpen(false);
};
const handleLabelChange = (id: string, newLabel: string) => {
addToHistory(circuitRef.current);
setCircuit(prev => ({
...prev,
components: prev.components.map(c => c.id === id ? { ...c, label: newLabel } : c)
}));
};
const handleSaveProject = () => {
const data = JSON.stringify(circuit, null, 2);
const blob = new Blob([data], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'logic-lab-project.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
const handleLoadProjectTrigger = () => {
fileInputRef.current?.click();
};
const handleLoadProjectFile = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
try {
const content = event.target?.result as string;
const loadedCircuit = JSON.parse(content);
if (Array.isArray(loadedCircuit.components) && Array.isArray(loadedCircuit.wires)) {
addToHistory(circuitRef.current); // Save current before loading new
setCircuit({
components: loadedCircuit.components,
wires: loadedCircuit.wires,
icDefinitions: loadedCircuit.icDefinitions || [],
selection: []
});
setErrorMessage(null);
} else {
setErrorMessage("Invalid project file format.");
}
} catch (err) {
console.error(err);
setErrorMessage("Failed to parse project file.");
}
};
reader.readAsText(file);
e.target.value = '';
};
// --- AI Logic ---
const handleAIGeneration = async (prompt: string) => {
try {
const blueprint = await generateCircuitBlueprint(prompt, circuitRef.current.icDefinitions);
if (!blueprint || !blueprint.components) {
setErrorMessage("AI could not generate a valid circuit.");
return;
}
addToHistory(circuitRef.current);
// Map AI ID -> Real UUID
const idMap = new Map<string, string>();
const newComponents: CircuitComponent[] = [];
// Find bounds to center it roughly
const startX = 200;
const startY = 200;
const GRID_SCALE = 100;
// Create Components
for (const spec of blueprint.components) {
const realId = uuidv4();
idMap.set(spec.id, realId);
const x = startX + spec.gridX * GRID_SCALE;
const y = startY + spec.gridY * GRID_SCALE;
let icId: string | undefined = undefined;
if (spec.type === 'IC' && spec.icName) {
const def = circuitRef.current.icDefinitions.find(d => d.name.toLowerCase() === spec.icName?.toLowerCase());
if (def) icId = def.id;
else {
// Fallback or warning if IC not found?
// Just skip or create a dummy box? Let's skip for safety, or default to AND.
console.warn(`IC ${spec.icName} not found.`);
}
}
const comp = createComponentObject(realId, spec.type, x, y, icId, spec.label);
if (comp) {
newComponents.push(comp);
}
}
// Create Wires
const newWires: Wire[] = [];
for (const conn of blueprint.connections) {
const sourceRealId = idMap.get(conn.sourceId);
const targetRealId = idMap.get(conn.targetId);
if (sourceRealId && targetRealId) {
const sourceComp = newComponents.find(c => c.id === sourceRealId);
const targetComp = newComponents.find(c => c.id === targetRealId);
// Default to first output for source
const sourcePin = sourceComp?.outputs[0];
// Target pin by index
const targetPin = targetComp?.inputs[conn.targetInputIndex];
if (sourcePin && targetPin) {
newWires.push({
id: uuidv4(),
sourcePinId: sourcePin.id,
targetPinId: targetPin.id
});
}
}
}
setCircuit(prev => ({
...prev,
components: [...prev.components, ...newComponents],
wires: [...prev.wires, ...newWires],
selection: newComponents.map(c => c.id) // Auto-select the AI creation
}));
setSuccessMessage(blueprint.explanation || "Circuit Generated Successfully");
} catch (e) {
console.error(e);
setErrorMessage("AI generation failed. Check console.");
throw e; // Re-throw for modal to catch
}
};
return (
<div className="flex h-screen w-screen overflow-hidden text-slate-100">
<Sidebar
onDragStart={(type, icId) => setDraggedItem({ type, icId })}
icDefinitions={circuit.icDefinitions}
/>
<div className="flex-1 flex flex-col relative">
{/* Toolbar */}
<div className="h-14 bg-slate-900 border-b border-slate-700 flex items-center px-4 justify-between z-10 shadow-md">
<div className="flex items-center space-x-2">
<h1 className="text-xl font-bold bg-gradient-to-r from-blue-400 to-emerald-400 bg-clip-text text-transparent mr-6">
LogicLab
</h1>
{/* Undo / Redo */}
<div className="flex items-center space-x-1 border-r border-slate-700 pr-4 mr-2">
<button
onClick={handleUndo}
disabled={history.past.length === 0}
className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded transition-colors disabled:opacity-30 disabled:hover:bg-transparent"
title="Undo (Ctrl+Z)"
>
<Undo2 size={18} />
</button>
<button
onClick={handleRedo}
disabled={history.future.length === 0}
className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded transition-colors disabled:opacity-30 disabled:hover:bg-transparent"
title="Redo (Ctrl+Y)"
>
<Redo2 size={18} />
</button>
</div>
{/* AI Button */}
<button
onClick={() => setIsAIModalOpen(true)}
className="flex items-center gap-2 px-3 py-1.5 bg-gradient-to-r from-violet-600 to-fuchsia-600 hover:from-violet-500 hover:to-fuchsia-500 text-white rounded-md text-sm font-medium shadow-lg shadow-purple-900/20 transition-all border border-white/10"
>
<Sparkles size={16} />
<span>AI Architect</span>
</button>
<div className="ml-4 text-xs text-slate-400 flex items-center gap-2 hidden lg:flex">
<span className="px-2 py-1 bg-slate-800 rounded border border-slate-700">
{circuit.components.length} Components
</span>
<span className="px-2 py-1 bg-slate-800 rounded border border-slate-700">
{circuit.wires.length} Wires
</span>
</div>
</div>
{/* Success Toast */}
{successMessage && (
<div className="absolute top-16 left-1/2 -translate-x-1/2 bg-emerald-500/90 text-white px-4 py-2 rounded-md shadow-lg flex items-center gap-2 animate-in fade-in slide-in-from-top-2 z-50">
<Sparkles size={16} />
<span className="text-sm font-medium">{successMessage}</span>
</div>
)}
{/* Error Toast */}
{errorMessage && (
<div className="absolute top-16 left-1/2 -translate-x-1/2 bg-red-500/90 text-white px-4 py-2 rounded-md shadow-lg flex items-center gap-2 animate-bounce z-50">
<AlertTriangle size={16} />
<span className="text-sm font-medium">{errorMessage}</span>
</div>
)}
<div className="flex items-center space-x-4">
<div className="text-xs text-slate-500 mr-4 hidden md:block">
<span className="mr-3">Shift + Drag to Select</span>
</div>
{/* File Operations */}
<div className="flex items-center space-x-2 border-r border-slate-700 pr-4 mr-2">
<button
onClick={handleSaveProject}
className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded transition-colors"
title="Save Project"
>
<Save size={20} />
</button>
<button
onClick={handleLoadProjectTrigger}
className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded transition-colors"
title="Load Project"
>
<FolderOpen size={20} />
</button>
<input
type="file"
ref={fileInputRef}
onChange={handleLoadProjectFile}
className="hidden"
accept=".json"
/>
</div>
{circuit.selection.length > 0 && (
<>
<button
onClick={onOpenCreateICModal}
className="flex items-center space-x-2 px-3 py-1.5 bg-indigo-600 hover:bg-indigo-500 rounded-md text-sm font-medium transition-colors"
>
<Plus size={16} />
<span>Create IC</span>
</button>
<button
onClick={handleDelete}
className="flex items-center space-x-2 px-3 py-1.5 bg-red-600 hover:bg-red-500 rounded-md text-sm font-medium transition-colors"
>
<Trash2 size={16} />
<span>Delete</span>
</button>
</>
)}
</div>
</div>
<div className="flex-1 relative overflow-hidden">
<Canvas
circuit={circuit}
onDrop={handleDrop}
setCircuit={setCircuit}
onConnect={handleConnect}
onToggle={handleToggleState}
onPress={handleButtonPress}
onLabelChange={handleLabelChange}
onDragStart={handleComponentDragStart}
onDragEnd={handleComponentDragEnd}
/>
</div>
</div>
{isModalOpen && (
<CreateICModal
onClose={() => setIsModalOpen(false)}
onCreate={handleCreateIC}
selectedCount={circuit.selection.length}
/>
)}
{isAIModalOpen && (
<AIChatModal
onClose={() => setIsAIModalOpen(false)}
onGenerate={handleAIGeneration}
/>
)}
</div>
);
};
export default App;