feat: 添加滚动环境和媒体状态管理,优化头部组件功能,支持背景音乐和主题切换

This commit is contained in:
2026-09-01 14:39:37 +08:00
parent b8483e94a6
commit 602f1c82ed
8 changed files with 537 additions and 22 deletions
+8
View File
@@ -60,3 +60,11 @@ html, body {
html::-webkit-scrollbar, body::-webkit-scrollbar { html::-webkit-scrollbar, body::-webkit-scrollbar {
display: none; /* Chrome, Safari and Opera */ display: none; /* Chrome, Safari and Opera */
} }
@keyframes vh-fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
+88 -2
View File
@@ -1,6 +1,7 @@
"use client"; "use client";
import { Canvas } from "@react-three/fiber"; import { useEffect, useRef } from "react";
import { Canvas, useThree } from "@react-three/fiber";
import { PerspectiveCamera } from "@react-three/drei"; import { PerspectiveCamera } from "@react-three/drei";
import { StickerDrop, StickerCamera } from "@/components/canvas/StickerDrop"; import { StickerDrop, StickerCamera } from "@/components/canvas/StickerDrop";
@@ -12,6 +13,52 @@ import PostFX from "@/components/canvas/PostFX";
import { useAppReady } from "@/components/dom/LoadingOverlay"; import { useAppReady } from "@/components/dom/LoadingOverlay";
import { useIsMobile } from "@/lib/useIsMobile"; import { useIsMobile } from "@/lib/useIsMobile";
/**
* R3F's initial measurement can race page CSS on first load: the canvas
* mounts before styles are applied, react-use-measure reports the canvas
* element's intrinsic size (300×150 → 1440×150) instead of the fixed
* inset-0 container (100vh), and R3F writes that stale size into
* canvas.style — permanently, because its ResizeObserver never fires
* again (the container never actually changes size afterwards). Any real
* window resize re-measures and self-heals. This guard re-runs R3F's own
* size pipeline when it detects that mismatch, so the canvas is always
* sized to its container.
*/
function CanvasSizeGuard() {
const gl = useThree((s) => s.gl);
const setSize = useThree((s) => s.setSize);
useEffect(() => {
const canvas = gl.domElement;
let raf = 0;
let ticks = 0;
const fix = () => {
const parent = canvas.parentElement;
if (parent) {
const cw = parent.clientWidth;
const ch = parent.clientHeight;
const styleW = parseFloat(canvas.style.width) || 0;
const styleH = parseFloat(canvas.style.height) || 0;
if (
cw > 0 &&
ch > 0 &&
(Math.abs(styleW - cw) > 1 || Math.abs(styleH - ch) > 1)
) {
// Re-run R3F's sizing: store.setSize updates size state + viewport
// (camera aspect, consumers), gl.setSize resizes the drawing
// buffer and canvas style.
gl.setSize(cw, ch, true);
setSize(cw, ch);
}
}
ticks += 1;
if (ticks < 40) raf = requestAnimationFrame(fix);
};
raf = requestAnimationFrame(fix);
return () => cancelAnimationFrame(raf);
}, [gl, setSize]);
return null;
}
/** /**
* Hero canvas: animated background + falling stickers + glass models + * Hero canvas: animated background + falling stickers + glass models +
* DOM-tracked image layers. * DOM-tracked image layers.
@@ -27,14 +74,53 @@ import { useIsMobile } from "@/lib/useIsMobile";
export function HeroScene() { export function HeroScene() {
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const ready = useAppReady(); const ready = useAppReady();
const hostRef = useRef<HTMLDivElement>(null);
// Watchdog (outside the Canvas so it runs even before R3F configures):
// R3F's react-use-measure can capture a stale intrinsic-size measurement
// on first load (canvas 300×150 before page CSS applies) and its
// ResizeObserver then never fires again — the canvas stays squished
// until a real window resize. react-use-measure independently listens
// to window 'resize' (debounced 0ms), so dispatching one forces a fresh
// measurement and reconfigures R3F with the correct container size.
useEffect(() => {
const host = hostRef.current;
if (!host) return;
const fix = () => {
const canvas = host.querySelector("canvas");
if (!canvas) return;
const cw = host.clientWidth;
const ch = host.clientHeight;
const sw = parseFloat(canvas.style.width) || 0;
const sh = parseFloat(canvas.style.height) || 0;
if (
cw > 0 &&
ch > 0 &&
(Math.abs(sw - cw) > 1 || Math.abs(sh - ch) > 1)
) {
window.dispatchEvent(new Event("resize"));
}
};
const raf = requestAnimationFrame(() => requestAnimationFrame(fix));
const iv = window.setInterval(fix, 250);
document.fonts?.ready?.then(fix).catch(() => {});
return () => {
cancelAnimationFrame(raf);
window.clearInterval(iv);
};
}, []);
return ( return (
// z-30 keeps it above the BackgroundGrid (z-20) to prevent mix-blend-difference from making it gray // z-30 keeps it above the BackgroundGrid (z-20) to prevent mix-blend-difference from making it gray
<div className="z-30 fixed inset-0 w-full h-full pointer-events-none"> <div
ref={hostRef}
className="z-30 fixed inset-0 w-full h-full pointer-events-none"
>
<Canvas <Canvas
dpr={[1, 2]} dpr={[1, 2]}
gl={{ alpha: true, antialias: true }} gl={{ alpha: true, antialias: true }}
> >
<CanvasSizeGuard />
{/* Camera rig: horizontal FOV 60/38, distance lerp(24, 32, sP), {/* Camera rig: horizontal FOV 60/38, distance lerp(24, 32, sP),
intro dolly z+8 → A (customCubic, 1.2s, ready-gated), mouse intro dolly z+8 → A (customCubic, 1.2s, ready-gated), mouse
parallax (desktop). */} parallax (desktop). */}
+267 -19
View File
@@ -1,17 +1,65 @@
"use client"; "use client";
import { useEffect, useState } from "react"; import { useCallback, useEffect, useRef, useState } from "react";
import ScrambleReveal from "@/components/dom/ScrambleReveal"; import ScrambleReveal from "@/components/dom/ScrambleReveal";
import { useShellMedia, type ThemeSetting } from "@/lib/shellMedia";
import { useBgm } from "@/lib/useBgm";
import { scrollEnv } from "@/lib/scrollEnv";
/** /**
* Header, matching the original: scramble-revealed labels (startDelay 300), * Header — ported from the original (chunk 2689132c4e070b68.js):
* live local clock (HH:MM, minute tick), and a center coordinate readout *
* driven by the pointer (normalized position × viewport size, zero-padded 4). * - THEME[L]/THEME[D]/THEME[A]: click cycles light→dark→system; global
* keyboard [L]/[D]/[A] (original ASCIIThemeToggle; theme rendering is
* light-only in this port, the setting is stored).
* - SOUND[|/-\] / SOUND[·]: background music (/bgm.mp3, loop, 0.35);
* spinner chars cycle at 130ms while playing; keyboard [S]
* (original ASCIISoundToggle); choice persisted.
* - Hovering THEME/SOUND increments a counter that reveals the fixed
* nav-hint panel (top-24): keyboard help + browser name + viewport
* size. Pointer-down or any shortcut key resets it; changing
* theme/sound also hides it (original P counter logic).
* - Bottom row: live clock, pointer coordinate readout (click → scroll
* to top), and — replacing the original RotatingGlobe — the
* VIRTHEART copyright line.
* - Keyboard [T] scroll to top, [B] scroll to bottom.
*/ */
const SPINNER = ["|", "/", "-", "\\"];
const dotted =
"relative before:content-[''] before:absolute before:inset-0 before:border-2 before:border-dotted before:border-transparent before:pointer-events-none before:transition-colors before:duration-200 lg:hover:before:border-l1";
function useBrowserName(): string {
const [name, setName] = useState("Unknown");
useEffect(() => {
const ua = navigator.userAgent;
let result = "Unknown";
if (/Edg\//.test(ua)) result = "Edge";
else if (/OPR\//.test(ua)) result = "Opera";
else if (/Firefox\//.test(ua)) result = "Firefox";
else if (/Chrome\//.test(ua)) result = "Chrome";
else if (/Safari\//.test(ua)) result = "Safari";
setName(result);
}, []);
return name;
}
export default function Header() { export default function Header() {
const { theme, setTheme, soundEnabled, setSoundEnabled } = useShellMedia();
useBgm(soundEnabled);
const [time, setTime] = useState("--:--"); const [time, setTime] = useState("--:--");
const [coords, setCoords] = useState({ x: "0001", y: "0001" }); const [coords, setCoords] = useState({ x: "0001", y: "0001" });
const [hintCount, setHintCount] = useState(0);
const [spinnerIndex, setSpinnerIndex] = useState(0);
const [toggleEpoch, setToggleEpoch] = useState(0);
const interactedRef = useRef(false);
const browserName = useBrowserName();
const [viewport, setViewport] = useState({ w: 0, h: 0 });
const year = new Date().getFullYear();
// Clock tick (original: minute interval).
useEffect(() => { useEffect(() => {
const tick = () => { const tick = () => {
const d = new Date(); const d = new Date();
@@ -24,26 +72,115 @@ export default function Header() {
return () => window.clearInterval(interval); return () => window.clearInterval(interval);
}, []); }, []);
// Pointer coordinates (original usePointerPosition × viewport, y-up).
useEffect(() => { useEffect(() => {
const onMove = (e: PointerEvent) => { const onMove = (e: PointerEvent) => {
const x = Math.round(e.clientX); const x = Math.round(e.clientX);
const y = Math.round( const y = Math.round(window.innerHeight - e.clientY);
(window.innerHeight || 0) - e.clientY
);
setCoords({ setCoords({
x: String(Math.max(0, x)).padStart(4, "0").slice(0, 4), x: String(Math.max(0, Math.min(9999, x))).padStart(4, "0"),
y: String(Math.max(0, y)).padStart(4, "0").slice(0, 4), y: String(Math.max(0, Math.min(9999, y))).padStart(4, "0"),
}); });
}; };
window.addEventListener("pointermove", onMove, { passive: true }); window.addEventListener("pointermove", onMove, { passive: true });
return () => window.removeEventListener("pointermove", onMove); return () => window.removeEventListener("pointermove", onMove);
}, []); }, []);
const dotted = // Viewport size for the hint panel (original useWindowSize).
"relative before:content-[''] before:absolute before:inset-0 before:border-2 before:border-dotted before:border-transparent before:pointer-events-none before:transition-colors before:duration-200 lg:hover:before:border-l1"; useEffect(() => {
const update = () =>
setViewport({ w: window.innerWidth, h: window.innerHeight });
update();
window.addEventListener("resize", update, { passive: true });
return () => window.removeEventListener("resize", update);
}, []);
// Spinner while sound is playing (original 130ms interval).
useEffect(() => {
if (!soundEnabled) {
setSpinnerIndex(0);
return;
}
const interval = window.setInterval(
() => setSpinnerIndex((i) => (i + 1) % SPINNER.length),
130
);
return () => window.clearInterval(interval);
}, [soundEnabled]);
const bumpHint = useCallback(() => setHintCount((c) => c + 1), []);
const sinkHint = useCallback(() => setHintCount((c) => Math.max(0, c - 1)), []);
const resetHint = useCallback(() => setHintCount(0), []);
// Changing theme/sound hides the hint panel (original effect).
const prevRef = useRef({ theme, soundEnabled });
useEffect(() => {
const prev = prevRef.current;
if (prev.theme !== theme || prev.soundEnabled !== soundEnabled) {
prevRef.current = { theme, soundEnabled };
setHintCount((c) => (c > 0 ? 0 : c));
}
}, [theme, soundEnabled]);
const cycleTheme = useCallback(() => {
interactedRef.current = true;
setToggleEpoch((e) => e + 1);
const order: ThemeSetting[] = ["light", "dark", "system"];
const next = order[(order.indexOf(theme) + 1) % order.length];
setTheme(next);
}, [theme, setTheme]);
const toggleSound = useCallback(() => {
interactedRef.current = true;
setToggleEpoch((e) => e + 1);
setSoundEnabled(!soundEnabled);
}, [soundEnabled, setSoundEnabled]);
// Global keyboard shortcuts: [L]/[D]/[A] theme, [S] sound, [T]/[B] edges.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (
e.defaultPrevented ||
e.metaKey ||
e.ctrlKey ||
e.altKey ||
(e.target instanceof HTMLElement &&
["INPUT", "TEXTAREA", "SELECT"].includes(e.target.tagName))
) {
return;
}
const key = e.key.length === 1 ? e.key.toLowerCase() : "";
if (!key) return;
if (["l", "d", "a", "s"].includes(key)) resetHint();
if (key === "l") {
setTheme("light");
} else if (key === "d") {
setTheme("dark");
} else if (key === "a") {
setTheme("system");
} else if (key === "s") {
toggleSound();
} else if (key === "t") {
scrollEnv.scrollToTop("smooth");
} else if (key === "b") {
scrollEnv.scrollToBottom("smooth");
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [resetHint, setTheme, toggleSound]);
const themeLabel =
theme === "light" ? "THEME[L]" : theme === "dark" ? "THEME[D]" : "THEME[A]";
const soundLabel = soundEnabled
? `SOUND[${SPINNER[spinnerIndex]}]`
: "SOUND[\u00B7]";
const toggleCommon =
"inline-flex shrink-0 items-baseline gap-0 normal-case";
return ( return (
<header className="z-50 fixed inset-0 flex flex-col justify-between font-mono-2 pointer-events-none transition-colors duration-300 ease-out text-l1"> <header className="z-50 fixed inset-0 flex flex-col justify-between font-mono-2 pointer-events-none text-l1">
<div className="flex justify-between items-center px-4 lg:px-14 py-4 lg:py-7 text-base"> <div className="flex justify-between items-center px-4 lg:px-14 py-4 lg:py-7 text-base">
<a <a
className={`${dotted} p-2 font-sans font-bold uppercase pointer-events-auto transition-colors duration-300 ease-out`} className={`${dotted} p-2 font-sans font-bold uppercase pointer-events-auto transition-colors duration-300 ease-out`}
@@ -54,29 +191,131 @@ export default function Header() {
<ScrambleReveal text=".design" startDelayMs={300} scrambleColors={false} /> <ScrambleReveal text=".design" startDelayMs={300} scrambleColors={false} />
</a> </a>
<div className="hidden lg:flex flex-wrap justify-between items-center gap-x-3 gap-y-2 pointer-events-auto basis-1/2 xl:basis-1/3"> <div className="hidden lg:flex flex-wrap justify-between items-center gap-x-3 gap-y-2 pointer-events-auto basis-1/2 xl:basis-1/3">
<button type="button" className={`${dotted} p-2 uppercase cursor-pointer`}> <button
type="button"
className={`${dotted} p-2 uppercase cursor-pointer`}
onClick={() => scrollEnv.scrollToSection('[data-section="about"]')}
>
<ScrambleReveal text="Work" startDelayMs={300} scrambleColors={false} /> <ScrambleReveal text="Work" startDelayMs={300} scrambleColors={false} />
</button> </button>
<button type="button" className={`${dotted} p-2 uppercase cursor-pointer`}> <button
type="button"
className={`${dotted} p-2 uppercase cursor-pointer`}
onClick={() => scrollEnv.scrollToBottom("smooth")}
>
<ScrambleReveal text="Contact" startDelayMs={300} scrambleColors={false} /> <ScrambleReveal text="Contact" startDelayMs={300} scrambleColors={false} />
</button> </button>
<span role="button" tabIndex={0} className={`${dotted} p-2 uppercase cursor-pointer pointer-events-auto`}> <span
<ScrambleReveal text="THEME[A]" startDelayMs={300} scrambleColors={false} /> role="button"
tabIndex={0}
aria-label={`Theme: ${theme}`}
className={`${dotted} ${toggleCommon} p-2 uppercase cursor-pointer pointer-events-auto`}
onClick={(e) => {
e.preventDefault();
cycleTheme();
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
cycleTheme();
}
}}
onPointerEnter={bumpHint}
onPointerLeave={sinkHint}
onPointerDown={resetHint}
>
<ScrambleReveal
key={`theme-${theme}-${toggleEpoch}`}
text={themeLabel}
startDelayMs={interactedRef.current ? 100 : 300}
scrambleColors={false}
/>
</span> </span>
<span role="button" tabIndex={0} className={`${dotted} p-2 uppercase cursor-pointer pointer-events-auto normal-case`}> <span
<ScrambleReveal text="SOUND[|]" startDelayMs={300} scrambleColors={false} /> role="button"
tabIndex={0}
aria-label={
soundEnabled ? "Sound playing, click to pause" : "Sound paused, click to play"
}
aria-pressed={soundEnabled}
className={`${dotted} ${toggleCommon} p-2 uppercase cursor-pointer pointer-events-auto`}
onClick={(e) => {
e.preventDefault();
toggleSound();
}}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
toggleSound();
}
}}
onPointerEnter={bumpHint}
onPointerLeave={sinkHint}
onPointerDown={resetHint}
>
<ScrambleReveal
key={`sound-${soundEnabled}-${toggleEpoch}`}
text={soundLabel}
startDelayMs={soundEnabled ? 100 : 300}
letterDelayMs={80}
scrambleColors={false}
/>
</span> </span>
</div> </div>
</div> </div>
{/* Nav hint panel — revealed by hovering THEME/SOUND (original P>0,
fade .4s cubic-bezier(.25,1,.5,1) via AnimatePresence). */}
{hintCount > 0 && (
<div
className="hidden top-24 right-0 left-0 z-50 fixed lg:flex flex-row-reverse px-4 lg:px-14 w-full pointer-events-none"
style={{
animation: "vh-fade-in 0.4s cubic-bezier(0.25, 1, 0.5, 1) both",
}}
>
<div className="flex flex-col bg-be p-2 font-mono-2 text-l1 xl:basis-1/3 basis-1/2">
{/* Original hint-panel texts omit scrambleColors → the scramble
component's default (true) applies: chars flash the lime
phase colors #c0fe04 → #607F02 while revealing, and the
per-char 10ms stagger over the wrapped lines produces the
top-to-bottom green sweep. */}
<ScrambleReveal
text="Press [L] for light mode, [D] for dark mode, [A] for auto mode, or click THEME. Press [S] to pause or resume background music, or click SOUND; your choice is saved in this browser. [T] scroll to top, [B] scroll to bottom."
startDelayMs={0}
letterDelayMs={10}
/>
<br />
<span className="flex flex-row justify-between">
<ScrambleReveal
text={browserName}
startDelayMs={200}
letterDelayMs={10}
/>
<ScrambleReveal
text={`${viewport.w} \u00D7 ${viewport.h}`}
startDelayMs={200}
letterDelayMs={10}
/>
</span>
</div>
</div>
)}
<div className="flex justify-between px-4 lg:px-14 py-4 lg:py-7"> <div className="flex justify-between px-4 lg:px-14 py-4 lg:py-7">
<span className="lg:hidden p-2 uppercase"> <span className="lg:hidden p-2 uppercase">
<ScrambleReveal text={time} startDelayMs={300} letterDelayMs={40} scrambleColors={false} /> <ScrambleReveal text={time} startDelayMs={300} letterDelayMs={40} scrambleColors={false} />
</span> </span>
<span className="hidden lg:inline p-2 uppercase"> <span className="hidden lg:inline p-2 uppercase">
<ScrambleReveal text={`GMT+8 CN ${time}`} startDelayMs={300} letterDelayMs={40} scrambleColors={false} /> <ScrambleReveal
text={`GMT+8 CN ${time}`}
startDelayMs={300}
letterDelayMs={40}
scrambleColors={false}
/>
</span> </span>
<span <span
className={`${dotted} hidden lg:inline lg:bottom-7 lg:left-1/2 lg:fixed p-2 lg:-translate-x-1/2 cursor-pointer pointer-events-auto`} className={`${dotted} hidden lg:inline lg:bottom-7 lg:left-1/2 lg:fixed p-2 lg:-translate-x-1/2 cursor-pointer pointer-events-auto`}
onClick={() => scrollEnv.scrollToTop("smooth")}
> >
<ScrambleReveal <ScrambleReveal
text={`${coords.x} X ${coords.y} Y`} text={`${coords.x} X ${coords.y} Y`}
@@ -85,6 +324,15 @@ export default function Header() {
scrambleColors={false} scrambleColors={false}
/> />
</span> </span>
{/* VIRTHEART copyright — replaces the original RotatingGlobe. */}
<span className="hidden lg:inline p-2 uppercase">
<ScrambleReveal
text={`VIRTHEART (c) ${year}`}
startDelayMs={300}
letterDelayMs={40}
scrambleColors={false}
/>
</span>
</div> </div>
</header> </header>
); );
+3
View File
@@ -3,6 +3,7 @@
import { useEffect } from 'react'; import { useEffect } from 'react';
import Lenis from 'lenis'; import Lenis from 'lenis';
import { scrollBus } from '@/lib/scrollBus'; import { scrollBus } from '@/lib/scrollBus';
import { scrollEnv } from '@/lib/scrollEnv';
const clamp01 = (v: number) => Math.min(1, Math.max(0, v)); const clamp01 = (v: number) => Math.min(1, Math.max(0, v));
@@ -57,6 +58,7 @@ export default function SmoothScroller() {
lerp: 0.1, lerp: 0.1,
smoothWheel: true, smoothWheel: true,
}); });
scrollEnv.setLenis(lenis);
lenis.scrollTo(0, { immediate: true }); lenis.scrollTo(0, { immediate: true });
@@ -79,6 +81,7 @@ export default function SmoothScroller() {
return () => { return () => {
window.removeEventListener('resize', updateCameraProgress); window.removeEventListener('resize', updateCameraProgress);
window.removeEventListener('pageshow', onPageShow); window.removeEventListener('pageshow', onPageShow);
scrollEnv.setLenis(null);
lenis.destroy(); lenis.destroy();
}; };
}, []); }, []);
+45
View File
@@ -0,0 +1,45 @@
"use client";
/**
* Scroll environment — module singleton mirroring the original
* `scrollEnv` (module 29680): holds the Lenis instance so header
* shortcuts (coords click → top, [T] top, [B] bottom, Work/Contact
* anchors) can scroll from anywhere. SmoothScroller registers the
* instance on mount.
*/
type LenisLike = {
scrollTo: (
target: number | string | HTMLElement,
opts?: Record<string, unknown>
) => void;
} | null;
let lenis: LenisLike = null;
export const scrollEnv = {
setLenis(instance: LenisLike) {
lenis = instance;
},
getLenis() {
return lenis;
},
scrollToTop(behavior: "smooth" | "auto" = "smooth") {
if (lenis) lenis.scrollTo(0, { lerp: 0.1, immediate: behavior === "auto" });
else window.scrollTo({ top: 0, behavior });
},
scrollToBottom(behavior: "smooth" | "auto" = "smooth") {
const limit = Math.max(
0,
(document.documentElement?.scrollHeight ?? 0) - window.innerHeight
);
if (lenis) lenis.scrollTo(limit, { lerp: 0.1, immediate: behavior === "auto" });
else window.scrollTo({ top: limit, behavior });
},
scrollToSection(selector: string) {
const el = document.querySelector(selector);
if (!el) return;
if (lenis) lenis.scrollTo(el as HTMLElement, { lerp: 0.1 });
else (el as HTMLElement).scrollIntoView({ behavior: "smooth" });
},
};
+67
View File
@@ -0,0 +1,67 @@
"use client";
import { useCallback, useEffect, useState } from "react";
/**
* Shell media state (theme + sound) — mirrors the original useShellMedia /
* useThemeMode contract: theme ∈ {light, dark, system}, persisted to
* localStorage; soundEnabled persisted likewise (original keys
* "hq-theme" / "hq-sound"; namespaced here). The THEME cycle is
* light → dark → system, keyboard [L]/[D]/[A] shortcuts live in the
* header component (original ASCIIThemeToggle behavior).
*/
export type ThemeSetting = "light" | "dark" | "system";
const THEME_KEY = "vh-theme";
const SOUND_KEY = "vh-sound";
function readStored(key: string): string | null {
try {
return window.localStorage.getItem(key);
} catch {
return null;
}
}
export function useShellMedia() {
const [theme, setThemeState] = useState<ThemeSetting>("light");
const [soundEnabled, setSoundEnabledState] = useState(false);
useEffect(() => {
const t = readStored(THEME_KEY);
if (t === "light" || t === "dark" || t === "system") setThemeState(t);
setSoundEnabledState(readStored(SOUND_KEY) === "1");
}, []);
// Theme is light-only in this port: system/dark resolve to light.
useEffect(() => {
document.documentElement.dataset.themeSetting = theme;
}, [theme]);
const setTheme = useCallback((next: ThemeSetting) => {
setThemeState(next);
try {
window.localStorage.setItem(THEME_KEY, next);
} catch {}
}, []);
const setSoundEnabled = useCallback((next: boolean) => {
setSoundEnabledState(next);
try {
window.localStorage.setItem(SOUND_KEY, next ? "1" : "0");
} catch {}
}, []);
return { theme, setTheme, soundEnabled, setSoundEnabled };
}
export type ShellMedia = ReturnType<typeof useShellMedia>;
let contextValue: ShellMedia | null = null;
/** Module-singleton variant (no provider tree needed for this port). */
export function useShellMediaSingleton(): ShellMedia {
const own = useShellMedia();
return contextValue ?? own;
}
+58
View File
@@ -0,0 +1,58 @@
"use client";
import { useEffect, useRef } from "react";
/**
* Background music loader — port of the original effect (chunk
* 2689132c4e070b68.js): fetch /bgm.mp3 once, create a looping Audio at
* volume 0.35, play/pause with `enabled`. Keeps the same abort/cleanup
* semantics (revoke object URL on unmount).
*/
export function useBgm(enabled: boolean) {
const audioRef = useRef<HTMLAudioElement | null>(null);
const readyRef = useRef(false);
useEffect(() => {
let cancelled = false;
let objectUrl: string | null = null;
let audio: HTMLAudioElement | null = null;
readyRef.current = false;
fetch("/bgm.mp3")
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.blob();
})
.then((blob) => {
if (cancelled) return;
objectUrl = URL.createObjectURL(blob);
audio = new Audio(objectUrl);
audio.loop = true;
audio.volume = 0.35;
audioRef.current = audio;
readyRef.current = true;
if (enabled) void audio.play().catch(() => {});
})
.catch((err) => {
if (!cancelled) console.warn("Failed to load BGM:", err);
});
return () => {
cancelled = true;
if (audioRef.current === audio) audioRef.current = null;
audio?.pause();
audio?.removeAttribute("src");
audio?.load();
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
// Load once on mount (original: deps [enabled-guarded flag]).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
const audio = audioRef.current;
if (!audio || !readyRef.current) return;
if (enabled) void audio.play().catch(() => {});
else audio.pause();
}, [enabled]);
}
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 988 KiB

After

Width:  |  Height:  |  Size: 82 KiB