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
+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]);
}