vb6parse 1.0.0

vb6parse is a library for parsing and analyzing VB6 code, from projects, to controls, to modules, and forms.
Documentation
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
/**
 * VB6Parse Playground - Main Application Module
 * 
 * Entry point that coordinates all other modules:
 * - Initializes WASM module
 * - Sets up editor
 * - Handles UI events
 * - Coordinates parsing and rendering
 * 
 * TODO: Wire up all event handlers
 * TODO: Implement auto-parse with debouncing
 * TODO: Add URL sharing functionality
 */

import { getExample } from './examples.js';
import * as Parser from './parser.js';
import * as Editor from './editor.js';
import * as Renderer from './renderer.js';
import * as TreeViz from './tree-viz.js';

// Application state
const state = {
    currentFileType: 'module',
    autoParse: true,
    parseTimeout: null,
    lastParseResult: null,
    isInitialized: false,
    activeTab: 'tokens'
};

/**
 * Main initialization function
 * Called when DOM is ready
 */
async function init() {
    console.log('🚀 Initializing VB6Parse Playground...');

    try {
        // Show loading overlay
        showLoading('Initializing WASM module...');

        // Initialize WASM module
        const wasmOk = await Parser.initWasm();
        if (!wasmOk) {
            throw new Error('Failed to initialize WASM module');
        }

        // Initialize editor
        await Editor.initEditor('editor-container');

        // Initialize tree visualization
        TreeViz.initTreeViz('tree-viz-container');

        // Set up event listeners
        setupEventListeners();

        // Load from localStorage if available
        loadFromLocalStorage();

        // Hide loading overlay
        hideLoading();

        state.isInitialized = true;
        console.log('✅ Playground initialized successfully');

    } catch (error) {
        console.error('❌ Initialization failed:', error);
        showError(`Failed to initialize playground: ${error.message}`);
        hideLoading();
    }
}

/**
 * Set up all event listeners
 */
function setupEventListeners() {
    // File type selector
    document.getElementById('file-type')?.addEventListener('change', handleFileTypeChange);

    // Examples selector
    document.getElementById('examples')?.addEventListener('change', handleExampleChange);

    // Parse button
    document.getElementById('parse-btn')?.addEventListener('click', handleParse);

    // Share button
    document.getElementById('share-btn')?.addEventListener('click', handleShare);

    // Clear button
    document.getElementById('clear-btn')?.addEventListener('click', handleClear);

    // Auto-parse toggle
    document.getElementById('auto-parse')?.addEventListener('change', handleAutoParseToggle);

    // Tab navigation
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', () => handleTabChange(btn.dataset.tab));
    });

    // Editor highlight events from CST nodes
    document.addEventListener('highlightNodeInEditor', handleHighlightNode);
    document.addEventListener('highlightAndPositionCursor', handleHighlightAndPosition);
    document.addEventListener('clearEditorHighlight', handleClearHighlight);

    // Token filter
    document.getElementById('show-whitespace')?.addEventListener('change', () => {
        if (state.lastParseResult) {
            Renderer.renderTokensTab(state.lastParseResult.tokens);
        }
    });

    document.getElementById('token-filter')?.addEventListener('change', handleTokenFilter);
    document.getElementById('token-search')?.addEventListener('input', handleTokenSearch);

    // CST controls
    document.getElementById('expand-all')?.addEventListener('click', handleExpandAll);
    document.getElementById('collapse-all')?.addEventListener('click', handleCollapseAll);
    document.getElementById('show-byte-ranges')?.addEventListener('change', () => {
        if (state.lastParseResult) {
            Renderer.renderCstTab(state.lastParseResult.cst);
        }
    });

    // Tree visualization controls
    document.getElementById('tree-layout-toggle')?.addEventListener('click', TreeViz.toggleLayout);
    document.getElementById('tree-fit')?.addEventListener('click', TreeViz.fitToScreen);
    document.getElementById('tree-reset-zoom')?.addEventListener('click', TreeViz.resetZoom);

    // Editor content change (for auto-parse)
    document.addEventListener('editorContentChanged', handleEditorChange);

    // Editor click event (for token highlighting)
    document.addEventListener('editorCursorPositionChange', handleEditorCursorChange);

    // Highlight in editor (from renderer)
    document.addEventListener('highlightInEditor', handleHighlightRequest);

    // Theme toggle (inherited from main site)
    document.getElementById('theme-toggle')?.addEventListener('click', handleThemeToggle);

    // Resizer for split panel
    setupResizer();

    // Window resize
    window.addEventListener('resize', handleWindowResize);

    console.log('✅ Event listeners set up');
}

