-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy path+page.svelte
More file actions
1699 lines (1536 loc) · 50.7 KB
/
+page.svelte
File metadata and controls
1699 lines (1536 loc) · 50.7 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
<script lang="ts">
import { onMount } from 'svelte';
import { base } from '$app/paths';
import { fly, scale } from 'svelte/transition';
import { cubicOut } from 'svelte/easing';
import FlowCanvas from '$lib/components/FlowCanvas.svelte';
import SimulationPanel from '$lib/components/panels/SimulationPanel.svelte';
import BlockPropertiesDialog from '$lib/components/dialogs/BlockPropertiesDialog.svelte';
import EventPropertiesDialog from '$lib/components/dialogs/EventPropertiesDialog.svelte';
import CodePreviewDialog from '$lib/components/dialogs/CodePreviewDialog.svelte';
import { codePreviewStore } from '$lib/stores/codePreview';
import PlotPanel from '$lib/components/panels/PlotPanel.svelte';
import ConsolePanel from '$lib/components/panels/ConsolePanel.svelte';
import CodeEditor from '$lib/components/panels/CodeEditor.svelte';
import NodeLibrary from '$lib/components/panels/NodeLibrary.svelte';
import EventsPanel from '$lib/components/panels/EventsPanel.svelte';
import ContextMenu from '$lib/components/ContextMenu.svelte';
import { buildContextMenuItems, type ContextMenuCallbacks } from '$lib/components/contextMenuBuilders';
import ExportDialog from '$lib/components/dialogs/ExportDialog.svelte';
import KeyboardShortcutsDialog from '$lib/components/dialogs/KeyboardShortcutsDialog.svelte';
import PlotOptionsDialog from '$lib/components/dialogs/PlotOptionsDialog.svelte';
import SearchDialog from '$lib/components/dialogs/SearchDialog.svelte';
import ResizablePanel from '$lib/components/ResizablePanel.svelte';
import WelcomeModal from '$lib/components/WelcomeModal.svelte';
import SubsystemBreadcrumb from '$lib/components/SubsystemBreadcrumb.svelte';
import Icon from '$lib/components/icons/Icon.svelte';
import { nodeRegistry } from '$lib/nodes';
import { NODE_TYPES } from '$lib/constants/nodeTypes';
import { PANEL_GAP, PANEL_TOGGLES_WIDTH, MIN_BOTTOM_PANEL_WIDTH, PANEL_DEFAULTS, NAV_HEIGHT } from '$lib/constants/layout';
import { GRID_SIZE } from '$lib/constants/grid';
import { DEFAULT_SIMULATION_SETTINGS } from '$lib/nodes/types';
import { graphStore } from '$lib/stores/graph';
import { eventStore } from '$lib/stores/events';
import { historyStore } from '$lib/stores/history';
import { settingsStore } from '$lib/stores/settings';
import { codeContextStore } from '$lib/stores/codeContext';
import { themeStore, type Theme } from '$lib/stores/theme';
import { contextMenuStore, type ContextMenuTarget } from '$lib/stores/contextMenu';
import { openNodeDialog } from '$lib/stores/nodeDialog';
import { openEventDialog } from '$lib/stores/eventDialog';
import type { MenuItemType } from '$lib/components/ContextMenu.svelte';
import { pyodideState, simulationState, initPyodide, stopSimulation, continueStreamingSimulation, stageMutations } from '$lib/pyodide/bridge';
import { pendingMutationCount } from '$lib/pyodide/mutationQueue';
import { initBackendFromUrl, autoDetectBackend } from '$lib/pyodide/backend';
import { runGraphStreamingSimulation, validateGraphSimulation, exportToPython } from '$lib/pyodide/pathsimRunner';
import { consoleStore } from '$lib/stores/console';
import { newGraph, saveFile, saveAsFile, setupAutoSave, clearAutoSave, debouncedAutoSave, openImportDialog, importFromUrl, currentFileName } from '$lib/schema/fileOps';
import { confirmationStore } from '$lib/stores/confirmation';
import ConfirmationModal from '$lib/components/ConfirmationModal.svelte';
import { triggerFitView, triggerZoomIn, triggerZoomOut, triggerPan, getViewportCenter, screenToFlow, triggerClearSelection, triggerNudge, hasAnySelection, setFitViewPadding, triggerFlyInAnimation } from '$lib/stores/viewActions';
import { nodeUpdatesStore } from '$lib/stores/nodeUpdates';
import { pinnedPreviewsStore } from '$lib/stores/pinnedPreviews';
import { portLabelsStore } from '$lib/stores/portLabels';
import { clipboardStore } from '$lib/stores/clipboard';
import Tooltip, { tooltip } from '$lib/components/Tooltip.svelte';
import { isInputFocused } from '$lib/utils/focus';
// Theme toggle button ref for radial transition origin
let themeToggleBtn: HTMLButtonElement;
function toggleThemeWithTransition(e?: MouseEvent) {
const apply = () => themeStore.toggle();
if (!document.startViewTransition) { apply(); return; }
let x: number, y: number;
if (e) {
x = e.clientX; y = e.clientY;
} else if (themeToggleBtn) {
const rect = themeToggleBtn.getBoundingClientRect();
x = rect.left + rect.width / 2;
y = rect.top + rect.height / 2;
} else {
apply(); return;
}
const maxRadius = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y));
const transition = document.startViewTransition(apply);
transition.ready.then(() => {
document.documentElement.animate(
{ clipPath: [`circle(0px at ${x}px ${y}px)`, `circle(${maxRadius}px at ${x}px ${y}px)`] },
{ duration: 500, easing: 'ease-out', pseudoElement: '::view-transition-new(root)' }
);
});
}
// Track mouse position for paste operations
let mousePosition = $state({ x: 0, y: 0 });
// Save feedback animation state
let saveFlash = $state<'save' | 'save-as' | 'codegen' | null>(null);
let saveFlashTimeout: ReturnType<typeof setTimeout> | undefined;
function flashSaveButton(which: 'save' | 'save-as' | 'codegen') {
clearTimeout(saveFlashTimeout);
saveFlash = which;
saveFlashTimeout = setTimeout(() => { saveFlash = null; }, 1500);
}
async function handleSave() {
const success = await saveFile();
if (success) flashSaveButton('save');
}
async function handleSaveAs() {
const success = await saveAsFile();
if (success) flashSaveButton('save-as');
}
// Codegen export — compress Python code into URL hash and open codegen
const CODEGEN_URL = import.meta.env.VITE_CODEGEN_URL ?? 'https://code.pathsim.org/app';
const CODEGEN_MAX_BYTES = 100_000; // 100 KB raw Python limit
async function compressAndEncode(text: string): Promise<string> {
const data = new TextEncoder().encode(text);
const cs = new CompressionStream('deflate-raw');
const writer = cs.writable.getWriter();
writer.write(data);
writer.close();
const compressed = new Uint8Array(await new Response(cs.readable).arrayBuffer());
let binary = '';
for (const b of compressed) binary += String.fromCharCode(b);
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
async function handleSendToCodegen() {
const { nodes, connections } = graphStore.toJSON();
if (nodes.length === 0) {
await confirmationStore.show({
title: 'No Model',
message: 'There are no blocks in the current graph. Add blocks to your simulation before exporting to Codegen.',
confirmText: 'OK',
cancelText: 'Cancel'
});
return;
}
const settings = settingsStore.get();
const codeContext = codeContextStore.getCode();
const events = eventStore.toJSON();
const pythonCode = exportToPython(nodes, connections, settings, codeContext, events);
const rawBytes = new TextEncoder().encode(pythonCode).length;
if (rawBytes > CODEGEN_MAX_BYTES) {
const sizeKB = Math.round(rawBytes / 1024);
const openExport = await confirmationStore.show({
title: 'Model Too Large',
message: `The generated Python code is ${sizeKB} KB, which exceeds the transfer limit. Use the Python Code export (Ctrl+E) to copy the code and paste it into Codegen manually.`,
confirmText: 'Open Python Export',
cancelText: 'Cancel'
});
if (openExport) exportDialogOpen = true;
return;
}
const encoded = await compressAndEncode(pythonCode);
window.open(`${CODEGEN_URL}?code=${encoded}`, '_blank');
flashSaveButton('codegen');
}
// Panel visibility state
let showProperties = $state(false);
let showNodeLibrary = $state(false);
let showEventsPanel = $state(false);
let showCodeEditor = $state(false);
let showPlot = $state(false);
let showConsole = $state(false);
let plotPanelHeight = $state(280);
let consolePanelHeight = $state(280);
let bottomPanelSplit = $state(0.5); // 0-1, ratio of console width to total
let showPinnedPreviews = $state(false);
let hasAutoOpenedPlot = $state(false); // Only auto-open once
let hasAutoOpenedConsole = $state(false); // Only auto-open once
// Parse URL model params once at init
function getUrlModelConfig(): { url: string; isGitHub: boolean } | null {
if (typeof window === 'undefined') return null;
const params = new URLSearchParams(window.location.search);
const model = params.get('model');
const modelgh = params.get('modelgh');
if (model) return { url: model, isGitHub: false };
if (modelgh) return { url: modelgh, isGitHub: true };
return null;
}
const urlModelConfig = getUrlModelConfig();
let showWelcomeModal = $state(!urlModelConfig); // Hide if loading from URL
// Track widths directly - initialized on first dual-panel open
let consolePanelWidth = $state<number | undefined>(undefined);
let plotPanelWidth = $state<number | undefined>(undefined);
// Track side panel widths for fitView padding calculation
let nodeLibraryWidth = $state(320);
let eventsPanelWidth = $state(280);
let codeEditorWidth = $state(400);
const propertiesPanelWidth = 310; // Fixed width, not resizable
// Track window size for fitView padding calculation
let windowWidth = $state(typeof window !== 'undefined' ? window.innerWidth : 1920);
let windowHeight = $state(typeof window !== 'undefined' ? window.innerHeight : 1080);
function getBottomPanelTotalWidth() {
if (typeof window === 'undefined') return 800;
// Layout: [toggles + gap][panel1][gap][panel2][gap]
return window.innerWidth - PANEL_TOGGLES_WIDTH - PANEL_GAP * 3;
}
// Max width for bottom panels when both are open (total - min for the other panel)
const bottomPanelMaxWidth = $derived(
showPlot && showConsole ? getBottomPanelTotalWidth() - MIN_BOTTOM_PANEL_WIDTH : undefined
);
// Initialize widths when both panels become visible
$effect(() => {
if (showPlot && showConsole) {
if (consolePanelWidth === undefined || plotPanelWidth === undefined) {
const total = getBottomPanelTotalWidth();
const consoleW = Math.floor(total * bottomPanelSplit);
consolePanelWidth = consoleW;
plotPanelWidth = total - consoleW;
}
} else {
// Reset when not both open
consolePanelWidth = undefined;
plotPanelWidth = undefined;
}
});
// Handle width changes from ResizablePanel - use a single derived to avoid circular updates
function handleConsoleWidthChange(newWidth: number) {
if (!showPlot || !showConsole) return;
const total = getBottomPanelTotalWidth();
const clampedWidth = Math.max(MIN_BOTTOM_PANEL_WIDTH, Math.min(total - MIN_BOTTOM_PANEL_WIDTH, newWidth));
consolePanelWidth = clampedWidth;
plotPanelWidth = total - clampedWidth;
bottomPanelSplit = clampedWidth / total;
}
function handlePlotWidthChange(newWidth: number) {
if (!showPlot || !showConsole) return;
const total = getBottomPanelTotalWidth();
const clampedWidth = Math.max(MIN_BOTTOM_PANEL_WIDTH, Math.min(total - MIN_BOTTOM_PANEL_WIDTH, newWidth));
plotPanelWidth = clampedWidth;
consolePanelWidth = total - clampedWidth;
bottomPanelSplit = (total - clampedWidth) / total;
}
// Handle window resize - recalculate panel widths maintaining split ratio
function handleWindowResize() {
// Update window dimensions for fitView padding calculation
windowWidth = window.innerWidth;
windowHeight = window.innerHeight;
if (showPlot && showConsole && consolePanelWidth !== undefined && plotPanelWidth !== undefined) {
const total = getBottomPanelTotalWidth();
const consoleW = Math.max(MIN_BOTTOM_PANEL_WIDTH, Math.min(total - MIN_BOTTOM_PANEL_WIDTH, Math.floor(total * bottomPanelSplit)));
consolePanelWidth = consoleW;
plotPanelWidth = total - consoleW;
}
}
// Panel layout constant - matches --panel-gap (12px) adjusted for max-height formula
// Side panels use max-height: calc(100vh - 80px - offset), this constant ensures
// the gap between side panels and bottom panels equals --panel-gap
const PANEL_OFFSET_ADJUSTMENT = 12;
// Node placement grid - used when adding multiple nodes to prevent stacking
const NODE_PLACEMENT_COLS = 5;
const NODE_PLACEMENT_GAP_X = 40;
const NODE_PLACEMENT_GAP_Y = 50;
// Compute bottom offset for left side panels (avoids console when both shown)
const leftPanelBottomOffset = $derived(() => {
if (!showPlot && !showConsole) return 0;
if (showPlot && showConsole) return consolePanelHeight + PANEL_OFFSET_ADJUSTMENT;
// Only one shown - it takes full width
return (showPlot ? plotPanelHeight : consolePanelHeight) + PANEL_OFFSET_ADJUSTMENT;
});
// Toggle node library (closes other left panels if open)
function toggleNodeLibrary() {
if (showNodeLibrary) {
showNodeLibrary = false;
} else {
showEventsPanel = false;
showNodeLibrary = true;
setTimeout(() => nodeLibraryRef?.focus(), 50);
}
}
// Toggle events panel (closes other left panels if open)
function toggleEventsPanel() {
if (showEventsPanel) {
showEventsPanel = false;
} else {
showNodeLibrary = false;
showEventsPanel = true;
}
}
// Toggle simulation settings (closes other right panels if open)
function toggleProperties() {
if (showProperties) {
showProperties = false;
} else {
showCodeEditor = false;
showProperties = true;
}
}
// Toggle code editor (closes other right panels if open)
function toggleCodeEditor() {
if (showCodeEditor) {
showCodeEditor = false;
} else {
showProperties = false;
showCodeEditor = true;
// Focus editor after it mounts
setTimeout(() => codeEditorRef?.focus(), 50);
}
}
// Compute bottom offset for right side panel (avoids plot when both shown)
const rightPanelBottomOffset = $derived(() => {
if (!showPlot && !showConsole) return 0;
if (showPlot && showConsole) return plotPanelHeight + PANEL_OFFSET_ADJUSTMENT;
// Only one shown - it takes full width
return (showPlot ? plotPanelHeight : consolePanelHeight) + PANEL_OFFSET_ADJUSTMENT;
});
// Update fitView padding when panel state changes (in pixels)
$effect(() => {
if (typeof window === 'undefined') return;
// Dependencies: panel visibility, widths, heights, and window size
// These variable reads ensure the effect reruns when values change
const _w = windowWidth;
const _h = windowHeight;
const _nlw = nodeLibraryWidth;
const _epw = eventsPanelWidth;
const _cew = codeEditorWidth;
// Calculate pixel offsets for each side
// Left panels: Block Library or Events (only one can be open at a time)
const leftPanelWidth = showNodeLibrary ? nodeLibraryWidth : showEventsPanel ? eventsPanelWidth : 0;
const leftPx = PANEL_TOGGLES_WIDTH + PANEL_GAP + (leftPanelWidth > 0 ? leftPanelWidth + PANEL_GAP : 0);
// Right panels: Code Editor or Simulation (Properties)
const rightPanelWidth = showCodeEditor ? codeEditorWidth : showProperties ? propertiesPanelWidth : 0;
const rightPx = (rightPanelWidth > 0 ? rightPanelWidth + PANEL_GAP : 0) + 20; // 20px extra buffer
// Bottom panels: Plot and Console - only use heights of panels that are actually open
let bottomPx = 20;
if (showPlot && showConsole) {
bottomPx = Math.max(plotPanelHeight, consolePanelHeight) + PANEL_GAP + 20;
} else if (showPlot) {
bottomPx = plotPanelHeight + PANEL_GAP + 20;
} else if (showConsole) {
bottomPx = consolePanelHeight + PANEL_GAP + 20;
}
// Top: Navigation bar
const topPx = NAV_HEIGHT + 20; // 20px extra buffer
setFitViewPadding({
top: topPx,
right: rightPx,
bottom: bottomPx,
left: leftPx
});
});
// References for focus management
let nodeLibraryRef = $state<NodeLibrary | undefined>(undefined);
let codeEditorRef = $state<CodeEditor | undefined>(undefined);
let exportDialogOpen = $state(false);
let showKeyboardShortcuts = $state(false);
let showSearchDialog = $state(false);
let showPlotOptionsDialog = $state(false);
// Context menu state
let contextMenuOpen = $state(false);
let contextMenuPosition = $state({ x: 0, y: 0 });
let contextMenuTarget = $state<ContextMenuTarget | null>(null);
// Context menu callbacks
const contextMenuCallbacks: ContextMenuCallbacks = {
toggleNodeLibrary,
toggleEventsPanel,
deleteNodes
};
// Build context menu items based on target
function getContextMenuItems(): MenuItemType[] {
return buildContextMenuItems(contextMenuTarget, contextMenuPosition, contextMenuCallbacks);
}
// Helper to rotate a node (single node)
function rotateNode(nodeId: string) {
const node = graphStore.getNode(nodeId);
if (node) {
historyStore.mutate(() => {
const currentRotation = (node.params?.['_rotation'] as number) || 0;
const newRotation = (currentRotation + 1) % 4;
graphStore.updateNodeParams(nodeId, { '_rotation': newRotation });
});
// Queue update to re-render handles
nodeUpdatesStore.queueUpdate([nodeId]);
}
}
// Helper to rotate multiple nodes as a single undoable action
function rotateNodes(nodeIds: string[]) {
const nodesToUpdate = historyStore.mutate(() => {
const updated: string[] = [];
for (const nodeId of nodeIds) {
const node = graphStore.getNode(nodeId);
if (node) {
const currentRotation = (node.params?.['_rotation'] as number) || 0;
const newRotation = (currentRotation + 1) % 4;
graphStore.updateNodeParams(nodeId, { '_rotation': newRotation });
updated.push(nodeId);
}
}
return updated;
});
// Queue updates to re-render handles
if (nodesToUpdate.length > 0) {
nodeUpdatesStore.queueUpdate(nodesToUpdate);
}
}
// Helper to delete multiple nodes as a single undoable action
function deleteNodes(nodeIds: string[]) {
if (nodeIds.length === 0) return;
historyStore.mutate(() => {
for (const nodeId of nodeIds) {
graphStore.removeNode(nodeId);
}
});
}
// App state
let nodeCount = $state(0);
let pyodideReady = $state(false);
let pyodideLoading = $state(false);
let simRunning = $state(false);
let isRunStarting = false; // Synchronous flag to prevent race conditions
let isContinuing = false; // Synchronous flag to prevent rapid continue calls
let hasRunSimulation = $state(false);
let statusText = $state('Ready');
let currentTheme = $state<Theme>('dark');
let consoleLogCount = $state(0);
let plotActiveTab = $state(0);
let plotViewMode = $state<'tabs' | 'tiles'>('tabs');
let resultPlots = $state<{ id: string; type: 'scope' | 'spectrum'; title: string }[]>([]);
let resultTraces = $state<{ nodeId: string; nodeType: 'scope' | 'spectrum'; nodeName: string; signalIndex: number; signalLabel: string }[]>([]);
// Tooltip for continue button - simple, disabled state shows availability
const continueTooltip = { text: "Continue", shortcut: "Shift+Enter" };
onMount(() => {
// Auto-detect same-origin Flask backend (pip package mode), then check URL params
autoDetectBackend().then(() => initBackendFromUrl());
// Subscribe to stores (with cleanup)
const unsubPinnedPreviews = pinnedPreviewsStore.subscribe((pinned) => {
showPinnedPreviews = pinned;
});
const unsubContextMenu = contextMenuStore.subscribe((state) => {
contextMenuOpen = state.open;
contextMenuPosition = state.position;
contextMenuTarget = state.target;
});
const unsubTheme = themeStore.subscribe((theme) => {
currentTheme = theme;
});
const unsubNodeCount = graphStore.nodesArray.subscribe((nodes) => {
nodeCount = nodes.length;
});
const unsubPyodide = pyodideState.subscribe((s) => {
pyodideReady = s.initialized;
pyodideLoading = s.loading;
if (s.loading) {
statusText = s.progress || 'Loading...';
} else if (s.error) {
statusText = `Error: ${s.error}`;
} else if (s.initialized) {
statusText = 'Ready';
}
});
const unsubSimulation = simulationState.subscribe((s) => {
simRunning = s.phase === 'running';
// Sync hasRunSimulation with whether we have results
hasRunSimulation = s.result !== null;
if (s.phase === 'running') {
statusText = s.progress || 'Simulating...';
} else if (s.error) {
statusText = `Error: ${s.error}`;
} else if (pyodideReady) {
statusText = 'Ready';
}
// Derive plots and traces from result (use nodeNames from simulation result for subsystem support)
const plots: { id: string; type: 'scope' | 'spectrum'; title: string }[] = [];
const traces: typeof resultTraces = [];
if (s.result?.scopeData) {
Object.entries(s.result.scopeData).forEach(([id, data], index) => {
const title = s.result?.nodeNames?.[id] || `Scope ${index + 1}`;
plots.push({ id, type: 'scope', title });
// Add traces for each signal in this scope
for (let i = 0; i < data.signals.length; i++) {
traces.push({
nodeId: id,
nodeType: 'scope',
nodeName: title,
signalIndex: i,
signalLabel: data.labels?.[i] || `port ${i}`
});
}
});
}
if (s.result?.spectrumData) {
Object.entries(s.result.spectrumData).forEach(([id, data], index) => {
const title = s.result?.nodeNames?.[id] || `Spectrum ${index + 1}`;
plots.push({ id, type: 'spectrum', title });
// Add traces for each signal in this spectrum
for (let i = 0; i < data.magnitude.length; i++) {
traces.push({
nodeId: id,
nodeType: 'spectrum',
nodeName: title,
signalIndex: i,
signalLabel: data.labels?.[i] || `port ${i}`
});
}
});
}
resultPlots = plots;
resultTraces = traces;
// Reset tab if out of bounds
if (plotActiveTab >= plots.length && plots.length > 0) {
plotActiveTab = 0;
}
});
const unsubConsole = consoleStore.subscribe((logs) => {
consoleLogCount = logs.length;
});
// Always start with clean slate
clearAutoSave();
// Setup periodic autosave (backup)
const cleanupAutoSave = setupAutoSave(30000);
// Setup immediate autosave on graph changes
const unsubNodes = graphStore.nodesArray.subscribe(() => {
debouncedAutoSave();
});
const unsubConnections = graphStore.connections.subscribe(() => {
debouncedAutoSave();
});
// Listen for simulation events from code editor
const handleRunSimulation = () => handleRun();
const handleContinueSimulation = () => {
if (hasRunSimulation && pyodideReady && !simRunning && !isContinuing) {
handleContinue();
}
};
window.addEventListener('run-simulation', handleRunSimulation);
window.addEventListener('continue-simulation', handleContinueSimulation);
// Check for URL parameters to load model
loadFromUrlParam();
return () => {
// Cleanup store subscriptions
unsubPinnedPreviews();
unsubContextMenu();
unsubTheme();
unsubNodeCount();
unsubPyodide();
unsubSimulation();
unsubConsole();
// Cleanup autosave subscriptions
cleanupAutoSave();
unsubNodes();
unsubConnections();
window.removeEventListener('run-simulation', handleRunSimulation);
window.removeEventListener('continue-simulation', handleContinueSimulation);
};
});
// Keyboard shortcuts
function handleKeydown(event: KeyboardEvent) {
const inputFocused = isInputFocused(event);
// Shift+Enter for continue simulation
if (event.shiftKey && event.key === 'Enter') {
event.preventDefault();
if (hasRunSimulation && pyodideReady && !simRunning && !isContinuing) {
handleContinue();
}
return;
}
// Cmd/Ctrl shortcuts (work even in inputs, except select all)
if (event.metaKey || event.ctrlKey) {
switch (event.key.toLowerCase()) {
case 's':
event.preventDefault();
if (event.shiftKey) {
handleSaveAs();
} else {
handleSave();
}
return;
case 'o':
event.preventDefault();
handleOpen();
return;
case 'e':
event.preventDefault();
exportDialogOpen = true;
return;
case 'f':
event.preventDefault();
showSearchDialog = true;
return;
case 'd':
event.preventDefault();
historyStore.mutate(() => graphStore.duplicateSelected());
return;
case 'c':
if (!inputFocused) {
event.preventDefault();
clipboardStore.copy();
}
return;
case 'x':
if (!inputFocused) {
event.preventDefault();
clipboardStore.cut();
}
return;
case 'v':
if (!inputFocused) {
event.preventDefault();
const flowPosition = screenToFlow(mousePosition);
clipboardStore.paste(flowPosition);
}
return;
case 'a':
if (!inputFocused) {
event.preventDefault();
graphStore.selectAll();
}
return;
case 'z':
event.preventDefault();
if (event.shiftKey) {
historyStore.redo();
} else {
historyStore.undo();
}
return;
case 'y':
event.preventDefault();
historyStore.redo();
return;
case 'enter':
event.preventDefault();
handleRun();
return;
}
}
// Non-modifier shortcuts (only when not typing)
if (!inputFocused) {
switch (event.key) {
case 'Escape':
// Progressive close - one thing at a time
if (contextMenuOpen) {
contextMenuStore.close();
} else if (exportDialogOpen) {
exportDialogOpen = false;
} else if (showKeyboardShortcuts) {
showKeyboardShortcuts = false;
} else if (hasAnySelection()) {
triggerClearSelection();
} else if (simRunning) {
stopSimulation();
} else if (showConsole) {
showConsole = false;
} else if (showPlot) {
showPlot = false;
} else if (showCodeEditor) {
showCodeEditor = false;
} else if (showNodeLibrary) {
showNodeLibrary = false;
} else if (showEventsPanel) {
showEventsPanel = false;
} else if (showProperties) {
showProperties = false;
}
return;
case 'f':
event.preventDefault();
triggerFitView();
return;
case 's':
event.preventDefault();
toggleProperties();
return;
case 'e':
event.preventDefault();
toggleCodeEditor();
return;
case 'v':
event.preventDefault();
showPlot = !showPlot;
return;
case 'c':
event.preventDefault();
showConsole = !showConsole;
return;
case 'p':
event.preventDefault();
pinnedPreviewsStore.toggle();
return;
case 'l':
event.preventDefault();
portLabelsStore.toggle();
return;
case 'b':
event.preventDefault();
toggleNodeLibrary();
return;
case 'n':
event.preventDefault();
toggleEventsPanel();
return;
case 'h':
event.preventDefault();
if (!graphStore.isAtRoot()) {
graphStore.navigateTo(0);
}
return;
case 't':
event.preventDefault();
toggleThemeWithTransition();
return;
case '+':
case '=':
if (!event.ctrlKey && !event.metaKey) {
event.preventDefault();
triggerZoomIn();
}
return;
case '-':
if (!event.ctrlKey && !event.metaKey) {
event.preventDefault();
triggerZoomOut();
}
return;
case '?':
event.preventDefault();
showKeyboardShortcuts = !showKeyboardShortcuts;
return;
case 'ArrowUp':
case 'ArrowDown':
case 'ArrowLeft':
case 'ArrowRight':
event.preventDefault();
handleArrowKey(event.key, event.shiftKey);
return;
}
}
}
// Handle arrow keys - nudge selected nodes or pan canvas
function handleArrowKey(direction: string, largeStep: boolean) {
const hasSelection = hasAnySelection();
const panStep = largeStep ? GRID_SIZE * 5 : GRID_SIZE * 2;
const nudgeStep = largeStep ? GRID_SIZE * 2 : GRID_SIZE;
const delta = { x: 0, y: 0 };
switch (direction) {
case 'ArrowUp': delta.y = hasSelection ? -nudgeStep : panStep; break;
case 'ArrowDown': delta.y = hasSelection ? nudgeStep : -panStep; break;
case 'ArrowLeft': delta.x = hasSelection ? -nudgeStep : panStep; break;
case 'ArrowRight': delta.x = hasSelection ? nudgeStep : -panStep; break;
}
if (hasSelection) {
triggerNudge(delta);
} else {
triggerPan(delta);
}
}
// Run simulation (auto-initializes if needed)
async function handleRun() {
// Prevent concurrent simulation runs (synchronous check for rapid key presses)
if (simRunning || isRunStarting || pyodideLoading) return;
// Set flag before any async operations to prevent race conditions
isRunStarting = true;
// Auto-initialize if not ready
if (!pyodideReady) {
try {
await initPyodide();
} catch (error) {
console.error('Failed to initialize Pyodide:', error);
isRunStarting = false;
return;
}
}
try {
// Run simulation
const { nodes, connections } = graphStore.toJSON();
if (nodes.length === 0) {
statusText = 'Add nodes first';
return;
}
// Auto-open console on first run to show progress
if (!hasAutoOpenedConsole) {
showConsole = true;
hasAutoOpenedConsole = true;
}
const codeContext = codeContextStore.getCode();
// Validate before running
try {
statusText = 'Validating...';
const validation = await validateGraphSimulation(nodes, codeContext);
if (!validation.valid) {
// Show validation errors
showConsole = true;
consoleStore.error('Validation failed:');
for (const err of validation.errors) {
if (err.nodeId === '__code_context__') {
consoleStore.error(` Code context: ${err.error}`);
} else {
const node = nodes.find((n) => n.id === err.nodeId);
const nodeName = node?.name || err.nodeId;
consoleStore.error(` ${nodeName}.${err.param}: ${err.error}`);
}
}
statusText = 'Validation failed';
return;
}
} catch (error) {
showConsole = true;
consoleStore.error(`Validation error: ${error}`);
statusText = 'Validation error';
return;
}
// Run streaming simulation
try {
const events = eventStore.toJSON();
await runGraphStreamingSimulation(
nodes,
connections,
settingsStore.get(),
codeContext,
events
);
// Auto-open results panel only on first run
if (!hasAutoOpenedPlot) {
showPlot = true;
hasAutoOpenedPlot = true;
}
} catch (error) {
// Auto-open console panel to show error details
showConsole = true;
console.error('Simulation failed:', error);
}
} finally {
isRunStarting = false;
}
}
// Continue simulation from where it left off (streaming)
async function handleContinue() {
// Prevent concurrent continue calls (synchronous check for rapid key presses)
if (!pyodideReady || !hasRunSimulation || simRunning || isContinuing) return;
isContinuing = true;
try {
const settingsDuration = settingsStore.get().duration;
// Use default if duration is empty (same logic as initial run)
const duration = settingsDuration?.trim() ? String(settingsDuration) : String(DEFAULT_SIMULATION_SETTINGS.duration);
await continueStreamingSimulation(duration);
} catch (error) {
showConsole = true;
console.error('Continue simulation failed:', error);
} finally {
isContinuing = false;
}
}
// File operations
async function handleNew() {
if (nodeCount > 0) {
const confirmed = await confirmationStore.show({
title: 'Unsaved Changes',
message: 'Creating a new file will discard your current work. Continue?',
confirmText: 'Discard & Create New',
cancelText: 'Cancel'
});
if (!confirmed) return;
}
newGraph();
// Clear ?model= URL param so the URL reflects a blank canvas
if (window.location.search) {
window.history.replaceState({}, '', window.location.pathname);
}
}
async function handleOpen() {
// Uses unified import system with built-in confirmation
const result = await openImportDialog();
if (result.success && result.type === 'model') {
// Trigger fit view after a brief delay to let nodes render
setTimeout(() => triggerFitView(), 100);
}
}
/**
* Expand GitHub shorthand to raw.githubusercontent.com URL
* Format: owner/repo/path/to/file.pvm
* Expands to: https://raw.githubusercontent.com/owner/repo/main/path/to/file.pvm
*/
function expandGitHubShorthand(shorthand: string): string {
const parts = shorthand.split('/');
if (parts.length < 3) {
throw new Error('Invalid GitHub shorthand. Use: owner/repo/path/to/file.pvm');
}
const owner = parts[0];
const repo = parts[1];
const pathParts = parts.slice(2);
// Default to 'main' branch
const branch = 'main';
const filePath = pathParts.join('/');
return `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${filePath}`;
}
/**
* Load model from URL parameter on page load
*/
async function loadFromUrlParam(): Promise<void> {
if (!urlModelConfig) return;
let url: string;
try {
url = urlModelConfig.isGitHub
? expandGitHubShorthand(urlModelConfig.url)
: urlModelConfig.url;
} catch (e) {
consoleStore.error(`Invalid GitHub shorthand: ${urlModelConfig.url}`);
consoleStore.error('Expected format: owner/repo/path/to/file.pvm');
showConsole = true;
return;
}
const result = await importFromUrl(url);
if (result.success) {
setTimeout(() => triggerFitView(), 100);
} else if (result.error) {
consoleStore.error(`Failed to load model from URL: ${url}`);
consoleStore.error(result.error);
showConsole = true;
}
}
// Track placement offset for stacking prevention
let placementOffset = 0;
let lastPlacementTime = 0;
// Add node from node library sidebar