-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
276 lines (244 loc) · 9.68 KB
/
Copy pathApp.tsx
File metadata and controls
276 lines (244 loc) · 9.68 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
import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
AppSettings,
OrnamentConfig
} from './types';
import {
BG_MUSIC_TRACK,
BG_MUSIC_FILENAME,
GITHUB_API_CONTENTS_URL,
GITHUB_USER,
GITHUB_REPO,
GITHUB_BRANCH,
ORNAMENT_POSITIONS,
ORNAMENT_COLORS
} from './constants';
import { audioService } from './services/audioService';
import Ornament from './components/Ornament';
import SettingsMenu from './components/SettingsMenu';
import ChristmasTree from './components/ChristmasTree';
import IntroAnimation from './components/IntroAnimation';
import BackgroundSlider from './components/BackgroundSlider';
const App: React.FC = () => {
const [hasStarted, setHasStarted] = useState(false);
const [isMenuOpen, setIsMenuOpen] = useState(false);
const [settings, setSettings] = useState<AppSettings>({
bgVolume: 0.3,
sfxVolume: 0.8,
isLooping: false,
});
const [ornaments, setOrnaments] = useState<OrnamentConfig[]>([]);
const [introTarget, setIntroTarget] = useState<OrnamentConfig | null>(null);
const [audioLevel, setAudioLevel] = useState(0);
const [bgImage, setBgImage] = useState<string | null>(null);
const [soundPool, setSoundPool] = useState<string[]>([]);
const [isLoadingSounds, setIsLoadingSounds] = useState(true);
const animationRef = useRef<number>(0);
// Fetch sounds from GitHub API with Fallback
useEffect(() => {
const fetchSounds = async () => {
try {
const response = await fetch(GITHUB_API_CONTENTS_URL);
const data = await response.json();
// GitHub API returns an object (with message) on error/rate-limit, array on success
if (!Array.isArray(data)) {
throw new Error("GitHub API response is not an array (likely rate limit)");
}
// Filter for mp3s, exclude directory entries, and exclude the specific background track
const mp3Urls = data
.filter((item: any) =>
item.type === 'file' &&
item.name.toLowerCase().endsWith('.mp3') &&
item.name !== BG_MUSIC_FILENAME
)
.map((item: any) => item.download_url); // GitHub API returns a 'download_url' which is the raw link
if (mp3Urls.length === 0) throw new Error("No MP3s found via API");
console.log(`Found ${mp3Urls.length} sound effects.`);
setSoundPool(mp3Urls);
} catch (error) {
console.warn("Error fetching sounds from GitHub, using fallback filenames:", error);
// Fallback: Construct URLs for 1.mp3 to 8.mp3 assuming they exist
const fallbackUrls = Array.from({length: 8}, (_, i) =>
`https://raw.githubusercontent.com/${GITHUB_USER}/${GITHUB_REPO}/${GITHUB_BRANCH}/${i+1}.mp3`
);
setSoundPool(fallbackUrls);
} finally {
setIsLoadingSounds(false);
}
};
fetchSounds();
}, []);
// Initialize/Shuffle Ornaments
const initOrnaments = useCallback(() => {
// Shuffle the sound pool if we have sounds
const availableSounds = soundPool.length > 0 ? soundPool : [];
const shuffledSounds = [...availableSounds].sort(() => 0.5 - Math.random());
const newOrnaments: OrnamentConfig[] = ORNAMENT_POSITIONS.map((pos, idx) => {
// Cycle through shuffled sounds, or use empty string if none available
const soundUrl = shuffledSounds.length > 0
? shuffledSounds[idx % shuffledSounds.length]
: '';
return {
id: `ornament-${idx}`,
x: pos.x,
y: pos.y,
scale: pos.scale,
color: ORNAMENT_COLORS[idx % ORNAMENT_COLORS.length],
soundUrl: soundUrl
};
});
setOrnaments(newOrnaments);
}, [soundPool]);
// Re-initialize ornaments whenever the sound pool is ready or updated
useEffect(() => {
if (!isLoadingSounds) {
initOrnaments();
}
}, [isLoadingSounds, soundPool, initOrnaments]);
// Audio Loop for Visualization
const updateAudioAnalysis = () => {
if (audioService.analyser) {
const dataArray = new Uint8Array(audioService.analyser.frequencyBinCount);
audioService.getByteFrequencyData(dataArray);
// Calculate average volume
let sum = 0;
for (let i = 0; i < dataArray.length; i++) {
sum += dataArray[i];
}
const avg = sum / dataArray.length;
setAudioLevel(avg);
}
animationRef.current = requestAnimationFrame(updateAudioAnalysis);
};
// Handle Start (User Interaction required for AudioContext)
const handleStart = async () => {
await audioService.playBackground(BG_MUSIC_TRACK, settings.bgVolume);
setHasStarted(true);
updateAudioAnalysis();
// intro animation triggered by useEffect below
};
// Handle Intro Complete (Stable reference)
const handleIntroComplete = useCallback(() => {
setIntroTarget(null);
}, []);
// Trigger Animation Logic
const triggerIntro = useCallback(() => {
if (ornaments.length > 0) {
const randomIdx = Math.floor(Math.random() * ornaments.length);
setIntroTarget(ornaments[randomIdx]);
}
}, [ornaments]);
// Watch for Menu Close or Start to trigger animation
useEffect(() => {
if (hasStarted && !isMenuOpen) {
// Delay slightly to allow menu transition or startup fade
const timer = setTimeout(() => {
triggerIntro();
}, 500);
return () => clearTimeout(timer);
}
}, [isMenuOpen, hasStarted, triggerIntro]);
// Update Volumes
useEffect(() => {
audioService.setBgVolume(settings.bgVolume);
audioService.setSfxVolume(settings.sfxVolume);
}, [settings.bgVolume, settings.sfxVolume]);
// Cleanup
useEffect(() => {
return () => {
cancelAnimationFrame(animationRef.current);
};
}, []);
return (
<div
className="relative w-full h-screen overflow-hidden bg-black transition-all duration-1000"
>
{/* Background Layer: Slider OR Static Generated Image */}
{bgImage ? (
<div
className="absolute inset-0 bg-cover bg-center transition-opacity duration-1000"
style={{ backgroundImage: `url(${bgImage})` }}
/>
) : (
<BackgroundSlider />
)}
{/* Radial Gradient Overlay for depth (always present) */}
<div className="absolute inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,rgba(15,23,42,0.5)_100%)] pointer-events-none"></div>
{/* Snow/Sparkle overlay */}
<div className="absolute inset-0 bg-[url('https://www.transparenttextures.com/patterns/stardust.png')] opacity-30 pointer-events-none mix-blend-screen"></div>
{/* Start Screen Overlay */}
{!hasStarted && (
<div className="absolute inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm">
<button
onClick={handleStart}
disabled={isLoadingSounds}
className="group relative px-8 py-4 bg-red-600 hover:bg-red-500 disabled:bg-gray-600 text-white font-christmas text-3xl rounded-full shadow-[0_0_30px_rgba(220,38,38,0.6)] transition-all hover:scale-105"
>
<span className="relative z-10">
{isLoadingSounds ? "Loading Magic..." : "Open Christmas Card"}
</span>
{!isLoadingSounds && <div className="absolute inset-0 rounded-full border-2 border-white animate-ping opacity-50"></div>}
</button>
</div>
)}
{/* Main Content */}
<div className={`relative w-full h-full flex flex-col justify-end items-center pb-4 transition-opacity duration-1000 ${hasStarted ? 'opacity-100' : 'opacity-0'}`}>
{/* UNIFIED SCENE CONTAINER
This container holds both the Tree and the Ornaments.
It enforces an aspect ratio matching the SVG (100:130 -> ~0.77).
It uses min() to ensuring it fits within both Width and Height constraints.
- 85vw: Fits width on mobile portrait
- 70vh * 0.77: Fits height on landscape (maintaining ratio)
*/}
<div
className="relative mx-auto mb-4 pointer-events-none"
style={{
width: 'min(85vw, 70vh * 0.77)',
aspectRatio: '100 / 130',
// Ensure it never exceeds reasonable height
maxHeight: '80vh'
}}
>
{/* 1. The Tree Background */}
<ChristmasTree audioLevel={audioLevel} />
{/* 2. The Interactive Ornaments Layer */}
<div className="absolute inset-0 pointer-events-auto">
{ornaments.map((ornament) => (
<Ornament
key={ornament.id}
config={ornament}
settings={settings}
audioLevel={audioLevel}
/>
))}
</div>
{/* 3. Intro Animation Layer (Relative to tree coords) */}
{introTarget && (
<IntroAnimation
target={introTarget}
settings={settings}
onComplete={handleIntroComplete}
/>
)}
</div>
{/* Text Greeting */}
<div className="w-full text-center pointer-events-none z-30 mb-2">
<h1 className="font-christmas text-3xl md:text-5xl text-yellow-100 drop-shadow-[0_2px_4px_rgba(0,0,0,0.8)] animate-pulse">
Lieve kerstgroeten van <br className="md:hidden" /> Jeroen en Lyda
</h1>
</div>
{/* Settings Menu */}
<SettingsMenu
isOpen={isMenuOpen}
setIsOpen={setIsMenuOpen}
settings={settings}
onUpdateSettings={setSettings}
onReloadSounds={initOrnaments}
onUpdateBackground={setBgImage}
currentBgImage={bgImage || undefined}
/>
</div>
</div>
);
};
export default App;