-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
486 lines (430 loc) · 15.6 KB
/
Copy pathApp.tsx
File metadata and controls
486 lines (430 loc) · 15.6 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
import React, { useState, useEffect, useCallback, useRef } from 'react'
import { CellType, Direction, GridCell, BeamSegment } from './types'
import { GRID_COLS, GRID_ROWS, DEFAULT_BPM } from './constants'
import Grid from './components/Grid'
import GridCanvas from './components/GridCanvas'
import ControlPanel from './components/ControlPanel'
import PresetModal from './components/PresetModal'
import { runSimulation } from './services/simulation'
import { audioService } from './services/audioService'
import { generatePattern } from './services/geminiService'
import { shareService } from './services/shareService'
const INITIAL_GRID: GridCell[][] = Array(GRID_ROWS)
.fill(null)
.map(() =>
Array(GRID_COLS)
.fill(null)
.map(() => ({
type: CellType.EMPTY,
direction: Direction.RIGHT,
active: false,
}))
)
// Preset for demo
const DEMO_GRID = JSON.parse(JSON.stringify(INITIAL_GRID))
DEMO_GRID[7][2] = {
type: CellType.EMITTER,
direction: Direction.RIGHT,
active: false,
}
DEMO_GRID[7][10] = {
type: CellType.SPLITTER,
direction: Direction.RIGHT,
active: false,
}
DEMO_GRID[4][10] = {
type: CellType.MIRROR_SLASH,
direction: Direction.RIGHT,
active: false,
}
DEMO_GRID[10][10] = {
type: CellType.MIRROR_BACKSLASH,
direction: Direction.RIGHT,
active: false,
}
DEMO_GRID[4][15] = {
type: CellType.SENSOR,
direction: Direction.RIGHT,
active: false,
}
DEMO_GRID[10][15] = {
type: CellType.SENSOR,
direction: Direction.RIGHT,
active: false,
}
DEMO_GRID[7][18] = {
type: CellType.SENSOR,
direction: Direction.RIGHT,
active: false,
}
const HISTORY_LIMIT = 50
const App: React.FC = () => {
const [grid, setGrid] = useState<GridCell[][]>(DEMO_GRID)
const [selectedTool, setSelectedTool] = useState<CellType>(CellType.EMITTER)
const [isPlaying, setIsPlaying] = useState(false)
const [bpm, setBpm] = useState(DEFAULT_BPM)
const [beams, setBeams] = useState<BeamSegment[]>([])
// Modal States
const [isGenerating, setIsGenerating] = useState(false)
const [genPrompt, setGenPrompt] = useState('')
const [showPromptModal, setShowPromptModal] = useState(false)
const [showPresetModal, setShowPresetModal] = useState(false)
// Toast State
const [toast, setToast] = useState<string | null>(null)
// History State
const historyRef = useRef<GridCell[][][]>([DEMO_GRID])
const historyIndexRef = useRef(0)
const [canUndo, setCanUndo] = useState(false)
const [canRedo, setCanRedo] = useState(false)
const gridRef = useRef(grid) // Ref for latest state in interval
// Sync Ref
useEffect(() => {
gridRef.current = grid
}, [grid])
// Helper: Deep Clone
const cloneGrid = (g: GridCell[][]) =>
g.map((row) => row.map((cell) => ({ ...cell })))
// Helper: Add to History
const recordHistory = useCallback((newGrid: GridCell[][]) => {
const currentHistory = historyRef.current
const currentIndex = historyIndexRef.current
// Remove future history if we are not at end
const newHistory = currentHistory.slice(0, currentIndex + 1)
// Add new state
// Note: We must strip 'active' status for history to avoid visual glitch saving
const cleanGrid = newGrid.map((r) =>
r.map((c) => ({ ...c, active: false }))
)
newHistory.push(cleanGrid)
// Limit size
if (newHistory.length > HISTORY_LIMIT) {
newHistory.shift()
}
historyRef.current = newHistory
historyIndexRef.current = newHistory.length - 1
setCanUndo(historyIndexRef.current > 0)
setCanRedo(false)
}, [])
// Toast Helper
const showToast = useCallback((msg: string) => {
setToast(msg)
setTimeout(() => setToast(null), 3000)
}, [])
// Undo Logic
const handleUndo = useCallback(() => {
if (historyIndexRef.current > 0) {
historyIndexRef.current--
const prevGrid = historyRef.current[historyIndexRef.current]
setGrid(cloneGrid(prevGrid))
setCanUndo(historyIndexRef.current > 0)
setCanRedo(true)
}
}, [])
const handleRedo = useCallback(() => {
if (historyIndexRef.current < historyRef.current.length - 1) {
historyIndexRef.current++
const nextGrid = historyRef.current[historyIndexRef.current]
setGrid(cloneGrid(nextGrid))
setCanUndo(true)
setCanRedo(historyIndexRef.current < historyRef.current.length - 1)
}
}, [])
// Initial Load from URL
useEffect(() => {
const hash = window.location.hash
if (hash && hash.length > 1) {
const decoded = shareService.decode(hash)
if (decoded) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setGrid(decoded.grid)
setBpm(decoded.bpm)
// Reset history for shared link
historyRef.current = [decoded.grid]
historyIndexRef.current = 0
setCanUndo(false)
setCanRedo(false)
showToast('Pattern Loaded from URL')
}
}
}, [showToast])
// Simulation Tick
const tick = useCallback(() => {
// 1. Run Physics
const result = runSimulation(gridRef.current)
// 2. Audio Trigger
result.activeSensors.forEach((sensor) => {
audioService.playNote(sensor.y, sensor.intensity, sensor.channel)
})
// 3. Update Grid State (for visual feedback and rotations)
setBeams(result.beams)
setGrid((prevGrid) => {
// We want to update 'active' and 'direction' (for rotators)
// But we DON'T record this to undo history to keep it clean.
const newGrid = prevGrid.map((row) =>
row.map((cell) => ({ ...cell, active: false }))
)
// Mark active sensors
result.activeSensors.forEach((s) => {
if (newGrid[s.y][s.x].type === CellType.SENSOR) {
newGrid[s.y][s.x].active = true
}
})
// Apply Rotations (Generative aspect)
result.gridUpdates.forEach((update) => {
newGrid[update.y][update.x].direction = update.newDir
})
return newGrid
})
}, [])
// Sequencer Loop
useEffect(() => {
let interval: number
if (isPlaying) {
audioService.resume()
const msPerBeat = (60 / bpm) * 1000
interval = window.setInterval(tick, msPerBeat)
// Run once immediately
tick()
} else {
// Clear beams when stopped
// eslint-disable-next-line react-hooks/set-state-in-effect
setBeams([])
setGrid((g) => g.map((r) => r.map((c) => ({ ...c, active: false }))))
}
return () => clearInterval(interval)
}, [isPlaying, bpm, tick])
// Keyboard Shortcuts
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'z') {
e.preventDefault()
if (e.shiftKey) handleRedo()
else handleUndo()
}
if ((e.metaKey || e.ctrlKey) && e.key === 'y') {
e.preventDefault()
handleRedo()
}
}
window.addEventListener('keydown', handleKeyDown)
return () => window.removeEventListener('keydown', handleKeyDown)
}, [handleUndo, handleRedo])
const handleShare = () => {
const hash = shareService.encode(grid, bpm)
window.location.hash = hash
navigator.clipboard.writeText(window.location.href).then(() => {
showToast('Link Copied to Clipboard!')
})
}
// Interaction Handlers
const handleCellClick = (x: number, y: number) => {
audioService.init()
setGrid((prev) => {
const newGrid = cloneGrid(prev)
const current = newGrid[y][x]
if (selectedTool === CellType.EMPTY) {
newGrid[y][x] = {
type: CellType.EMPTY,
direction: Direction.RIGHT,
active: false,
}
} else {
if (
current.type === selectedTool &&
selectedTool !== CellType.SENSOR &&
selectedTool !== CellType.WALL
) {
newGrid[y][x] = { ...current, direction: (current.direction + 1) % 4 }
} else {
newGrid[y][x] = {
type: selectedTool,
direction: Direction.RIGHT,
active: false,
}
}
}
// Record History
recordHistory(newGrid)
return newGrid
})
}
const handleCellRightClick = (e: React.MouseEvent, x: number, y: number) => {
e.preventDefault()
setGrid((prev) => {
const newGrid = cloneGrid(prev)
const current = newGrid[y][x]
if (
current.type !== CellType.EMPTY &&
current.type !== CellType.SENSOR &&
current.type !== CellType.WALL
) {
newGrid[y][x] = { ...current, direction: (current.direction + 3) % 4 }
} else {
newGrid[y][x] = {
type: CellType.EMPTY,
direction: Direction.RIGHT,
active: false,
}
}
// Record History
recordHistory(newGrid)
return newGrid
})
}
const handleClear = () => {
setGrid(INITIAL_GRID)
setBeams([])
setIsPlaying(false)
recordHistory(INITIAL_GRID)
}
const handleGenerate = async () => {
setShowPromptModal(true)
}
const confirmGenerate = async () => {
setShowPromptModal(false)
setIsGenerating(true)
setIsPlaying(false)
const newGrid = await generatePattern(
genPrompt || 'A complex polyrhythmic pattern'
)
if (newGrid) {
setGrid(newGrid)
recordHistory(newGrid)
showToast('Pattern Generated')
} else {
showToast('Generation Failed')
}
setIsGenerating(false)
}
const handleLoadPreset = (loadedGrid: GridCell[][], loadedBpm: number) => {
setGrid(loadedGrid)
setBpm(loadedBpm)
setIsPlaying(false)
recordHistory(loadedGrid)
showToast('Preset Loaded')
}
return (
<div className="bg-grid-pattern relative flex min-h-screen overflow-hidden bg-gray-950 font-sans text-gray-100 selection:bg-cyan-500/30">
{/* Ambient Vignette & Overlays */}
<div className="pointer-events-none absolute inset-0 z-0 bg-[radial-gradient(circle_at_center,rgba(10,20,30,0)_0%,rgba(3,7,18,0.9)_100%)]"></div>
<div className="pointer-events-none absolute inset-0 z-0 bg-[linear-gradient(rgba(255,255,255,0.05)_1px,transparent_1px)] bg-[size:100%_4px] opacity-5"></div>
<ControlPanel
selectedTool={selectedTool}
setSelectedTool={setSelectedTool}
isPlaying={isPlaying}
togglePlay={() => setIsPlaying(!isPlaying)}
clearGrid={handleClear}
bpm={bpm}
setBpm={setBpm}
onGenerate={handleGenerate}
isGenerating={isGenerating}
onOpenPresets={() => setShowPresetModal(true)}
canUndo={canUndo}
canRedo={canRedo}
onUndo={handleUndo}
onRedo={handleRedo}
onShare={handleShare}
/>
<main className="relative z-10 ml-72 flex flex-1 flex-col items-center justify-center overflow-auto p-8">
{/* Header/Status HUD */}
<div className="pointer-events-none absolute top-6 right-8 z-20 flex flex-col items-end select-none">
<div
className={`mb-1 flex items-center gap-2 font-mono text-[10px] tracking-[0.2em] uppercase ${isPlaying ? 'text-green-400' : 'text-gray-600'}`}
>
<div
className={`h-1.5 w-1.5 rounded-full ${isPlaying ? 'animate-pulse bg-green-400' : 'bg-gray-600'}`}
></div>
{isPlaying ? 'System Active' : 'System Standby'}
</div>
<div className="font-mono text-[9px] tracking-widest text-gray-500 opacity-50">
COORDS: {GRID_COLS}x{GRID_ROWS}
</div>
</div>
{/* Grid Container */}
<div className="relative rounded-2xl p-8 shadow-2xl shadow-black/50 transition-all duration-500">
<div className="relative hidden sm:block">
{/* Glow behind grid */}
<div
className={`absolute inset-0 rounded-full bg-cyan-500/5 blur-3xl transition-opacity duration-1000 ${isPlaying ? 'opacity-100' : 'opacity-0'}`}
></div>
<GridCanvas beams={beams} cellSize={40} />
<Grid
grid={grid}
onCellClick={handleCellClick}
onCellRightClick={handleCellRightClick}
/>
</div>
<div className="rounded border border-red-900/50 bg-red-900/10 p-4 font-mono text-xs text-red-400 sm:hidden">
⚠️ VIEWPORT ERROR: DESKTOP RESOLUTION REQUIRED
</div>
</div>
{/* Key Controls Hint */}
<div className="absolute right-8 bottom-6 font-mono text-[9px] tracking-widest text-gray-600 uppercase opacity-50 select-none">
L-Click: Place/Rot • R-Click: Del/Rot-CCW
</div>
</main>
{/* Toast Notification */}
{toast && (
<div className="animate-in slide-in-from-top-4 fade-in fixed top-8 left-1/2 z-50 ml-36 -translate-x-1/2">
<div className="flex items-center gap-3 rounded-lg border border-cyan-500/30 bg-black/80 px-6 py-3 text-xs font-bold tracking-[0.1em] text-cyan-400 uppercase shadow-[0_0_20px_rgba(6,182,212,0.2)] backdrop-blur-md">
<div className="h-1.5 w-1.5 animate-pulse rounded-full bg-cyan-400"></div>
{toast}
</div>
</div>
)}
{/* Preset Modal */}
<PresetModal
isOpen={showPresetModal}
onClose={() => setShowPresetModal(false)}
currentGrid={grid}
currentBpm={bpm}
onLoad={handleLoadPreset}
/>
{/* Generation Modal */}
{showPromptModal && (
<div className="animate-in fade-in fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4 backdrop-blur-sm duration-200">
<div className="group relative w-full max-w-lg overflow-hidden rounded-xl border border-cyan-500/20 bg-[#050914] shadow-2xl">
<div className="pointer-events-none absolute inset-0 bg-cyan-500/5"></div>
<div className="relative z-10 flex items-center justify-between border-b border-white/5 bg-black/20 p-5">
<div>
<h2 className="flex items-center gap-2 text-sm font-bold tracking-[0.1em] text-white uppercase">
<span className="text-cyan-400">✦</span> Generate Pattern
</h2>
</div>
<button
onClick={() => setShowPromptModal(false)}
className="flex h-6 w-6 items-center justify-center rounded-full text-gray-600 transition-colors hover:bg-white/10 hover:text-white"
>
✕
</button>
</div>
<div className="relative z-10 p-6">
<textarea
className="mb-6 h-32 w-full resize-none rounded-lg border border-gray-700 bg-black/40 p-4 font-mono text-sm text-xs text-cyan-100 placeholder-gray-600 shadow-inner transition-all outline-none focus:border-cyan-500/50 focus:ring-0"
placeholder="> DESCRIBE TOPOLOGY_ > e.g., 'Recursive loop with prismatic refraction'"
value={genPrompt}
onChange={(e) => setGenPrompt(e.target.value)}
autoFocus
/>
<div className="flex justify-end gap-3">
<button
onClick={() => setShowPromptModal(false)}
className="rounded-lg px-4 py-2 text-[10px] font-bold tracking-widest text-gray-500 uppercase transition-colors hover:bg-white/5 hover:text-gray-300"
>
Cancel
</button>
<button
onClick={confirmGenerate}
className="rounded-lg border border-cyan-500/50 bg-cyan-500/10 px-6 py-2 text-[10px] font-bold tracking-[0.15em] text-cyan-400 uppercase shadow-[0_0_15px_rgba(6,182,212,0.15)] transition-all hover:bg-cyan-500/20 hover:shadow-[0_0_25px_rgba(6,182,212,0.3)]"
>
Execute
</button>
</div>
</div>
</div>
</div>
)}
</div>
)
}
export default App