/**
 * Handle file type change
 */
function handleFileTypeChange(e) {
    state.currentFileType = e.target.value;
    Editor.setFileType(state.currentFileType);
    console.log(`📄 File type changed to: ${state.currentFileType}`);

    // Auto-parse if enabled
    if (state.autoParse) {
        debouncedParse();
    }
}

/**
 * Handle example selection
 */
function handleExampleChange(e) {
    const exampleId = e.target.value;
    if (!exampleId) return;

    const example = getExample(exampleId);
    if (!example) {
        console.error(`Example ${exampleId} not found`);
        return;
    }

    // Set file type
    document.getElementById('file-type').value = example.fileType;
    state.currentFileType = example.fileType;

    // Load code into editor
    Editor.setEditorContent(example.code);

    // Auto-parse if enabled
    if (state.autoParse) {
        handleParse();
    }

    // Reset selector
    e.target.value = '';

    console.log(`📝 Loaded example: ${example.name}`);
}

/**
 * Handle parse button click
 */
async function handleParse() {
    if (!state.isInitialized) {
        showError('Playground not initialized yet');
        return;
    }

    const code = Editor.getEditorContent();
    if (!code || code.trim().length === 0) {
        return;
    }

    try {
        console.log(`🔍 Parsing ${state.currentFileType}...`);

        // Parse code
        const result = await Parser.parseCode(code, state.currentFileType);
        state.lastParseResult = result;

        // Render results
        Renderer.renderOutput(result);
        TreeViz.renderTree(result.cst);

        console.log(` Parse complete in ${result.parseTimeMs.toFixed(2)}ms`);

    } catch (error) {
        console.error('❌ Parse failed:', error);
        showError(`Parse failed: ${error.message}`);
    }
}

/**
 * Handle editor content change (for auto-parse)
 */
function handleEditorChange() {
    if (state.autoParse) {
        debouncedParse();
    }

    // Save to localStorage
    saveToLocalStorage();
}

/**
 * Debounced parse (500ms delay)
 */
function debouncedParse() {
    if (state.parseTimeout) {
        clearTimeout(state.parseTimeout);
    }

    state.parseTimeout = setTimeout(() => {
        handleParse();
    }, 500);
}

/**
 * Handle auto-parse toggle
 */
function handleAutoParseToggle(e) {
    state.autoParse = e.target.checked;
    console.log(`🔄 Auto-parse ${state.autoParse ? 'enabled' : 'disabled'}`);
}

/**
 * Handle share button click
 * TODO: Implement URL encoding and sharing
 */
function handleShare() {
    console.log('🔧 TODO: Implement share functionality');
    
    // TODO: Encode code and file type in URL
    // const code = Editor.getEditorContent();
    // const encoded = btoa(encodeURIComponent(code));
    // const url = `${window.location.origin}${window.location.pathname}?code=${encoded}&type=${state.currentFileType}`;
    
    // TODO: Copy to clipboard or show share dialog
    showError('Share functionality coming soon!');
}

/**
 * Handle clear button click
 */
function handleClear() {
    if (confirm('Clear editor and output?')) {
        Editor.clearEditor();
        Renderer.clearOutput();
        TreeViz.clearTree();
        state.lastParseResult = null;
        console.log('🗑️ Cleared editor and output');
    }
}

/**
 * Handle tab change
 */
function handleTabChange(tabId) {
    // Update active tab in state
    state.activeTab = tabId;

    // Update tab buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.tab === tabId);
    });

    // Update tab panes
    document.querySelectorAll('.tab-pane').forEach(pane => {
        pane.classList.toggle('active', pane.id === `${tabId}-tab`);
    });

    console.log(`📑 Switched to ${tabId} tab`);

    // Initialize tree viz if switching to tree tab for the first time
    if (tabId === 'tree' && state.lastParseResult) {
        TreeViz.renderTree(state.lastParseResult.cst);
    }
}

/**
 * Handle token filter
 * TODO: Implement token filtering
 */
function handleTokenFilter(e) {
    console.log('🔧 TODO: Implement token filter:', e.target.value);
}

/**
 * Handle token search
 * TODO: Implement token search
 */
function handleTokenSearch(e) {
    console.log('🔧 TODO: Implement token search:', e.target.value);
}

/**
 * Handle expand all (CST)
 */
