Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions docs/site-audio.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,19 @@ as original-cast masters; the owner accepted the candidates for this project.
- The public page has one icon button: mute/unmute theme music only. It never
stops dialogue or Sharingan effects. The visitor's theme mute preference is
saved separately; old per-browser volume settings are ignored.
- The theme is preloaded from the document head. The mixer starts immediately
on mount, in parallel with the settings API; a slow settings response cannot
hold up the theme. Saved admin settings are applied when the response arrives.
- Automatic startup attempts to play the theme on load. Browser autoplay policy
may suspend it until the first pointer or key interaction. That interaction
unlocks the same mixer; it never creates duplicate theme sources.
- The theme starts at zero gain and ramps to its configured level over 4 seconds,
then holds there. Default theme is 75%, dialogue 100%, and eye effects 95%.
- The theme loops continuously beneath voices and effects. A master compressor
reduces peaks when loud channels mix; individual sources remain independent.
- The theme loops continuously beneath voices and effects. During a quote it
fades to 20% of its configured level over 150 ms, then restores over 800 ms
when the quote ends or is canceled. The loop never stops or restarts. Theme
mute takes priority, including when a quote ends. A master compressor reduces
combined peaks; dialogue and effects keep their own channel levels.
- The first dialogue starts after 20 seconds of active playback. Every later
dialogue waits 20 seconds after the previous recording ENDS, irrespective of
clip length. Settings refreshes do not restart an unchanged countdown.
Expand All @@ -47,7 +53,10 @@ as original-cast masters; the owner accepted the candidates for this project.
The authenticated dashboard has a **Site audio** section with all three channel
levels, dialogue gap (1–600 seconds), theme fade (0–30 seconds), automatic
character dialogue, and individual clip enable switches and preview players.
Defaults can be restored in the form, then saved explicitly.
Defaults can be restored in the form, then saved explicitly. Numeric fields
retain string drafts while typing, so zero can be deleted and replaced. Empty
required values and out-of-range values are rejected before a save request;
only validated numbers are sent to the API.

`GET /api/site-audio` returns public, non-sensitive settings; before the first
save it returns the defaults. `PUT /api/site-audio` requires the existing admin
Expand All @@ -62,7 +71,8 @@ the admin form reports the error and never pretends an unsuccessful save worked.
## Validation

Run TypeScript, ESLint, Jest, and the production build. Tests cover theme-only
mute, fade targets, short and long dialogue completion plus the full gap,
mute, duck/restore/cancel behavior, slow-settings startup, editable numeric
drafts, fade targets, short and long dialogue completion plus the full gap,
blocked-autoplay unlock without duplicate music, admin-only writes, persistence
contracts, invalid settings, playlist assets, and public/admin UI separation.
Browser checks should exercise the fade, theme-only mute with active dialogue
Expand Down
2 changes: 2 additions & 0 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { SiteFooter } from "@/components/site-footer";
import { getFooterData } from "@/lib/portfolio-data";
import { ExperienceGate } from "@/components/cyber/experience-gate";
import { SiteAudio } from '@/components/cyber/site-audio';
import { MUSIC_TRACK } from '@/lib/site-audio-library';
import { CyberCursor } from "@/components/cyber/cyber-cursor";

