-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
654 lines (605 loc) · 26.8 KB
/
App.tsx
File metadata and controls
654 lines (605 loc) · 26.8 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
import { useState, useEffect, useCallback, useMemo } from 'react';
import { Header } from './components/Header';
import { Controls } from './components/Controls';
import { PatternDisplay } from './components/PatternDisplay';
import { MediaOverlay } from './components/MediaOverlay';
import { Studio3D } from './components/Studio3D';
import { CheatsheetModal } from './components/CheatsheetModal';
import { ChannelMeters } from './components/ChannelMeters';
import { MetadataPanel } from './components/MetadataPanel';
import type { ModuleMetadata } from './components/MetadataPanel';
import { Playlist } from './components/Playlist';
import { SeekBar } from './components/SeekBar';
import { useLibOpenMPT } from './hooks/useLibOpenMPT';
import { usePlaylist } from './hooks/usePlaylist';
import { useKeyboardShortcuts } from './hooks/useKeyboardShortcuts';
import { useLocalStorage } from './hooks/useLocalStorage';
import type { MediaItem } from './types';
import {
DEFAULT_BLOOM_PRESET,
DEFAULT_COLOR_SCHEME,
type BloomPreset,
type ColorScheme
} from './types/bloomPresets';
// Shader Definitions
const SHADER_GROUPS = {
SQUARE: [
{ id: 'patternv0.44.wgsl', label: 'v0.44 (Frosted Wall 64)' },
{ id: 'patternv0.43.wgsl', label: 'v0.43 (Frosted Wall 32)' },
{ id: 'patternv0.40.wgsl', label: 'v0.40 (Frosted Grid)' },
{ id: 'patternv0.39.wgsl', label: 'v0.39 (Modern)' },
{ id: 'patternv0.21.wgsl', label: 'v0.21 (Wall)' },
],
CIRCULAR: [
{ id: 'patternv0.50.wgsl', label: 'v0.50 (Trap Frosted Lens)' },
{ id: 'patternv0.49.wgsl', label: 'v0.49 (Trap Frosted Glass)' },
{ id: 'patternv0.48.wgsl', label: 'v0.48 (Trap Frosted Disc)' },
{ id: 'patternv0.47.wgsl', label: 'v0.47 (Trap Frosted)' },
{ id: 'patternv0.46.wgsl', label: 'v0.46 (Frosted Glass)' },
{ id: 'patternv0.45.wgsl', label: 'v0.45 (Frosted Bloom)' },
{ id: 'patternv0.45b.wgsl', label: 'v0.45b (Note-On Sustain)' },
{ id: 'patternv0.42.wgsl', label: 'v0.42 (Frosted Disc)' },
{ id: 'patternv0.38.wgsl', label: 'v0.38 (Glass)' },
{ id: 'patternv0.35_bloom.wgsl', label: 'v0.35 (Bloom)' },
{ id: 'patternv0.30.wgsl', label: 'v0.30 (Disc)' },
],
VIDEO: [
{ id: 'patternv0.23.wgsl', label: 'v0.23 (Clouds)' },
{ id: 'patternv0.24.wgsl', label: 'v0.24 (Tunnel)' },
]
};
function App() {
const [shaderFile, setShaderFile] = useState<string>('patternv0.50.wgsl');
const [volume, setVolume] = useState<number>(0.5);
const [pan, setPan] = useState<number>(0.0);
// 3D View State
const [is3DMode, setIs3DMode] = useState<boolean>(false);
const [isDarkMode, setIsDarkMode] = useState<boolean>(false);
const [viewMode, setViewMode] = useState<'device' | 'wall'>('device');
// Bloom and Color Scheme State
const [bloomPreset, setBloomPreset] = useState<BloomPreset>(DEFAULT_BLOOM_PRESET);
const [colorScheme, setColorScheme] = useState<ColorScheme>(DEFAULT_COLOR_SCHEME);
const {
isReady,
isModuleLoaded,
isPlaying,
isLooping,
playbackSeconds,
playbackRowFraction,
totalPatternRows,
sequencerMatrix,
channelStates,
beatPhase,
grooveAmount,
kickTrigger,
activeChannels,
play,
stopMusic,
loadFile,
setIsLooping,
seekToStep,
setPanValue: setLibPan,
activeEngine,
isWorkletSupported,
toggleAudioEngine,
status,
syncDebug,
analyserNode,
playbackStateRef,
workletLoadError,
} = useLibOpenMPT(volume);
// Media Overlay State
const [mediaVisible, setMediaVisible] = useState<boolean>(false);
const [mediaItem, setMediaItem] = useState<MediaItem | null>(null);
// Panel visibility
const [showChannelMeters, setShowChannelMeters] = useState<boolean>(true);
const [showMetadata, setShowMetadata] = useState<boolean>(true);
const [showPlaylist, setShowPlaylist] = useState<boolean>(true);
const [debugPanelOpen, setDebugPanelOpen] = useLocalStorage<boolean>('xasm1.debugPanel.open', false);
const [cheatsheetOpen, setCheatsheetOpen] = useState<boolean>(false);
// Channel VU data (from worklet channelStates)
const channelVU = useMemo(() => {
if (!channelStates || channelStates.length === 0) return null;
const vu = new Float32Array(channelStates.length);
for (let i = 0; i < channelStates.length; i++) {
vu[i] = channelStates[i]?.volume ?? 0;
}
return vu;
}, [channelStates]);
// Module metadata derived from existing state
const moduleMetadata = useMemo((): ModuleMetadata | null => {
if (!isModuleLoaded || !sequencerMatrix) return null;
return {
title: status.replace(/^Loaded "/, '').replace(/"$/, '') || 'Unknown',
artist: '',
tracker: activeEngine === 'native-worklet' ? 'Native C++/Wasm' : activeEngine === 'worklet' ? 'JS AudioWorklet' : 'ScriptProcessor',
numChannels: sequencerMatrix?.numChannels ?? 0,
numOrders: totalPatternRows > 0 ? Math.ceil(totalPatternRows / (sequencerMatrix?.numRows || 64)) : 0,
numPatterns: 0,
numInstruments: 0,
durationSeconds: 0,
currentBpm: 125,
instruments: [],
};
}, [isModuleLoaded, sequencerMatrix, status, activeEngine, totalPatternRows]);
// Playlist
const playlist = usePlaylist();
const handlePlaylistSelect = useCallback((index: number) => {
const item = playlist.select(index);
if (item) loadFile(item.fileData, item.fileName);
}, [playlist, loadFile]);
const handlePlaylistNext = useCallback(() => {
const item = playlist.next();
if (item) loadFile(item.fileData, item.fileName);
}, [playlist, loadFile]);
const handlePlaylistPrev = useCallback(() => {
const item = playlist.prev();
if (item) loadFile(item.fileData, item.fileName);
}, [playlist, loadFile]);
const handlePlaylistFilesAdded = useCallback((files: FileList) => {
playlist.addFiles(files);
}, [playlist]);
// Sync pan with library
useEffect(() => { setLibPan(pan); }, [pan, setLibPan]);
const seekByOrderDelta = useCallback((delta: number) => {
const rowsPerPattern = sequencerMatrix?.numRows ?? 64;
const currentOrder = sequencerMatrix?.order ?? 0;
const targetStep = (currentOrder + delta) * rowsPerPattern;
seekToStep(Math.max(0, targetStep));
}, [seekToStep, sequencerMatrix]);
const jumpToOrder = useCallback((orderIndex: number) => {
const rowsPerPattern = sequencerMatrix?.numRows ?? 64;
const targetStep = orderIndex * rowsPerPattern;
seekToStep(Math.max(0, targetStep));
}, [seekToStep, sequencerMatrix?.numRows]);
// Keyboard shortcuts
useKeyboardShortcuts({
onPlayPause: () => { isPlaying ? stopMusic(false) : play(); },
// Issue #135 binding table: ArrowLeft/Right seek one row
onSeekForward: () => seekToStep(Math.floor(playbackRowFraction) + 1),
onSeekBackward: () => seekToStep(Math.max(0, Math.floor(playbackRowFraction) - 1)),
onSeekNextOrder: () => seekByOrderDelta(1),
onSeekPrevOrder: () => seekByOrderDelta(-1),
onPreviousOrder: () => seekByOrderDelta(-1),
onNextOrder: () => seekByOrderDelta(1),
onJumpToOrder: jumpToOrder,
onVolumeUp: () => setVolume(v => Math.min(1, v + 0.05)),
onVolumeDown: () => setVolume(v => Math.max(0, v - 0.05)),
onToggleLoop: () => setIsLooping(!isLooping),
onToggleFullscreen: () => {
if (document.fullscreenElement) document.exitFullscreen();
else document.documentElement.requestFullscreen();
},
onToggleDebugPanel: () => setDebugPanelOpen(!debugPanelOpen),
onToggleCheatsheet: () => setCheatsheetOpen((open) => !open),
onCloseCheatsheet: () => setCheatsheetOpen(false),
cheatsheetOpen,
});
// Register PWA service worker
useEffect(() => {
if (!('serviceWorker' in navigator)) {
console.log('[PWA] Service Worker not supported in this browser');
return;
}
// Only register in production builds
if (!import.meta.env.PROD) {
console.log('[PWA] Skipping SW registration (development mode)');
return;
}
// Detect actual base path from current location for subdirectory deployments
const pathSegments = window.location.pathname.split('/').filter(Boolean);
const detectedBase = pathSegments.length > 0 ? `/${pathSegments[0]}/` : '/';
const baseUrl = import.meta.env.BASE_URL !== '/' ? import.meta.env.BASE_URL : detectedBase;
// Ensure consistent trailing slash for URL construction
const normalizedBase = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;
const swUrl = `${normalizedBase}sw.js`;
const scope = normalizedBase;
console.log('[PWA] ==================================================');
console.log('[PWA] Registering Service Worker...');
console.log('[PWA] Service Worker URL:', swUrl);
console.log('[PWA] Scope:', scope);
console.log('[PWA] BASE_URL (env):', import.meta.env.BASE_URL);
console.log('[PWA] Detected base:', detectedBase);
console.log('[PWA] ==================================================');
navigator.serviceWorker.register(swUrl, { scope }).then((reg) => {
console.log('[PWA] ✅ Service Worker registered successfully');
console.log('[PWA] Scope:', reg.scope);
console.log('[PWA] State:', reg.installing ? 'installing' : reg.waiting ? 'waiting' : 'active');
}).catch((err) => {
console.error('[PWA] ❌ Service Worker registration failed:', err);
console.error('[PWA] Failed URL:', swUrl);
console.error('[PWA] This usually means sw.js is missing from the build output');
});
}, []);
// Handle File Selection
const handleFileSelected = async (file: File) => {
const arrayBuffer = await file.arrayBuffer();
const data = new Uint8Array(arrayBuffer);
loadFile(data, file.name);
};
const handleMediaAdd = (file: File) => {
const kind = file.type.startsWith("video") ? "video" : "image";
const url = URL.createObjectURL(file);
setMediaItem({
id: crypto.randomUUID(),
kind,
url,
fileName: file.name,
mimeType: file.type,
loop: kind === 'video'
});
setMediaVisible(true);
};
const handleRemoteMediaSelect = (item: MediaItem) => {
setMediaItem(item);
setMediaVisible(true);
};
// Calculate Dim Factor
const dimFactor = isDarkMode ? 0.3 : 1.0;
// Determine shader based on view mode when in 3D
const get3DShader = () => {
if (viewMode === 'wall') return 'patternv0.21.wgsl';
return 'patternv0.38.wgsl';
};
// Render in 3D mode
if (is3DMode) {
const shader3D = get3DShader();
return (
<>
<Studio3D
darkMode={isDarkMode}
viewMode={viewMode}
onDarkModeToggle={() => setIsDarkMode(!isDarkMode)}
onViewModeToggle={() => setViewMode(viewMode === 'device' ? 'wall' : 'device')}
onExitStudio={() => setIs3DMode(false)}
dimFactor={dimFactor}
headerContent={
<div className="scale-75 origin-top-left">
<Header status={status} isModuleLoaded={isModuleLoaded} />
<div className={`mb-2 inline-flex flex-col rounded border px-2 py-1 text-[10px] font-mono ${isDarkMode ? 'border-gray-700 bg-black/50 text-gray-300' : 'border-gray-300 bg-white/80 text-gray-700'}`}>
<span>sync mode: {syncDebug.mode}</span>
<span>buffer: {syncDebug.bufferMs.toFixed(1)}ms</span>
<span>drift: {syncDebug.driftMs.toFixed(1)}ms</span>
<span>row: {syncDebug.row.toFixed(2)}</span>
<span>starvations: {syncDebug.starvationCount}</span>
</div>
</div>
}
patternDisplayContent={
<div className="scale-75 origin-center">
<PatternDisplay
key={shader3D}
matrix={sequencerMatrix}
playheadRow={playbackRowFraction}
isPlaying={isPlaying}
bpm={120}
timeSec={playbackSeconds}
tickOffset={playbackRowFraction % 1}
channels={channelStates}
beatPhase={beatPhase}
grooveAmount={grooveAmount}
kickTrigger={kickTrigger}
activeChannels={activeChannels}
isModuleLoaded={isModuleLoaded}
shaderFile={shader3D}
volume={volume}
pan={pan}
isLooping={isLooping}
totalRows={totalPatternRows}
onPlay={play}
onStop={() => stopMusic(false)}
onFileSelected={handleFileSelected}
onLoopToggle={() => setIsLooping(!isLooping)}
onSeek={(row) => seekToStep(row)}
onVolumeChange={setVolume}
onPanChange={setPan}
externalVideoSource={null}
dimFactor={dimFactor}
analyserNode={analyserNode}
debugPanelOpen={debugPanelOpen}
onCloseDebug={() => setDebugPanelOpen(false)}
onOpenDebug={() => setDebugPanelOpen(true)}
// PERFORMANCE OPTIMIZATION: Pass ref for high-frequency updates
playbackStateRef={playbackStateRef}
// Bloom settings from preset
bloomIntensity={bloomPreset.intensity}
bloomThreshold={bloomPreset.threshold}
/>
</div>
}
controlsContent={
<div className="scale-75 origin-top-left">
<Controls
isReady={isReady}
isPlaying={isPlaying}
isModuleLoaded={isModuleLoaded}
onFileSelected={handleFileSelected}
onPlay={play}
onStop={() => stopMusic(false)}
isLooping={isLooping}
onLoopToggle={() => setIsLooping(!isLooping)}
volume={volume}
setVolume={setVolume}
pan={pan}
setPan={setPan}
onMediaAdd={handleMediaAdd}
onRemoteMediaSelect={handleRemoteMediaSelect}
remoteMediaList={[
{ id: '1', kind: 'video', url: 'clouds.mp4', fileName: 'Clouds Demo (MP4)', mimeType: 'video/mp4' }
]}
bloomPreset={bloomPreset}
onBloomPresetChange={setBloomPreset}
colorScheme={colorScheme}
onColorSchemeChange={setColorScheme}
/>
</div>
}
mediaOverlayContent={
mediaVisible && mediaItem ? (
<div className="scale-75 origin-center">
<MediaOverlay
item={mediaItem}
visible={mediaVisible}
onClose={() => setMediaVisible(false)}
onUpdate={(partial) => {
if (mediaItem) setMediaItem({ ...mediaItem, ...partial });
}}
/>
</div>
) : undefined
}
playheadX={playbackSeconds * 10.0}
/>
{cheatsheetOpen && <CheatsheetModal onClose={() => setCheatsheetOpen(false)} />}
</>
);
}
// 2D Mode Render
return (
<div className={`min-h-screen ${isDarkMode ? 'bg-gray-900 text-white' : 'bg-gray-100 text-black'} p-4 flex flex-col items-center transition-colors duration-300`}>
<div className="w-full max-w-[1280px]">
<Header status={status} isModuleLoaded={isModuleLoaded} />
{/* Global Controls */}
<div className="mb-4 flex flex-wrap items-center justify-between gap-4">
<div className="flex gap-2">
<button
onClick={() => setIs3DMode(true)}
className="px-4 py-2 bg-blue-600 text-white text-sm font-mono rounded-lg shadow-lg hover:bg-blue-700 transition-colors border border-blue-500"
>
🎬 3D Mode
</button>
<button
onClick={() => setIsDarkMode(!isDarkMode)}
className={`px-4 py-2 text-sm font-mono rounded-lg shadow-lg transition-colors border ${isDarkMode ? 'bg-gray-800 text-white border-gray-700 hover:bg-gray-700' : 'bg-white text-black border-gray-300 hover:bg-gray-50'}`}
>
{isDarkMode ? '☀️ Light' : '🌙 Dark'}
</button>
<button
onClick={toggleAudioEngine}
disabled={!isWorkletSupported || !!workletLoadError}
title={workletLoadError ? `Worklet Error: ${workletLoadError}` : !isWorkletSupported ? "AudioWorklet not supported" : "Toggle Audio Engine (Worklet vs ScriptProcessor)"}
className={`px-4 py-2 text-sm font-mono rounded-lg shadow-lg transition-colors border ${
!isWorkletSupported || !!workletLoadError
? 'bg-gray-300 text-gray-500 cursor-not-allowed border-gray-400 opacity-50'
: activeEngine === 'native-worklet'
? 'bg-purple-600 text-white border-purple-500 hover:bg-purple-700'
: activeEngine === 'worklet'
? 'bg-green-600 text-white border-green-500 hover:bg-green-700'
: 'bg-yellow-500 text-black border-yellow-400 hover:bg-yellow-600'
}`}
>
{activeEngine === 'native-worklet' ? '🚀 Native' : activeEngine === 'worklet' ? '⚡ Worklet' : '🐌 Script'}
</button>
</div>
{/* Categorized Shader Selectors */}
<div className={`flex flex-wrap gap-2 p-2 rounded-xl border ${isDarkMode ? 'bg-black border-gray-800' : 'bg-gray-200 border-gray-300'}`}>
{/* Square Group */}
<div className="flex items-center gap-1">
<span className="text-[10px] font-bold text-gray-500 uppercase px-1">Square</span>
<select
className={`text-xs font-mono p-1 rounded border outline-none ${isDarkMode ? 'bg-gray-800 border-gray-600 text-white' : 'bg-white border-gray-300 text-black'}`}
value={SHADER_GROUPS.SQUARE.some(s => s.id === shaderFile) ? shaderFile : ''}
onChange={(e) => e.target.value && setShaderFile(e.target.value)}
>
<option value="" disabled>Select...</option>
{SHADER_GROUPS.SQUARE.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
</select>
</div>
<div className={`w-px h-6 ${isDarkMode ? 'bg-gray-800' : 'bg-gray-300'}`}></div>
{/* Circular Group */}
<div className="flex items-center gap-1">
<span className="text-[10px] font-bold text-gray-500 uppercase px-1">Circular</span>
<select
className={`text-xs font-mono p-1 rounded border outline-none ${isDarkMode ? 'bg-gray-800 border-gray-600 text-white' : 'bg-white border-gray-300 text-black'}`}
value={SHADER_GROUPS.CIRCULAR.some(s => s.id === shaderFile) ? shaderFile : ''}
onChange={(e) => e.target.value && setShaderFile(e.target.value)}
>
<option value="" disabled>Select...</option>
{SHADER_GROUPS.CIRCULAR.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
</select>
</div>
<div className={`w-px h-6 ${isDarkMode ? 'bg-gray-800' : 'bg-gray-300'}`}></div>
{/* Video Group */}
<div className="flex items-center gap-1">
<span className="text-[10px] font-bold text-gray-500 uppercase px-1">Video</span>
<select
className={`text-xs font-mono p-1 rounded border outline-none ${isDarkMode ? 'bg-gray-800 border-gray-600 text-white' : 'bg-white border-gray-300 text-black'}`}
value={SHADER_GROUPS.VIDEO.some(s => s.id === shaderFile) ? shaderFile : ''}
onChange={(e) => e.target.value && setShaderFile(e.target.value)}
>
<option value="" disabled>Select...</option>
{SHADER_GROUPS.VIDEO.map(s => <option key={s.id} value={s.id}>{s.label}</option>)}
</select>
</div>
</div>
</div>
{/* Main Display Area */}
<div className={`relative rounded-xl overflow-hidden shadow-2xl mb-6 border ${isDarkMode ? 'bg-black border-gray-800' : 'bg-white border-gray-300'}`}>
<PatternDisplay
key={shaderFile}
matrix={sequencerMatrix}
playheadRow={playbackRowFraction}
isPlaying={isPlaying}
bpm={120}
timeSec={playbackSeconds}
tickOffset={playbackRowFraction % 1}
channels={channelStates}
beatPhase={beatPhase}
grooveAmount={grooveAmount}
kickTrigger={kickTrigger}
activeChannels={activeChannels}
isModuleLoaded={isModuleLoaded}
shaderFile={shaderFile}
volume={volume}
pan={pan}
isLooping={isLooping}
totalRows={totalPatternRows}
onPlay={play}
onStop={() => stopMusic(false)}
onFileSelected={handleFileSelected}
onLoopToggle={() => setIsLooping(!isLooping)}
onSeek={(row) => seekToStep(row)}
onVolumeChange={setVolume}
onPanChange={setPan}
externalVideoSource={null}
dimFactor={dimFactor}
analyserNode={analyserNode}
debugPanelOpen={debugPanelOpen}
onCloseDebug={() => setDebugPanelOpen(false)}
onOpenDebug={() => setDebugPanelOpen(true)}
// PERFORMANCE OPTIMIZATION: Pass ref for high-frequency updates
playbackStateRef={playbackStateRef}
// Bloom settings from preset
bloomIntensity={bloomPreset.intensity}
bloomThreshold={bloomPreset.threshold}
/>
<MediaOverlay
item={mediaItem}
visible={mediaVisible}
onClose={() => setMediaVisible(false)}
onUpdate={(partial) => {
if (mediaItem) setMediaItem({ ...mediaItem, ...partial });
}}
/>
</div>
{/* Controls */}
<Controls
isReady={isReady}
isPlaying={isPlaying}
isModuleLoaded={isModuleLoaded}
onFileSelected={handleFileSelected}
onPlay={play}
onStop={() => stopMusic(false)}
isLooping={isLooping}
onLoopToggle={() => setIsLooping(!isLooping)}
volume={volume}
setVolume={setVolume}
pan={pan}
setPan={setPan}
onMediaAdd={handleMediaAdd}
onRemoteMediaSelect={handleRemoteMediaSelect}
remoteMediaList={[
{ id: '1', kind: 'video', url: 'clouds.mp4', fileName: 'Clouds Demo (MP4)', mimeType: 'video/mp4' }
]}
bloomPreset={bloomPreset}
onBloomPresetChange={setBloomPreset}
colorScheme={colorScheme}
onColorSchemeChange={setColorScheme}
/>
{/* Seek Bar */}
{isModuleLoaded && (
<div className="mt-4">
<SeekBar
currentSeconds={playbackSeconds}
durationSeconds={0}
currentRow={Math.floor(playbackRowFraction)}
totalRows={totalPatternRows}
isPlaying={isPlaying}
onSeekRow={seekToStep}
/>
</div>
)}
{/* Panel Toggle Buttons */}
<div className="mt-4 flex flex-wrap gap-2">
{[
{ key: 'meters', label: '📊 VU Meters', state: showChannelMeters, toggle: setShowChannelMeters },
{ key: 'meta', label: 'ℹ️ Metadata', state: showMetadata, toggle: setShowMetadata },
{ key: 'playlist', label: '📋 Playlist', state: showPlaylist, toggle: setShowPlaylist },
].map(({ key, label, state, toggle }) => (
<button
key={key}
onClick={() => toggle(!state)}
className={`px-3 py-1 text-xs font-mono rounded-lg border transition-colors ${
state
? 'bg-cyan-900/30 text-cyan-300 border-cyan-800'
: isDarkMode
? 'bg-gray-800 text-gray-500 border-gray-700 hover:text-gray-300'
: 'bg-gray-200 text-gray-500 border-gray-300 hover:text-gray-700'
}`}
>
{label}
</button>
))}
</div>
{/* Virtual Hardware Panels */}
<div className="mt-4 grid grid-cols-1 lg:grid-cols-3 gap-4">
{/* Left Column: Visualizer placeholder (optional) */}
<div className="lg:col-span-2">
{/* Hardware display area - PatternDisplay is already shown above */}
<div className="h-full min-h-[200px] flex items-center justify-center text-gray-500 text-sm">
{/* Virtual hardware display active */}
</div>
</div>
{/* Right Column: Metadata + VU Meters */}
<div className="flex flex-col gap-4">
{showMetadata && (
<MetadataPanel
metadata={moduleMetadata}
currentOrder={sequencerMatrix?.order ?? 0}
currentRow={Math.floor(playbackRowFraction)}
currentPattern={sequencerMatrix?.patternIndex ?? 0}
matrix={sequencerMatrix}
isPlaying={isPlaying}
playbackSeconds={playbackSeconds}
/>
)}
{showChannelMeters && (
<ChannelMeters
channelVU={channelVU}
numChannels={sequencerMatrix?.numChannels ?? 4}
analyserNode={analyserNode}
isPlaying={isPlaying}
/>
)}
</div>
</div>
{/* Playlist */}
{showPlaylist && (
<div className="mt-4">
<Playlist
items={playlist.items}
currentIndex={playlist.currentIndex}
isPlaying={isPlaying}
shuffle={playlist.shuffle}
repeat={playlist.repeat}
onSelect={handlePlaylistSelect}
onRemove={playlist.remove}
onClear={playlist.clear}
onPrev={handlePlaylistPrev}
onNext={handlePlaylistNext}
onShuffleToggle={playlist.toggleShuffle}
onRepeatCycle={playlist.cycleRepeat}
onFilesAdded={handlePlaylistFilesAdded}
/>
</div>
)}
<div className="mt-8 text-center text-xs opacity-50">
<p>Supports .mod, .xm, .s3m, .it files.</p>
<p>WebGPU required for visualization.</p>
</div>
</div>
{cheatsheetOpen && <CheatsheetModal onClose={() => setCheatsheetOpen(false)} />}
</div>
);
}
export default App;