function handleExpandAll() {
    document.querySelectorAll('.cst-node.collapsed').forEach(node => {
        node.classList.remove('collapsed');
    });
}

/**
 * Handle collapse all (CST)
 */
function handleCollapseAll() {
    document.querySelectorAll('.cst-node').forEach(node => {
        if (node.querySelector('.cst-node-children')) {
            node.classList.add('collapsed');
        }
    });
}

/**
 * Handle highlight request from renderer
 */
function handleHighlightRequest(e) {
    const { line, column, length } = e.detail;
    Editor.highlightRange(line, column, line, column + length);
}

/**
 * Handle highlighting a CST node in the editor (hover)
 */
function handleHighlightNode(e) {
    const { startOffset, endOffset } = e.detail;
    
    // Convert byte offsets to Monaco positions
    const startPos = Editor.byteOffsetToPosition(startOffset);
    const endPos = Editor.byteOffsetToPosition(endOffset);
    
    // Highlight the range
    Editor.highlightRange(
        startPos.lineNumber,
        startPos.column,
        endPos.lineNumber,
        endPos.column
    );
}

/**
 * Handle highlighting and positioning cursor (click)
 */
function handleHighlightAndPosition(e) {
    const { startOffset, endOffset } = e.detail;
    
    // Convert byte offsets to Monaco positions
    const startPos = Editor.byteOffsetToPosition(startOffset);
    const endPos = Editor.byteOffsetToPosition(endOffset);
    
    // Highlight the range
    Editor.highlightRange(
        startPos.lineNumber,
        startPos.column,
        endPos.lineNumber,
        endPos.column
    );
    
    // Set cursor to start position
    Editor.setCursorToPosition(startPos.lineNumber, startPos.column);
}

/**
 * Handle clearing editor highlight
 */
function handleClearHighlight() {
    Editor.clearHighlight();
}

/**
 * Handle editor cursor position change (for token/CST highlighting)
 */
function handleEditorCursorChange(e) {
    // Only process if tokens or CST tab is active and we have parse results
    if (!state.lastParseResult) {
        return;
    }

    const { lineNumber, column } = e.detail;
    
    if (state.activeTab === 'tokens') {
        // Find and highlight token at this position
        const token = findTokenAtPosition(state.lastParseResult.tokens, lineNumber, column);
        if (token) {
            highlightTokenRow(token);
        }
    } else if (state.activeTab === 'cst') {
        // Find and highlight CST node at this position
        const byteOffset = positionToByteOffset(lineNumber, column);
        if (byteOffset !== null && state.lastParseResult.cst) {
            const node = findMostSpecificCstNode(state.lastParseResult.cst, byteOffset);
            if (node) {
                highlightCstNode(node);
            }
        }
    }
}

/**
 * Find the most specific token that contains the given position
 * @param {Array} tokens - Array of token objects
 * @param {number} line - Line number (1-based)
 * @param {number} column - Column number (1-based)
 * @returns {object|null} The matching token or null
 */
function findTokenAtPosition(tokens, line, column) {
    // Find all tokens on the same line
    const tokensOnLine = tokens.filter(t => t.line === line);
    
    // Find token that contains this column position
    for (const token of tokensOnLine) {
        const tokenEnd = token.column + token.length;
        if (column >= token.column && column < tokenEnd) {
            return token;
        }
    }
    
    return null;
}

/**
 * Highlight a token row in the tokens table
 * @param {object} token - Token object to highlight
 */
function highlightTokenRow(token) {
    // Remove previous highlights
    document.querySelectorAll('.tokens-table tbody tr.highlighted').forEach(row => {
        row.classList.remove('highlighted');
    });
    
    // Find and highlight the matching row
    const rows = document.querySelectorAll('.tokens-table tbody tr');
    for (const row of rows) {
        const rowLine = parseInt(row.dataset.line);
        const rowColumn = parseInt(row.dataset.column);
        
        if (rowLine === token.line && rowColumn === token.column) {
            row.classList.add('highlighted');
            // Scroll into view
            row.scrollIntoView({ behavior: 'smooth', block: 'center' });
            break;
        }
    }
}

/**
 * Convert editor position to byte offset
 * @param {number} line - Line number (1-based)
 * @param {number} column - Column number (1-based)
 * @returns {number|null} Byte offset (0-based) or null
 */