const SITE_TITLE = 'Bikram Dey | Hack. Secure. Defend.';
Expand Down Expand Up @@ -57,6 +58,7 @@ export default async function RootLayout({
return (
<html lang="en" className="dark" suppressHydrationWarning>
<head>
<link rel="preload" as="fetch" href={MUSIC_TRACK} crossOrigin="anonymous" fetchPriority="high" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" />
Expand Down
24 changes: 24 additions & 0 deletions src/components/admin/__tests__/audio-panel.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,27 @@ test('a failed load cannot overwrite unknown saved settings with defaults', asyn
expect(await screen.findByRole('alert')).toHaveTextContent('Settings unavailable');
expect(screen.queryByRole('button', { name: 'Save audio settings' })).not.toBeInTheDocument();
});

test('numeric drafts can be cleared and retyped, including a zero fade and fractional values', async () => {
jest.mocked(api).mockImplementation(async (_path, options) => options?.method === 'PUT'
? options.body as never : { ...DEFAULT_AUDIO_SETTINGS, fadeSeconds: 0 } as never);
render(<AudioPanel />);
const gap = await screen.findByLabelText('Gap after each dialogue (seconds)');
const fade = screen.getByLabelText('Theme fade-in (seconds)');
expect(fade).toHaveValue(0);
fireEvent.change(fade, { target: { value: '' } });
fireEvent.change(gap, { target: { value: '' } });
expect(fade).toHaveValue(null);
expect(gap).toHaveValue(null);
fireEvent.click(screen.getByRole('button', { name: 'Save audio settings' }));
expect(await screen.findByRole('alert')).toHaveTextContent('Enter the gap');
expect(api).not.toHaveBeenCalledWith('/api/site-audio', expect.objectContaining({ method: 'PUT' }));
fireEvent.change(gap, { target: { value: '35' } });
fireEvent.change(fade, { target: { value: '0.5' } });
fireEvent.click(screen.getByRole('button', { name: 'Save audio settings' }));
await waitFor(() => expect(api).toHaveBeenCalledWith('/api/site-audio', { method: 'PUT', body: {
...DEFAULT_AUDIO_SETTINGS, intervalSeconds: 35, fadeSeconds: 0.5,
} }));
expect(await screen.findByRole('status')).toHaveTextContent('saved for all visitors');
expect(fade).toHaveValue(0.5);
});
29 changes: 29 additions & 0 deletions src/components/admin/__tests__/collection-numbers.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { CollectionEditor } from '../collection-editor';
import { api } from '../api-client';
const toast = jest.fn();
jest.mock('../api-client', () => ({ api: jest.fn(), errorMessage: (e: Error) => e.message }));
jest.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast }) }));
jest.mock('lucide-react', () => ({ Pencil: () => null, Plus: () => null, RefreshCw: () => null, Trash2: () => null, X: () => null, Loader2: () => null }));

test('collection number fields allow deleting zero and send numbers only at save time', async () => {
const row = { id: '1', bounty: 0, points: 0, year: 0 };
jest.mocked(api).mockImplementation(async (_path, options) => options?.method === 'PUT'
? { ...row, ...options.body as object } as never : [row] as never);
render(<CollectionEditor title="Number fields" endpoint="/api/test-numbers"
fields={['bounty', 'points', 'year'].map(name => ({ name, label: name, type: 'number' as const }))}
itemTitle={() => 'Entry'} />);
fireEvent.click(await screen.findByRole('button', { name: 'Edit Entry' }));
for (const [field, value] of [['bounty', '100'], ['points', '20'], ['year', '2026']]) {
const input = screen.getByLabelText(field);
fireEvent.change(input, { target: { value: '' } });
expect(input).toHaveValue(null);
fireEvent.change(input, { target: { value } });
expect(input).toHaveValue(Number(value));
}
fireEvent.change(screen.getByLabelText('points'), { target: { value: '' } });
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
await waitFor(() => expect(api).toHaveBeenCalledWith('/api/test-numbers/1', {
method: 'PUT', body: { bounty: 100, points: null, year: 2026 },
}));
});
24 changes: 23 additions & 1 deletion src/components/admin/__tests__/github-panel.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import '@testing-library/jest-dom';
import { render, screen, waitFor } from '@testing-library/react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { GitHubPanel } from '../github-panel';
import { api } from '../api-client';
const toast = jest.fn();
Expand All @@ -20,3 +20,25 @@ test('checks for automatic refresh and labels repos hidden from the public site'
expect(screen.getByRole('switch', { name: 'Show repo on the site' })).toHaveAttribute('aria-checked', 'false');
expect(screen.getByRole('button', { name: 'Refresh list' })).toBeEnabled();
});

