-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.tsx
More file actions
3646 lines (3193 loc) · 159 KB
/
App.tsx
File metadata and controls
3646 lines (3193 loc) · 159 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 React, { useState, useEffect, useCallback, useRef } from 'react';
import { FileNode, ActivityView, TerminalLine, ProjectSettings, GitState, GitCommit, Problem, WalletConnection, CompilationResult, DeployedContract, TerminalInstance } from './types';
import { INITIAL_FILES, DEFAULT_SETTINGS } from './constants';
import ActivityBar from './components/Layout/ActivityBar';
import SidebarLeft from './components/Layout/SidebarLeft';
import SidebarRight from './components/Layout/SidebarRight';
import TerminalPanel from './components/Layout/TerminalPanel';
import CodeEditor from './components/Editor/CodeEditor';
import EditorTabs from './components/Layout/EditorTabs';
import Header from './components/Layout/Header';
import { Button } from './components/UI/Button';
import { PlayIcon, BotIcon, RocketIcon, BugIcon, UndoIcon, RedoIcon, SaveIcon, EyeIcon, SearchIcon, MessageSquareIcon, AnalyseIcon, RefreshIcon } from './components/UI/Icons';
import { DeploymentNotification } from './components/UI/DeploymentNotification';
import { SpecialTab } from './components/Layout/SpecialTab';
import EmptyState from './components/Layout/EmptyState';
import { ClarityCompiler } from './services/stacks/compiler';
import { StacksWalletService } from './services/stacks/wallet';
import { filesToFileNodes } from './services/templates';
import { GitHubTemplateService } from './services/githubTemplates';
import JSZip from 'jszip';
import Joyride, { Step, CallBackProps, STATUS } from 'react-joyride';
import { io, Socket } from 'socket.io-client';
import { DiscoveryImportType, StacksNetworkType } from './components/Layout/DiscoveryImportModal';
import IntroLoading from './components/UI/IntroLoading';
import { webContainerService } from './services/webContainerService';
import confetti from 'canvas-confetti';
import { Droplets } from 'lucide-react';
import { get, set } from 'idb-keyval';
import FaucetPopover from './components/UI/FaucetPopover';
const CHANGELOG_CONTENT = `# Changelog
All notable changes to the LabSTX IDE will be documented in this file.
## [1.2.0] - 2026-03-07
### Added
- Line ending (LF/CRLF) support in the status bar and editor.
- Changelog button in the status bar.
## [1.1.0] - 2026-03-01
### Added
- Enhanced terminal output with color-coded status messages.
- New project templates for Clarity contracts.
## [1.0.0] - 2026-02-20
### Added
- Initial release of LabSTX IDE.
- Support for Clarity programming language.
- Integrated Stacks wallet connection.
- Clarinet-based compilation and debugging.
`;
function App() {
const [activeView, setActiveView] = useState<ActivityView>(() => {
const saved = localStorage.getItem('labstx_active_view');
return (saved as ActivityView) || ActivityView.EXPLORER;
});
const [hasClarinet, setHasClarinet] = useState(false);
const dialogRef = useRef<HTMLDialogElement>(null);
const handleSelect = (value: 'LF' | 'CRLF') => {
setLineEnding(value);
dialogRef.current?.close();
};
const [loading, setLoading] = useState(true);
useEffect(() => {
localStorage.setItem('labstx_active_view', activeView);
}, [activeView]);
// Theme State
const [theme, setTheme] = useState<'dark' | 'light'>(() => {
return (localStorage.getItem('labstx_theme') as 'dark' | 'light') || 'dark';
});
useEffect(() => {
localStorage.setItem('labstx_theme', theme);
}, [theme]);
// Session State
const [sessionId] = useState(() => {
const saved = sessionStorage.getItem('labstx_session_id');
if (saved) return saved;
const newId = `sess_${Math.random().toString(36).substring(2, 9)}`;
sessionStorage.setItem('labstx_session_id', newId);
return newId;
});
const [firstRunWorkspaces, setFirstRunWorkspaces] = useState<Record<string, boolean>>({});
const [isStateLoaded, setIsStateLoaded] = useState(false);
const [workspaces, setWorkspaces] = useState<Record<string, FileNode[]>>({});
const [activeWorkspace, setActiveWorkspace] = useState(() => {
return localStorage.getItem('labstx_active_workspace') || 'default_workspace';
});
// Persistence logic moved to useEffect below
useEffect(() => {
if (isStateLoaded) {
set('labstx_workspaces', workspaces);
console.log("Saved to IndexedDB"); // Add this to verify it's firing
}
}, [workspaces, isStateLoaded]);
useEffect(() => {
if (isStateLoaded) {
localStorage.setItem('labstx_active_workspace', activeWorkspace);
}
}, [activeWorkspace, isStateLoaded]);
// Workspace Metadata (timestamps, etc)
const [workspaceMetadata, setWorkspaceMetadata] = useState<Record<string, { createdAt: number }>>(() => {
const saved = localStorage.getItem('labstx_workspace_metadata');
if (saved) {
try { return JSON.parse(saved); } catch (e) { return { 'default_workspace': { createdAt: Date.now() } }; }
}
return { 'default_workspace': { createdAt: Date.now() } };
});
useEffect(() => {
localStorage.setItem('labstx_workspace_metadata', JSON.stringify(workspaceMetadata));
}, [workspaceMetadata]);
// History State
const [history, setHistory] = useState<FileNode[][]>([INITIAL_FILES]);
const [historyIndex, setHistoryIndex] = useState(0);
// Derived state for current file tree
const files = history[historyIndex];
useEffect(() => {
const checkClarinet = (nodes: FileNode[]): boolean => {
return nodes.some(node => node.name.toLowerCase() === 'clarinet.toml');
};
setHasClarinet(checkClarinet(files));
}, [files, setHasClarinet]);
// Editor Tabs State with persistence
// Editor Tabs State (non-persistent)
const [openFileIds, setOpenFileIds] = useState<string[]>([]);
const [openSpecialIds, setOpenSpecialIds] = useState<string[]>(['@home']);
const [activeFileId, setActiveFileId] = useState<string | null>(null);
const [activeSpecialId, setActiveSpecialId] = useState<string | null>('@home');
const [activeTabGroup, setActiveTabGroup] = useState<'file' | 'special'>('special');
const [activeContent, setActiveContent] = useState<string>('');
const [pendingNodeCommand, setPendingNodeCommand] = useState<{ command: string, terminalId: string, timestamp: number } | null>(null);
// const [searchFindQuery, setSearchFindQuery] = useState<string>('');
//const [templateProgress, setTemplateProgress] = useState<number | null>(null);
const [activeLanguage, setActiveLanguage] = useState<string>('clarity');
// Tracks which file was last loaded into the editor so we only pull from 'files'
// when the user actually switches tabs — never during normal typing.
const loadedFileIdRef = useRef<string | null>(null);
const sidebarRightRef = useRef<any>(null);
// Simnet State
const [activeSimnetAccount, setActiveSimnetAccount] = useState<string>(() => {
return localStorage.getItem('labstx_active_simnet_account') || 'ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM';
});
useEffect(() => {
localStorage.setItem('labstx_active_simnet_account', activeSimnetAccount);
}, [activeSimnetAccount]);
const handleOpenSimnetScratchpad = () => {
if (!openSpecialIds.includes('@simnet')) {
setOpenSpecialIds(prev => [...prev, '@simnet']);
}
setActiveSpecialId('@simnet');
setActiveTabGroup('special');
};
const [lineEnding, setLineEnding] = useState<'LF' | 'CRLF'>('CRLF');
const [cursorPosition, setCursorPosition] = useState({ lineNumber: 1, column: 1 });
const cursorTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleCursorChange = useCallback((position: { lineNumber: number, column: number }) => {
if (cursorTimeoutRef.current) clearTimeout(cursorTimeoutRef.current);
cursorTimeoutRef.current = setTimeout(() => {
setCursorPosition(position);
}, 100);
}, []);
const [outputLines, setOutputLines] = useState<string[]>([]);
const [problems, setProblems] = useState<Problem[]>([]);
const [terminals, setTerminals] = useState<TerminalInstance[]>(() => [
{ id: 'default', title: 'clarinet', lines: [], isProcessRunning: false }
]);
const [activeTerminalId, setActiveTerminalId] = useState<string>('default');
const [discoveryProgress, setDiscoveryProgress] = useState(0);
const socketRef = useRef<Socket | null>(null);
const activeTerminal = terminals.find(t => t.id === activeTerminalId) || terminals[0];
// Helper to add lines to a specific terminal
const addTerminalLineToInstance = useCallback((terminalId: string, line: Omit<TerminalLine, 'id'>) => {
setTerminals(prev => prev.map(t => {
if (t.id === terminalId) {
return {
...t,
lines: [...t.lines, { ...line, id: Date.now().toString() + Math.random() }]
};
}
return t;
}));
}, []);
const addTerminalLine = useCallback((line: Omit<TerminalLine, 'id'>) => {
addTerminalLineToInstance(activeTerminalId, line);
}, [activeTerminalId, addTerminalLineToInstance]);
const handleClearTerminal = useCallback(() => {
setTerminals(prev => prev.map(t => t.id === activeTerminalId ? { ...t, lines: [] } : t));
}, [activeTerminalId]);
// Compilation & Deployment State
const [compilationResult, setCompilationResult] = useState<CompilationResult | undefined>();
const [wallet, setWallet] = useState<WalletConnection>(() => {
const saved = localStorage.getItem('labstx_wallet');
if (saved) {
try { return JSON.parse(saved); } catch (e) { return { type: 'none', connected: false }; }
}
return { type: 'none', connected: false };
});
useEffect(() => {
localStorage.setItem('labstx_wallet', JSON.stringify(wallet));
}, [wallet]);
const [deployedContracts, setDeployedContracts] = useState<DeployedContract[]>([]);
useEffect(() => {
if (isStateLoaded) {
set('labstx_deployed_contracts', deployedContracts);
}
}, [deployedContracts, isStateLoaded]);
// Initial State Loader and Migration
useEffect(() => {
const loadInitialState = async () => {
try {
// 1. Load Workspaces
let savedWorkspaces = await get('labstx_workspaces');
if (!savedWorkspaces) {
// Try migration from localStorage
const legacy = localStorage.getItem('labstx_workspaces');
if (legacy) {
try {
savedWorkspaces = JSON.parse(legacy);
await set('labstx_workspaces', savedWorkspaces);
localStorage.removeItem('labstx_workspaces');
} catch (e) {
savedWorkspaces = { 'default_workspace': INITIAL_FILES };
}
} else {
savedWorkspaces = { 'default_workspace': INITIAL_FILES };
}
}
setWorkspaces(savedWorkspaces);
// 2. Load Active Workspace (stays in localStorage as it is small)
const savedActive = localStorage.getItem('labstx_active_workspace');
if (savedActive) setActiveWorkspace(savedActive);
// 3. Load Deployed Contracts
let savedContracts = await get('labstx_deployed_contracts');
if (!savedContracts) {
// Try migration from localStorage
const legacy = localStorage.getItem('labstx_deployed_contracts');
if (legacy) {
try {
savedContracts = JSON.parse(legacy);
await set('labstx_deployed_contracts', savedContracts);
localStorage.removeItem('labstx_deployed_contracts');
} catch (e) {
savedContracts = [];
}
} else {
savedContracts = [];
}
}
// Filter out simnet contracts as they are transient
const filteredContracts = (savedContracts || []).filter((c: any) => c.network !== 'simnet');
setDeployedContracts(filteredContracts);
// 4. Update History with initial files of the active workspace
const activeFiles = savedWorkspaces[savedActive || 'default_workspace'] || INITIAL_FILES;
setHistory([activeFiles]);
setIsStateLoaded(true);
console.log('[Persistence] State loaded from IndexedDB');
} catch (err) {
console.error('[Persistence] Failed to load state:', err);
// Fallback to defaults
setWorkspaces({ 'default_workspace': INITIAL_FILES });
setHistory([INITIAL_FILES]);
setIsStateLoaded(true);
}
};
loadInitialState();
}, []);
const handleOpenNewProject = () => {
if (!openSpecialIds.includes('@new-project')) {
setOpenSpecialIds(prev => [...prev, '@new-project']);
}
setActiveSpecialId('@new-project');
setActiveTabGroup('special');
};
// Deployment Notification State
const [notification, setNotification] = useState<{ deployHash: string; network: string, contractName?: string } | null>(null);
// Project Settings with localStorage persistence
const [settings, setSettings] = useState<ProjectSettings>(() => {
const saved = localStorage.getItem('labstx_settings');
if (saved) {
try {
return { ...DEFAULT_SETTINGS, ...JSON.parse(saved) };
} catch (e) {
return DEFAULT_SETTINGS;
}
}
return DEFAULT_SETTINGS;
});
useEffect(() => {
localStorage.setItem('labstx_settings', JSON.stringify(settings));
}, [settings]);
const [isAiQuotaReached, setIsAiQuotaReached] = useState(false);
const [aiStats, setAiStats] = useState<{ aiInteractions: number; aiQuotaLimit: number } | null>(null);
const [templateProgress, setTemplateProgress] = useState<number | null>(null);
const [prefilledContractInfo, setPrefilledContractInfo] = useState<{ address: string; name: string } | null>(null);
const handleGoToInteract = useCallback((contractHash: string) => {
const [address, name] = contractHash.split('.');
setPrefilledContractInfo({ address, name });
setActiveView(ActivityView.CALL_CONTRACT);
}, []);
const handleOpenContractCall = useCallback((contractHash: string) => {
const tabId = `@contract-call-${contractHash}`;
if (!openSpecialIds.includes(tabId)) {
setOpenSpecialIds(prev => [...prev, tabId]);
}
setActiveSpecialId(tabId);
setActiveTabGroup('special');
}, [openSpecialIds]);
// AI Quota Checker
const handleCheckAiQuota = useCallback(async () => {
if (!wallet.address || wallet.address === 'unconnected') return;
try {
const backendUrl = import.meta.env.VITE_BACKEND_URL;
const res = await fetch(`${backendUrl}/ide-api/stats/user/${wallet.address}`);
if (res.ok) {
const stats = await res.json();
setAiStats({
aiInteractions: stats.aiInteractions,
aiQuotaLimit: stats.aiQuotaLimit
});
if (stats.aiInteractions >= stats.aiQuotaLimit) {
setIsAiQuotaReached(true);
} else {
setIsAiQuotaReached(false);
}
}
} catch (err) {
console.error('[AI Quota Checker] Failed:', err);
}
}, [wallet.address]);
useEffect(() => {
handleCheckAiQuota();
// Check every 6 minutes while app is active
const interval = setInterval(handleCheckAiQuota, 6 * 60 * 1000);
return () => clearInterval(interval);
}, [handleCheckAiQuota]);
// Editing State
const [dirtyFileIds, setDirtyFileIds] = useState<string[]>([]);
const [deletedFilePaths, setDeletedFilePaths] = useState<string[]>([]);
const [editorAction, setEditorAction] = useState<{ type: 'save' | 'gotoLine' | null, timestamp: number, line?: number, column?: number }>({ type: null, timestamp: 0 });
// Search-in-code state (synced to Monaco's find widget)
const [editorSearchQuery, setEditorSearchQuery] = useState<string>('');
const [searchFindQuery, setSearchFindQuery] = useState<string | undefined>(undefined);
const searchDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const historyDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Debounce the find query passed to the editor (avoids firing on every keystroke)
const handleSearchChange = useCallback((value: string) => {
setEditorSearchQuery(value);
if (searchDebounceRef.current) clearTimeout(searchDebounceRef.current);
searchDebounceRef.current = setTimeout(() => {
setSearchFindQuery(value);
}, 200);
}, []);
// Git State
const [gitState, setGitState] = useState<GitState>({
modifiedFiles: [],
stagedFiles: [],
commits: [
// Simulated History
{ id: 'c-5', message: 'Merge branch feature/staking', date: Date.now() - 3600000, hash: '8f2a1b', branch: 'main', parents: ['c-4', 'c-3'] },
{ id: 'c-4', message: 'Update project configuration', date: Date.now() - 7200000, hash: '7e1c9d', branch: 'main', parents: ['c-2'] },
{ id: 'c-3', message: 'Implement staking contract logic', date: Date.now() - 86400000, hash: '6d4e5f', branch: 'feature/staking', parents: ['c-1'] },
{ id: 'c-2', message: 'Refactor utility functions', date: Date.now() - 172800000, hash: '5c3b2a', branch: 'main', parents: ['c-1'] },
{ id: 'c-1', message: 'Initial commit ✨', date: Date.now() - 259200000, hash: '4b2a1c', branch: 'main', parents: [] },
],
branch: 'main'
});
// Layout State
const [leftWidth, setLeftWidth] = useState(300);
const [rightWidth, setRightWidth] = useState(450);
const [terminalHeight, setTerminalHeight] = useState(200);
const [isLeftSidebarVisible, setIsLeftSidebarVisible] = useState(true);
const [isRightSidebarVisible, setIsRightSidebarVisible] = useState(false);
const [isTerminalVisible, setIsTerminalVisible] = useState(false);
const [isTerminalMaximized, setIsTerminalMaximized] = useState(false);
// Faucet State
const [isFaucetOpen, setIsFaucetOpen] = useState(false);
const [faucetAnchorRect, setFaucetAnchorRect] = useState<DOMRect | null>(null);
// Layout Toggles
const toggleLeftSidebar = () => setIsLeftSidebarVisible(!isLeftSidebarVisible);
const toggleRightSidebar = () => setIsRightSidebarVisible(!isRightSidebarVisible);
const toggleTerminal = () => setIsTerminalVisible(!isTerminalVisible);
const toggleTerminalMaximize = () => {
const next = !isTerminalMaximized;
setIsTerminalMaximized(next);
if (next) setIsTerminalVisible(true);
};
// --- Onboarding Tour State ---
const ONBOARDING_STEPS: Step[] = [
{
target: 'body',
content: (
<div className="text-left">
<h3 className="text-lg font-bold text-labstx-orange mb-2">Welcome to LabSTX! ✨</h3>
<p>The premier development environment for Clarity smart contracts on the Stacks blockchain.</p>
</div>
),
placement: 'center',
disableBeacon: true,
},
{
target: '#workspace-selector',
content: 'Manage your projects here. You can create, rename, import, and even sync workspaces directly from the server.',
placement: 'bottom',
},
{
target: '#home-button',
content: 'The Home view is your dashboard. Access smart contract templates and follow walkthroughs to learn Clarity.',
placement: 'right',
},
{
target: '#view-explorer',
content: 'Your file system at a glance. Create folders, contracts, and markdown documentation here.',
placement: 'right',
},
{
target: '#editor-search-input',
content: 'Quickly find and replace text across your active file with powerful search tools.',
placement: 'bottom',
},
{
target: '#preview-button',
content: 'Switch to Preview mode to see rendered Markdown or explore the ABI specification of your Clarity contracts.',
placement: 'bottom',
},
{
target: '#check-button',
content: 'Run a syntax and logic check on your current Clarity contract using Clarinet.',
placement: 'bottom',
},
{
target: '#deploy-button',
content: 'Deploy your contracts to Stacks Mainnet, Testnet when you are ready.',
placement: 'bottom',
},
{
target: '#ai-assistant-button',
content: 'Open the LabSTX AI Assistant to help you write, explain, and debug Clarity code.',
placement: 'left',
},
{
target: '#terminal-panel',
content: 'Interact with the Stacks blockchain, view compiler output, and track code problems in real-time.',
placement: 'top',
},
{
target: '#status-bar',
content: 'Stay updated on your Problem count, line numbers, and the latest LabSTX improvements via the Changelog.',
placement: 'top',
},
{
target: '#layout-controls',
content: 'Customize your layout! Toggle the sidebars, panels, and switch between light and dark themes.',
placement: 'bottom',
}
];
const COMPILE_DEPLOY_STEPS: Step[] = [
{
target: 'body',
content: (
<div className="text-left">
<h3 className="text-lg font-bold text-labstx-orange mb-2">Compile & Deploy 🚀</h3>
<p>Learn how to turn your Clarity code into a live smart contract on the Stacks blockchain.</p>
</div>
),
placement: 'center',
disableBeacon: true,
},
{
target: '#view-explorer',
content: 'First, open a Clarity contract from the Explorer. Most contracts are located in the "contracts" folder.',
placement: 'right',
},
{
target: '#check-button',
content: 'Use the Compile button (at the top of the editor) to run a static analysis. It catches syntax errors before you deploy.',
placement: 'bottom',
},
{
target: '#deploy-button',
content: 'When you are ready, click Deploy. This will open the deployment panel where you can choose your network (Mainnet, Testnet, or Simnet).',
placement: 'bottom',
},
{
target: '#terminal-panel',
content: 'Watch the terminal for deployment logs. You will see the transaction hash and deployment status here.',
placement: 'top',
},
{
target: '#view-activity_history',
content: 'Check the Activity History to see all your past deployments and interactions with the blockchain.',
placement: 'right',
}
];
const [runTour, setRunTour] = useState(false);
const [activeTourId, setActiveTourId] = useState('getting-started');
const [tourSteps, setTourSteps] = useState<Step[]>(ONBOARDING_STEPS);
const handleStartTour = useCallback((tourId: string) => {
// Force reset by clearing then setting
setRunTour(false);
setTimeout(() => {
setActiveTourId(tourId);
if (tourId === 'getting-started') {
setTourSteps(ONBOARDING_STEPS);
} else if (tourId === 'compile-deploy') {
setTourSteps(COMPILE_DEPLOY_STEPS);
}
setRunTour(true);
}, 10);
}, []);
useEffect(() => {
const hasSeenTour = localStorage.getItem('labstx_has_seen_tour');
if (!hasSeenTour) {
setRunTour(true);
}
}, []);
const handleTourCallback = (data: CallBackProps) => {
const { status } = data;
if ([STATUS.FINISHED, STATUS.SKIPPED].includes(status as any)) {
setRunTour(false);
localStorage.setItem('labstx_has_seen_tour', 'true');
}
};
// Initialize WebContainer
// App.tsx - Update the initWC effect
useEffect(() => {
const initWC = async () => {
// Only proceed if the workspace data has finished loading from IndexedDB
if (!isStateLoaded) return;
try {
await webContainerService.boot();
console.log('[WebContainer] Booted successfully');
// Now 'files' contains your actual saved workspace
const wcFiles = transformFilesToWC(files);
await webContainerService.mountFiles(wcFiles);
console.log('[WebContainer] Files mounted with saved workspace');
} catch (err) {
console.error('[WebContainer] Boot failed:', err);
}
};
initWC();
}, [isStateLoaded]); // Add isStateLoaded as a dependency
// Helper to transform FileNode[] to WebContainer FS format
const transformFilesToWC = (nodes: FileNode[]): any => {
const result: any = {};
nodes.forEach(node => {
if (node.type === 'file') {
result[node.name] = {
file: {
contents: node.content || '',
},
};
} else if (node.children) {
result[node.name] = {
directory: transformFilesToWC(node.children),
};
}
});
return result;
};
// Helper to sync nodes to WebContainer VFS
const syncNodesToWebContainer = useCallback(async (nodes: FileNode[]) => {
try {
const wc = await webContainerService.boot();
if (!wc) return;
await webContainerService.clearFileSystem();
const wcFiles = transformFilesToWC(nodes);
await webContainerService.mountFiles(wcFiles);
console.log('[WebContainer] VFS synchronized');
} catch (err) {
console.error('[WebContainer] VFS sync failed:', err);
}
}, []);
const handleKillProcess = useCallback((id: string) => {
const term = terminals.find(t => t.id === id);
if (term?.isProcessRunning && socketRef.current) {
socketRef.current.emit('terminal:kill', { sessionId, terminalId: id });
setTerminals(prev => prev.map(t => t.id === id ? { ...t, isProcessRunning: false } : t));
addTerminalLineToInstance(id, { type: 'error', content: 'Process stopped by user.' });
}
}, [terminals, sessionId, addTerminalLineToInstance]);
const handleEnsureNodeTerminal = useCallback(() => {
const nodeTerm = terminals.find(t => t.type === 'webcontainer');
if (nodeTerm) {
setActiveTerminalId(nodeTerm.id);
} else {
const newId = `term_${Math.random().toString(36).substring(2, 9)}`;
setTerminals(prev => [
...prev,
{ id: newId, title: 'node', lines: [], isProcessRunning: false, type: 'webcontainer' }
]);
setActiveTerminalId(newId);
}
setIsTerminalVisible(true);
}, [terminals]);
const handleAddTerminal = (type: 'server' | 'webcontainer' = 'server') => {
const newId = `term_${Math.random().toString(36).substring(2, 9)}`;
setTerminals(prev => [
...prev,
{ id: newId, title: type === 'webcontainer' ? 'node' : 'clarinet', lines: [], isProcessRunning: false, type }
]);
setActiveTerminalId(newId);
};
const handleRemoveTerminal = (id: string) => {
if (terminals.length <= 1) return;
// Kill process on backend if running
const term = terminals.find(t => t.id === id);
if (term?.isProcessRunning && socketRef.current) {
socketRef.current.emit('terminal:kill', { sessionId, terminalId: id });
}
setTerminals(prev => {
const newTerminals = prev.filter(t => t.id !== id);
if (activeTerminalId === id) {
setActiveTerminalId(newTerminals[newTerminals.length - 1].id);
}
return newTerminals;
});
};
const handleRunNodeCommand = useCallback((command: string) => {
setIsTerminalVisible(true);
// Switch to node terminal if it exists
const nodeTerm = terminals.find(t => t.type === 'webcontainer');
if (nodeTerm) {
setActiveTerminalId(nodeTerm.id);
} else {
handleEnsureNodeTerminal();
}
// We need to trigger execution in TerminalPanel.
// I'll add a state to track the command to be executed.
setPendingNodeCommand({
command,
terminalId: nodeTerm ? nodeTerm.id : 'temp', // If temp, the new terminal will pick it up
timestamp: Date.now()
});
}, [terminals, handleEnsureNodeTerminal]);
// --- Deep Link Handling ---
const handleDeepLink = useCallback(() => {
const params = new URLSearchParams(window.location.search);
// 1. Template Deep Link
const templateId = params.get('template_id');
if (templateId) {
const loadDeepLinkTemplate = async () => {
try {
const templates = await GitHubTemplateService.fetchTemplates();
const template = templates.find(t => t.id === templateId);
if (template) {
const workspaceName = `${template.name} (Imported)`;
const files = await GitHubTemplateService.fetchTemplateFiles(template.path);
const newRoot = GitHubTemplateService.templateToFileNodes(files);
setWorkspaces(prev => ({ ...prev, [workspaceName]: newRoot }));
setWorkspaceMetadata(prev => ({ ...prev, [workspaceName]: { createdAt: Date.now() } }));
setActiveWorkspace(workspaceName);
setHistory([newRoot]);
setHistoryIndex(0);
setOpenFileIds([]);
setActiveFileId(null);
setActiveTabGroup('file');
addTerminalLine({ type: 'success', content: `Imported template from GitHub: ${template.name}` });
syncNodesToWebContainer(newRoot);
// If not a clarity template or no Clarinet.toml, switch to node terminal
const hasClarinet = newRoot.some(node => node.name.toLowerCase() === 'clarinet.toml');
if (!hasClarinet || template.type !== 'clarity') {
handleEnsureNodeTerminal();
}
// Clear URL params
window.history.replaceState({}, document.title, window.location.pathname);
}
} catch (err) {
console.error('Failed to load deep link template:', err);
addTerminalLine({ type: 'error', content: 'Failed to load template from GitHub deep link.' });
}
};
loadDeepLinkTemplate();
return;
}
// 2. Snippet Deep Link
const snippetCodeBase64 = params.get('snippet_code');
if (snippetCodeBase64) {
try {
const code = decodeURIComponent(escape(window.atob(snippetCodeBase64)));
const name = params.get('snippet_name') || 'snippet.clar';
const lang = params.get('snippet_lang') || 'clarity';
const newFile: FileNode = {
id: `${name}-${Date.now()}`,
name,
type: 'file',
language: lang,
content: code
};
setWorkspaces(prev => {
const currentFiles = prev[activeWorkspace] || INITIAL_FILES;
const contractsFolder = currentFiles.find(n => n.name === 'contracts' && n.type === 'folder');
let updatedFiles;
if (contractsFolder && contractsFolder.children) {
updatedFiles = currentFiles.map(n =>
n.id === contractsFolder.id
? { ...n, children: [...(n.children || []), newFile] }
: n
);
} else {
updatedFiles = [...currentFiles, newFile];
}
syncNodesToWebContainer(updatedFiles);
return { ...prev, [activeWorkspace]: updatedFiles };
});
setActiveFileId(newFile.id);
setOpenFileIds(prev => prev.includes(newFile.id) ? prev : [...prev, newFile.id]);
setActiveTabGroup('file');
addTerminalLine({ type: 'success', content: `Loaded snippet: ${name}` });
// Clear URL params
window.history.replaceState({}, document.title, window.location.pathname);
} catch (e) {
console.error('Failed to decode snippet:', e);
addTerminalLine({ type: 'error', content: 'Failed to decode snippet code.' });
}
}
}, [activeWorkspace, addTerminalLine, syncNodesToWebContainer, handleEnsureNodeTerminal]);
useEffect(() => {
// Run deep link handling after a short delay to ensure initial state is settled
const timer = setTimeout(() => {
handleDeepLink();
}, 500);
return () => clearTimeout(timer);
}, [handleDeepLink]);
// Prevent data loss and clear session on close
useEffect(() => {
const handleBeforeUnload = (e: BeforeUnloadEvent) => {
const message = "Are you sure you want to leave? Your temporary session will be cleared and the workspace folder on the server will be deleted.";
e.preventDefault();
e.returnValue = message; // Traditional browser-standard way to show "Are you sure?"
return message;
};
const handleUnload = () => {
// Use sendBeacon to ensure the request is sent even during tab closure
const payload = JSON.stringify({ sessionId });
const blob = new Blob([payload], { type: 'application/json' });
navigator.sendBeacon('/ide-api/project/session/clear', blob);
};
window.addEventListener('beforeunload', handleBeforeUnload);
window.addEventListener('unload', handleUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
window.removeEventListener('unload', handleUnload);
};
}, [sessionId]);
// Resizing Logic
const startResizing = useCallback((direction: 'left' | 'right') => (mouseDownEvent: React.MouseEvent) => {
mouseDownEvent.preventDefault();
const startX = mouseDownEvent.clientX;
const startWidth = direction === 'left' ? leftWidth : rightWidth;
const doDrag = (mouseMoveEvent: MouseEvent) => {
if (direction === 'left') {
const newWidth = startWidth + mouseMoveEvent.clientX - startX;
setLeftWidth(Math.max(160, Math.min(newWidth, 600)));
} else {
const newWidth = startWidth - (mouseMoveEvent.clientX - startX);
setRightWidth(Math.max(240, Math.min(newWidth, 600)));
}
};
const stopDrag = () => {
document.removeEventListener('mousemove', doDrag);
document.removeEventListener('mouseup', stopDrag);
document.body.style.cursor = 'default';
document.body.style.userSelect = 'auto';
};
document.addEventListener('mousemove', doDrag);
document.addEventListener('mouseup', stopDrag);
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
}, [leftWidth, rightWidth]);
// Terminal Resizing Logic
const startTerminalResizing = useCallback((mouseDownEvent: React.MouseEvent) => {
mouseDownEvent.preventDefault();
const startY = mouseDownEvent.clientY;
const startHeight = terminalHeight;
const doDrag = (mouseMoveEvent: MouseEvent) => {
const deltaY = startY - mouseMoveEvent.clientY; // Inverted because we're resizing from top
const newHeight = startHeight + deltaY;
setTerminalHeight(Math.max(100, Math.min(newHeight, 600)));
};
const stopDrag = () => {
document.removeEventListener('mousemove', doDrag);
document.removeEventListener('mouseup', stopDrag);
document.body.style.cursor = 'default';
document.body.style.userSelect = 'auto';
};
document.addEventListener('mousemove', doDrag);
document.addEventListener('mouseup', stopDrag);
document.body.style.cursor = 'row-resize';
document.body.style.userSelect = 'none';
}, [terminalHeight]);
const handleConnectWallet = useCallback(() => {
setActiveView(ActivityView.DEPLOY);
setIsLeftSidebarVisible(true);
}, []);
// Recursively find file by ID
const findFile = (nodes: FileNode[], id: string): FileNode | null => {
for (const node of nodes) {
if (node.id === id) return node;
if (node.children) {
const found = findFile(node.children, id);
if (found) return found;
}
}
return null;
};
// Recursively find file by name
const findFileByName = (nodes: FileNode[], name: string): FileNode | null => {
for (const node of nodes) {
if (node.type === 'file' && node.name === name) return node;
if (node.children) {
const found = findFileByName(node.children, name);
if (found) return found;
}
}
return null;
};
// Recursively get the path for a given file ID
const getFilePath = (nodes: FileNode[], targetId: string, currentPath = ''): string | null => {
for (const node of nodes) {
const newPath = currentPath ? `${currentPath}/${node.name}` : node.name;
if (node.id === targetId) return newPath;
if (node.children) {
const found = getFilePath(node.children, targetId, newPath);
if (found) return found;
}
}
return null;
};
// Find file by its full path
const findFileByPath = (nodes: FileNode[], targetPath: string, currentPath = ''): FileNode | null => {
for (const node of nodes) {
const nodePath = currentPath ? `${currentPath}/${node.name}` : node.name;
if (nodePath === targetPath) return node;
if (node.children) {
const found = findFileByPath(node.children, targetPath, nodePath);
if (found) return found;
}
}
return null;
};
// Navigate the editor to a specific file + line/column (used by Problems "Locate")
const handleLocateProblem = useCallback((fileName: string, line: number, column: number) => {
const target = findFile(files, fileName);
if (!target) return;
// Open & activate the file tab
if (!openFileIds.includes(target.id)) {
setOpenFileIds(prev => [...prev, target.id]);
}
setActiveFileId(target.id);
setActiveTabGroup('file');
// Slight delay so Monaco mounts the new file before we jump
setTimeout(() => {
setEditorAction({ type: 'gotoLine', timestamp: Date.now(), line, column });
}, 80);
}, [files, openFileIds]);
const handleExplainCode = useCallback(() => {
if (!activeFileId) return;
const file = findFile(files, activeFileId);
if (!file) return;
const command = `Act as an expert Clarity smart contract developer.
Analyze the file @${file.name} and provide a comprehensive, line-by-line technical breakdown.
For each block of code:
1. Explain the specific logic and syntax used.
2. Identify any state changes (data-set, data-get, etc.).
3. Highlight security considerations or Stacks-specific patterns.
Break the explanation down into clear, readable sections.`;
if (!isRightSidebarVisible) {
setIsRightSidebarVisible(true);
setTimeout(() => {
sidebarRightRef.current?.sendMessage(command);
}, 300);
} else {
sidebarRightRef.current?.sendMessage(command);
}
}, [activeFileId, files, isRightSidebarVisible]);
const handleAnalyseCode = useCallback(() => {
if (!activeFileId) return;
const file = findFile(files, activeFileId);
if (!file) return;
const command = `Act as a senior Clarity software architect.
Perform a deep structural and logical analysis of the smart contract @${file.name}.