function positionToByteOffset(line, column) {
    const content = Editor.getEditorContent();
    if (!content) return null;
    
    let currentLine = 1;
    let currentColumn = 1;
    let offset = 0;
    
    for (let i = 0; i < content.length; i++) {
        if (currentLine === line && currentColumn === column) {
            return offset;
        }
        
        if (content[i] === '\n') {
            currentLine++;
            currentColumn = 1;
        } else {
            currentColumn++;
        }
        offset++;
    }
    
    // If position is at end of content
    if (currentLine === line && currentColumn === column) {
        return offset;
    }
    
    return null;
}

/**
 * Find the most specific (deepest) CST node containing the byte offset
 * @param {object} node - CST node to search
 * @param {number} byteOffset - Byte offset to find
 * @returns {object|null} The most specific node or null
 */
function findMostSpecificCstNode(node, byteOffset) {
    if (!node || !node.range) return null;
    
    const [start, end] = node.range;
    
    // Check if offset is within this node's range
    if (byteOffset < start || byteOffset >= end) {
        return null;
    }
    
    // If this node has children, search them for a more specific match
    if (node.children && node.children.length > 0) {
        let bestMatch = null;
        let bestMatchDepth = 0;
        let bestMatchSize = end - start;
        
        for (const child of node.children) {
            const specificChild = findMostSpecificCstNode(child, byteOffset);
            if (specificChild) {
                const childSize = specificChild.range[1] - specificChild.range[0];
                const childDepth = getNodeDepth(specificChild);
                
                // Prefer smaller ranges (more specific) or deeper nodes when size is equal
                if (!bestMatch || childSize < bestMatchSize || 
                    (childSize === bestMatchSize && childDepth > bestMatchDepth)) {
                    bestMatch = specificChild;
                    bestMatchSize = childSize;
                    bestMatchDepth = childDepth;
                }
            }
        }
        
        // If we found a child match, return it
        if (bestMatch) {
            return bestMatch;
        }
    }
    
    // This node contains the offset and no child contains it more specifically
    return node;
}

/**
 * Get the depth of a CST node (how many levels of children it has)
 * @param {object} node - CST node
 * @returns {number} Depth of the node
 */
function getNodeDepth(node) {
    if (!node.children || node.children.length === 0) {
        return 0;
    }
    return 1 + Math.max(...node.children.map(child => getNodeDepth(child)));
}

/**
 * Highlight a CST node in the tree
 * @param {object} node - CST node to highlight
 */
function highlightCstNode(node) {
    if (!node) return;
    
    // Remove previous highlights
    document.querySelectorAll('.cst-node.highlighted').forEach(el => {
        el.classList.remove('highlighted');
    });
    
    // Find and highlight the matching node in the DOM by unique ID
    const nodeId = node._nodeId;
    if (nodeId === undefined) return;
    
    const cstNodes = document.querySelectorAll('.cst-node');
    
    for (const cstNode of cstNodes) {
        const domNodeId = parseInt(cstNode.dataset.nodeId);
        
        if (domNodeId === nodeId) {
            cstNode.classList.add('highlighted');
            
            // Expand parent nodes if collapsed
            let parent = cstNode.parentElement;
            while (parent) {
                if (parent.classList.contains('cst-node') && parent.classList.contains('collapsed')) {
                    parent.classList.remove('collapsed');
                }
                parent = parent.parentElement;
            }
            
            // Scroll into view
            cstNode.scrollIntoView({ behavior: 'smooth', block: 'center' });
            break;
        }
    }
}

/**
 * Handle theme toggle
 */
function handleThemeToggle() {
    // Theme switcher is handled by theme-switcher.js from main site
    // Just update editor theme
    Editor.updateEditorTheme();
}

/**
 * Set up split panel resizer
 */
function setupResizer() {
    const resizer = document.getElementById('resizer');
    const leftPanel = document.querySelector('.editor-panel');
    const rightPanel = document.querySelector('.output-panel');

    if (!resizer || !leftPanel || !rightPanel) return;

    let isResizing = false;
    let startX = 0;
    let startLeftWidth = 0;

    resizer.addEventListener('mousedown', (e) => {
        isResizing = true;
        startX = e.clientX;
        startLeftWidth = leftPanel.offsetWidth;
        document.body.style.cursor = 'col-resize';
        e.preventDefault();
    });

    document.addEventListener('mousemove', (e) => {
        if (!isResizing) return;

        const deltaX = e.clientX - startX;
        const newLeftWidth = startLeftWidth + deltaX;
        const minWidth = 300;
        const maxWidth = window.innerWidth - 300 - 8; // 8px for resizer

        if (newLeftWidth >= minWidth && newLeftWidth <= maxWidth) {
            leftPanel.style.width = `${newLeftWidth}px`;
            leftPanel.style.flex = 'none';
        }
    });

    document.addEventListener('mouseup', () => {
        if (isResizing) {
            isResizing = false;
            document.body.style.cursor = '';
        }
    });
}