test('a zero repository pin position can be cleared and saved as automatic ordering', async () => {
jest.clearAllMocks();
jest.mocked(api).mockImplementation(async (path, options) => {
if (path === '/api/personal-data') return null as never;
if (path === '/api/github/sync') return { skipped: true, data: null } as never;
if (options?.method === 'PUT') return { repository: { ...repo, displayOrder: null } } as never;
return { repositories: [{ ...repo, displayOrder: 0 }], stats: { lastSync: null, lastError: null } } as never;
});
render(<GitHubPanel />);
const edit = await screen.findByRole('button', { name: 'Customize' });
await waitFor(() => expect(edit).toBeEnabled());
fireEvent.click(edit);
const position = screen.getByLabelText('Pin position');
expect(position).toHaveValue(0);
fireEvent.change(position, { target: { value: '' } });
expect(position).toHaveValue(null);
fireEvent.click(screen.getByRole('button', { name: /^Save$/ }));
await waitFor(() => expect(api).toHaveBeenCalledWith('/api/github/repos/1', {
method: 'PUT', body: { customTitle: '', customDescription: '', customTags: [], displayOrder: null },
}));
});
34 changes: 25 additions & 9 deletions src/components/admin/audio-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,21 @@ import { AUDIO_SETTINGS_EVENT, DEFAULT_AUDIO_SETTINGS, DIALOGUES, parseAudioSett
import { api, errorMessage } from './api-client';
import { Btn, Field, Panel, TextInput, Toggle } from './ui';

type AudioDraft = Omit<AudioSettings, 'intervalSeconds' | 'fadeSeconds'> & {
intervalSeconds: string; fadeSeconds: string;
};
const toDraft = (settings: AudioSettings): AudioDraft => ({
...settings, intervalSeconds: String(settings.intervalSeconds), fadeSeconds: String(settings.fadeSeconds),
});

export function AudioPanel() {
const [settings, setSettings] = useState<AudioSettings | null>(null);
const [settings, setSettings] = useState<AudioDraft | null>(null);
const [busy, setBusy] = useState(false);
const [notice, setNotice] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const load = async () => {
setBusy(true);
try { setSettings(parseAudioSettings(await api('/api/site-audio'))); setError(null); }
try { setSettings(toDraft(parseAudioSettings(await api('/api/site-audio')))); setError(null); }
catch (e) { setError(errorMessage(e)); }
finally { setBusy(false); }
};
Expand All @@ -21,7 +28,16 @@ export function AudioPanel() {
if (!settings) return;
setBusy(true); setNotice(null);
try {
setSettings(parseAudioSettings(await api('/api/site-audio', { method: 'PUT', body: settings })));
if (!settings.intervalSeconds.trim()) throw new Error('Enter the gap after each dialogue.');
if (!settings.fadeSeconds.trim()) throw new Error('Enter the theme fade duration.');
const intervalSeconds = Number(settings.intervalSeconds);
const fadeSeconds = Number(settings.fadeSeconds);
if (!Number.isInteger(intervalSeconds) || intervalSeconds < 1 || intervalSeconds > 600)
throw new Error('Dialogue gap must be a whole number from 1 to 600 seconds.');
if (!Number.isFinite(fadeSeconds) || fadeSeconds < 0 || fadeSeconds > 30)
throw new Error('Theme fade duration must be from 0 to 30 seconds.');
const body: AudioSettings = { ...settings, intervalSeconds, fadeSeconds };
setSettings(toDraft(parseAudioSettings(await api('/api/site-audio', { method: 'PUT', body }))));
window.dispatchEvent(new Event(AUDIO_SETTINGS_EVENT));
setNotice('Audio settings saved for all visitors. Open pages refresh within one minute.'); setError(null);
} catch (e) { setError(errorMessage(e)); }
Expand All @@ -42,12 +58,12 @@ export function AudioPanel() {
</div>
<div className="grid gap-6 md:grid-cols-2">
<Field label="Gap after each dialogue (seconds)" htmlFor="audio-gap" hint="Measured from the end of a recording, regardless of its length.">
<TextInput id="audio-gap" type="number" min="1" max="600" step="1" value={settings.intervalSeconds}
onChange={e => setSettings({ ...settings, intervalSeconds: Number(e.target.value) })} />
<TextInput id="audio-gap" type="number" required min="1" max="600" step="1" value={settings.intervalSeconds}
onChange={e => setSettings({ ...settings, intervalSeconds: e.target.value })} />
</Field>
<Field label="Theme fade-in (seconds)" htmlFor="audio-fade" hint="Starts silent and rises to the theme volume, then stays there.">
<TextInput id="audio-fade" type="number" min="0" max="30" step="0.5" value={settings.fadeSeconds}
onChange={e => setSettings({ ...settings, fadeSeconds: Number(e.target.value) })} />
<TextInput id="audio-fade" type="number" required min="0" max="30" step="0.5" value={settings.fadeSeconds}
onChange={e => setSettings({ ...settings, fadeSeconds: e.target.value })} />
</Field>
</div>
<div className="flex items-center gap-3"><Toggle label="Automatic character dialogue" checked={settings.randomDialogue}
Expand All @@ -71,10 +87,10 @@ export function AudioPanel() {
</div>
<div className="flex flex-wrap gap-3">
<Btn onClick={() => void save()}>Save audio settings</Btn>
<Btn variant="outline" onClick={() => { setSettings({ ...DEFAULT_AUDIO_SETTINGS, enabledDialogueIds: [...DEFAULT_AUDIO_SETTINGS.enabledDialogueIds] }); setNotice('Defaults restored in this form. Save to apply.'); }}>Restore defaults</Btn>
<Btn variant="outline" onClick={() => { setSettings(toDraft({ ...DEFAULT_AUDIO_SETTINGS, enabledDialogueIds: [...DEFAULT_AUDIO_SETTINGS.enabledDialogueIds] })); setNotice('Defaults restored in this form. Save to apply.'); }}>Restore defaults</Btn>
</div>
</fieldset>
<p className="mt-5 text-xs text-muted-foreground">Theme loops throughout browsing beneath the voices. Browsers may require the first tap or keypress before audio starts. Muting the public theme button leaves dialogue and effects active.</p>
<p className="mt-5 text-xs text-muted-foreground">Theme lowers to 20% of its configured volume while a quote plays, then returns smoothly. Browsers may require the first tap or keypress before audio starts. Muting the public theme button leaves dialogue and effects active.</p>
</>}
</Panel>;
}
11 changes: 11 additions & 0 deletions src/components/cyber/__tests__/site-audio.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,14 @@ test('visitor volume overrides are ignored; only theme mute persists', async ()
expect(mockSettings).toHaveBeenLastCalledWith(settings);
expect(screen.getByRole('button', { name: 'Unmute theme music' })).toBeVisible();
});

test('theme startup does not wait for a slow settings response', async () => {
let finish!: (r: Response) => void;
jest.mocked(global.fetch).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
render(<SiteAudio />);
expect(mockEnable).toHaveBeenCalledTimes(1);
expect(mockSettings).not.toHaveBeenCalled();
await act(async () => finish({ ok: true, json: async () => ({ ...DEFAULT_AUDIO_SETTINGS, music: 0.5 }) } as Response));
expect(mockSettings).toHaveBeenCalledWith(expect.objectContaining({ music: 0.5 }));
expect(mockEnable).toHaveBeenCalledTimes(1);
});
5 changes: 4 additions & 1 deletion src/components/cyber/site-audio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ export function SiteAudio() {
if (!controller.signal.aborted) mixer.setSettings(settings);
} catch { /* Defaults keep audio working if settings cannot load. */ }
};
void load().then(() => { if (!controller.signal.aborted) void mixer.enable(); });
// Never put the settings API (including its cold-start timeout) on the
// audio startup path. Apply shared settings as soon as they arrive.
void mixer.enable();
void load();
const refresh = setInterval(() => { if (!document.hidden) void load(); }, 60_000);
const onSettings = () => { void load(); };
const onGesture = () => mixer.unlock();
Expand Down
29 changes: 29 additions & 0 deletions src/lib/__tests__/site-audio.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,3 +221,32 @@ test('a real gesture unlocks a pending autoplay attempt without starting duplica
await starting;
expect(sources.filter(s => s.loop)).toHaveLength(1);
});