/**
 * Handle window resize
 */
function handleWindowResize() {
    // Tree viz will handle its own resize due to automaticLayout
    // Just log for now
    console.log('↔️ Window resized');
}

/**
 * Show loading overlay
 */
function showLoading(message = 'Loading...') {
    const overlay = document.getElementById('loading-overlay');
    if (overlay) {
        overlay.querySelector('p').textContent = message;
        overlay.classList.remove('hidden');
    }
}

/**
 * Hide loading overlay
 */
function hideLoading() {
    const overlay = document.getElementById('loading-overlay');
    if (overlay) {
        overlay.classList.add('hidden');
    }
}

/**
 * Show error modal
 */
function showError(message) {
    const modal = document.getElementById('error-modal');
    const messageEl = document.getElementById('error-message');
    
    if (modal && messageEl) {
        messageEl.textContent = message;
        modal.classList.remove('hidden');
    }

    console.error('❌ Error:', message);
}

/**
 * Hide error modal
 */
function hideError() {
    const modal = document.getElementById('error-modal');
    if (modal) {
        modal.classList.add('hidden');
    }
}

// Error modal close button
document.querySelector('.modal-close')?.addEventListener('click', hideError);
document.getElementById('error-modal')?.addEventListener('click', (e) => {
    if (e.target.id === 'error-modal') {
        hideError();
    }
});

/**
 * Save state to localStorage
 */
function saveToLocalStorage() {
    try {
        const code = Editor.getEditorContent();
        localStorage.setItem('vb6parse-playground-code', code);
        localStorage.setItem('vb6parse-playground-filetype', state.currentFileType);
        localStorage.setItem('vb6parse-playground-autoparse', state.autoParse);
    } catch (error) {
        console.warn('Failed to save to localStorage:', error);
    }
}

/**
 * Load state from localStorage
 */
function loadFromLocalStorage() {
    try {
        const code = localStorage.getItem('vb6parse-playground-code');
        const fileType = localStorage.getItem('vb6parse-playground-filetype');
        const autoParse = localStorage.getItem('vb6parse-playground-autoparse');

        if (code) {
            Editor.setEditorContent(code);
        }

        if (fileType) {
            state.currentFileType = fileType;
            document.getElementById('file-type').value = fileType;
        }

        if (autoParse !== null) {
            state.autoParse = autoParse === 'true';
            document.getElementById('auto-parse').checked = state.autoParse;
        }

        console.log('📂 Loaded state from localStorage');
    } catch (error) {
        console.warn('Failed to load from localStorage:', error);
    }
}

/**
 * Load code from URL parameter
 * TODO: Implement URL parameter loading
 */
function loadFromUrl() {
    const params = new URLSearchParams(window.location.search);
    const encodedCode = params.get('code');
    const fileType = params.get('type');

    if (encodedCode) {
        try {
            const code = decodeURIComponent(atob(encodedCode));
            Editor.setEditorContent(code);
            console.log('🔗 Loaded code from URL');
        } catch (error) {
            console.error('Failed to decode URL code:', error);
        }
    }

    if (fileType) {
        state.currentFileType = fileType;
        document.getElementById('file-type').value = fileType;
    }
}

// Initialize when DOM is ready
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
} else {
    init();
}

/**
 * TODO: Future Enhancements
 * 
 * 1. URL Sharing:
 *    - Encode code in URL with LZ-string compression
 *    - Generate shareable links
 *    - QR code generation
 * 
 * 2. Keyboard Shortcuts:
 *    - Ctrl+Enter: Parse
 *    - Ctrl+K: Clear
 *    - Ctrl+S: Save (download)
 *    - Ctrl+O: Load file
 * 
 * 3. File Operations:
 *    - Load .vb6 files from disk
 *    - Save editor content to file
 *    - Drag & drop file support
 * 
 * 4. Session Management:
 *    - Multiple tabs/files
 *    - History of parsed code
 *    - Favorites/bookmarks
 * 
 * 5. Collaboration:
 *    - Share sessions with others
 *    - Real-time collaboration
 *    - Comments and annotations
 * 
 * 6. Analytics:
 *    - Track usage statistics
 *    - Popular examples
 *    - Performance metrics
 */

export default {
    init,
    state
};