test.each(['end', 'cancel'] as const)('ducks under an active quote and restores the saved theme level on %s', async action => {
await engine.enable();
await engine.playDialogue();
expect(gains[0].gain.linearRampToValueAtTime).toHaveBeenLastCalledWith(expect.closeTo(0.15), 12.15);
engine.setSettings({ ...DEFAULT_AUDIO_SETTINGS, music: 0.4 });
expect(gains[0].gain.linearRampToValueAtTime).toHaveBeenLastCalledWith(expect.closeTo(0.08), 12.15);
if (action === 'end') sources[1].onended?.();
else engine.stopDialogue();
expect(gains[0].gain.linearRampToValueAtTime).toHaveBeenLastCalledWith(0.4, 12.8);
expect(sources[0].start).toHaveBeenCalledTimes(1);
expect(sources[0].stop).not.toHaveBeenCalled();
});

test('ducking waits for the recording to load and never overrides theme mute', async () => {
await engine.enable();
gains[0].gain.linearRampToValueAtTime.mockClear();
let finish!: (r: Response) => void;
jest.mocked(global.fetch).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
const playing = engine.playDialogue();
expect(gains[0].gain.linearRampToValueAtTime).not.toHaveBeenCalled();
finish({ ok: true, arrayBuffer: async () => new ArrayBuffer(1) } as Response);
await playing;
engine.setThemeMuted(true);
sources[1].onended?.();
expect(gains[0].gain.linearRampToValueAtTime).toHaveBeenLastCalledWith(0, 12.8);
engine.setThemeMuted(false);
expect(gains[0].gain.linearRampToValueAtTime).toHaveBeenLastCalledWith(0.75, 16);
});
11 changes: 8 additions & 3 deletions src/lib/site-audio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export class SiteAudioEngine {
for (const key of ['dialogue', 'effects'] as const) {
this.gains[key].gain.setTargetAtTime(settings[key], this.context.currentTime, 0.03);
}
if (this.music) this.fadeTheme();
if (this.music) this.fadeTheme(this.voice ? 0.15 : this.settings.fadeSeconds);
}
if (!settings.randomDialogue || settings.dialogue === 0 ||
(this.status.quote && !settings.enabledDialogueIds.includes(this.status.quote.id))) this.stopDialogue();
Expand All @@ -94,7 +94,8 @@ export class SiteAudioEngine {
const now = this.context.currentTime;
gain.cancelScheduledValues(now);
gain.setValueAtTime(gain.value, now);
gain.linearRampToValueAtTime(this.themeMuted ? 0 : this.settings.music, now + seconds);
const target = this.themeMuted ? 0 : this.settings.music * (this.voice ? 0.2 : 1);
gain.linearRampToValueAtTime(target, now + seconds);
}

/** Call synchronously in a pointer/key handler for browser autoplay policy. */
Expand Down Expand Up @@ -190,8 +191,10 @@ export class SiteAudioEngine {
stopDialogue() {
this.clearDialogueTimer();
++this.voiceRequest;
const wasPlaying = !!this.voice;
this.stop(this.voice);
this.voice = null;
if (wasPlaying && this.music) this.fadeTheme(0.8);
if (this.status.quote) this.update({ quote: null });
}

Expand Down Expand Up @@ -264,18 +267,20 @@ export class SiteAudioEngine {
this.settings.dialogue === 0 || this.context?.state !== 'running') return;
const voice = this.node(buffer, 'dialogue');
this.voice = voice;
this.fadeTheme(0.15);
this.lastDialogue = index;
this.update({ quote });
voice.onended = () => {
voice.disconnect();
if (this.voice === voice) {
this.voice = null;
this.fadeTheme(0.8);
this.update({ quote: null });
this.scheduleDialogue();
}
};
voice.start();
// Music is a separate source: no stop, pause, restart, or ducking here.
// Duck only its gain: the same looping music source continues underneath.
} catch {
// Skip an unavailable quote and leave the music running.
} finally {
Expand Down
Loading