播放器更新

This commit is contained in:
YGC
2026-07-14 18:43:40 +08:00
parent e2e7cf85b1
commit a57b66189c
43 changed files with 5908 additions and 529 deletions
+1
View File
@@ -1,5 +1,6 @@
node_modules/
.next/
.next-*/
out/
.DS_Store
*.log
+1
View File
@@ -17,6 +17,7 @@ const eslintConfig = defineConfig([
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
".next-*/**",
"out/**",
"build/**",
"next-env.d.ts",
+9
View File
@@ -8,9 +8,18 @@ const serverApiBaseUrl = (
).replace(/\/+$/, "");
const nextConfig: NextConfig = {
distDir: process.env.NEXT_DIST_DIR || ".next",
output: "standalone",
async rewrites() {
return [
{
source: "/api/music/:path*",
destination: "/api/music/:path*",
},
{
source: "/api/music",
destination: "/api/music",
},
{
source: "/api/:path*",
destination: `${serverApiBaseUrl}/:path*`,
+7
View File
@@ -19,6 +19,7 @@
"lucide-react": "^1.21.0",
"next": "16.2.9",
"ogl": "^1.0.11",
"opencc-js": "^1.4.0",
"react": "19.2.4",
"react-dom": "19.2.4"
},
@@ -5683,6 +5684,12 @@
"integrity": "sha512-kUpC154AFfxi16pmZUK4jk3J+8zxwTWGPo03EoYA8QPbzikHoaC82n6pNTbd+oEaJonaE8aPWBlX7ad9zrqLsA==",
"license": "Unlicense"
},
"node_modules/opencc-js": {
"version": "1.4.0",
"resolved": "https://registry.npmmirror.com/opencc-js/-/opencc-js-1.4.0.tgz",
"integrity": "sha512-SEb4huI5+lT4CFPA4sgs+NAOOgpcmdHZ+vYxhRLR1bQWIt6VRwpFPjWgTJAWAg1MviDcXTBe5zVoUOVxVxNK8w==",
"license": "MIT AND Apache-2.0"
},
"node_modules/optionator": {
"version": "0.9.4",
"resolved": "https://registry.npmmirror.com/optionator/-/optionator-0.9.4.tgz",
+2 -1
View File
@@ -3,7 +3,7 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"dev": "next dev --turbo",
"build": "next build",
"start": "next start",
"lint": "eslint"
@@ -20,6 +20,7 @@
"lucide-react": "^1.21.0",
"next": "16.2.9",
"ogl": "^1.0.11",
"opencc-js": "^1.4.0",
"react": "19.2.4",
"react-dom": "19.2.4"
},
+30 -2
View File
@@ -1,10 +1,38 @@
import request, { getServerApiURL } from './request'
import { cache } from 'react'
export interface PublicConfigItem {
configKey: string
configValue: string
}
export function getPublicConfig() {
return request.get('/config/public')
}
export async function fetchPublicConfigForServer(init?: Parameters<typeof fetch>[1]) {
const response = await fetch(getServerApiURL('/config/public'), init)
return response.json()
try {
const response = await fetch(getServerApiURL('/config/public'), {
...init,
// 容错超时防刷屏
signal: AbortSignal.timeout(3000)
})
if (!response.ok) {
return { code: response.status, data: [] }
}
return await response.json()
} catch {
// 静默兜底,避免打印庞大的 Socket 异常日志
return { code: 500, data: [] }
}
}
export const getPublicConfigSnapshot = cache(async (): Promise<PublicConfigItem[]> => {
const payload = await fetchPublicConfigForServer({ next: { revalidate: 10 } })
if (payload.code !== 200 || !Array.isArray(payload.data)) return []
return payload.data.filter((item: unknown): item is PublicConfigItem => {
if (!item || typeof item !== 'object') return false
const candidate = item as Partial<PublicConfigItem>
return typeof candidate.configKey === 'string' && typeof candidate.configValue === 'string'
})
})
+272
View File
@@ -0,0 +1,272 @@
import axios, { AxiosError } from 'axios';
import {
ApiSearchResult,
MusicApiErrorPayload,
MusicSource,
TrackDetail,
} from '@/interface/music';
const MUSIC_API_URL = '/api/music';
export class MusicApiError extends Error {
code: MusicApiErrorPayload['code'];
status?: number;
constructor(message: string, code: MusicApiErrorPayload['code'] = 'UPSTREAM_UNAVAILABLE', status?: number) {
super(message);
this.name = 'MusicApiError';
this.code = code;
this.status = status;
}
}
function normalizeMusicError(error: unknown) {
if (error instanceof MusicApiError) return error;
if (error instanceof AxiosError) {
const payload = error.response?.data as Partial<MusicApiErrorPayload> | undefined;
return new MusicApiError(
payload?.message || '音乐服务暂时不可用',
payload?.code || 'UPSTREAM_UNAVAILABLE',
error.response?.status,
);
}
return new MusicApiError(error instanceof Error ? error.message : '音乐服务暂时不可用');
}
export function buildMusicStreamUrl(id: string, source: MusicSource = 'netease', name?: string, br = 320000) {
const params = new URLSearchParams({ types: 'stream', source, id, br: String(br) });
if (name) params.set('name', name);
return `${MUSIC_API_URL}?${params.toString()}`;
}
import { toSimplifiedChinese } from '@/lib/chinese';
/**
* 搜索音乐列表
* @param name 搜索关键词(歌曲/歌手/专辑)
* @param source 音乐源 (默认 netease)
* @param count 返回数量
*/
export async function searchMusic(
name: string,
source: MusicSource = 'netease',
count = 12
): Promise<ApiSearchResult[]> {
if (!name.trim()) return [];
try {
const res = await axios.get<ApiSearchResult[]>(MUSIC_API_URL, {
params: {
types: 'search',
source,
name: name.trim(),
count,
pages: 1,
},
timeout: 8000,
});
const items = Array.isArray(res.data) ? res.data : [];
return items.map((item) => ({
...item,
name: toSimplifiedChinese(item.name || ''),
artist: Array.isArray(item.artist)
? item.artist.map((a) => toSimplifiedChinese(a))
: toSimplifiedChinese(item.artist || ''),
album: toSimplifiedChinese(item.album || ''),
}));
} catch (error) {
throw normalizeMusicError(error);
}
}
/**
* 获取音频真实播放 URL (320k 优先)
*/
export async function fetchMusicUrl(
id: string,
source: MusicSource = 'netease',
br = 320000
): Promise<string> {
try {
const res = await axios.get(MUSIC_API_URL, {
params: {
types: 'url',
source,
id,
br,
},
timeout: 8000,
});
return res.data?.url || '';
} catch (error) {
throw normalizeMusicError(error);
}
}
/**
* 获取专辑封面 URL
*/
export async function fetchMusicPic(
picId: string,
source: MusicSource = 'netease',
size = 300
): Promise<string> {
if (!picId) return '';
if (picId.startsWith('http://') || picId.startsWith('https://')) {
return picId;
}
try {
const res = await axios.get(MUSIC_API_URL, {
params: {
types: 'pic',
source,
id: picId,
size,
},
timeout: 6000,
});
return res.data?.url || '';
} catch (error) {
throw normalizeMusicError(error);
}
}
/**
* 获取 LRC 歌词
*/
export async function fetchMusicLyric(
lyricId: string,
source: MusicSource = 'netease',
name?: string
): Promise<{ lyric: string; tlyric: string }> {
if (!lyricId && !name) return { lyric: '', tlyric: '' };
try {
const res = await axios.get(MUSIC_API_URL, {
params: {
types: 'lyric',
source,
id: lyricId || name,
...(name ? { name } : {}),
},
timeout: 6000,
});
return {
lyric: toSimplifiedChinese(res.data?.lyric || ''),
tlyric: toSimplifiedChinese(res.data?.tlyric || ''),
};
} catch (error) {
throw normalizeMusicError(error);
}
}
/**
* 懒加载解析:当用户点击播放搜索出来的曲目时,按需请求音频 URL 和 封面
*/
export async function resolveTrackDetails(searchResult: ApiSearchResult): Promise<TrackDetail> {
const rawArtist = Array.isArray(searchResult.artist)
? searchResult.artist.join(' / ')
: searchResult.artist || '未知歌手';
const formattedArtist = toSimplifiedChinese(rawArtist);
const [coverResult, lyricResult] = await Promise.allSettled([
fetchMusicPic(searchResult.pic_id, searchResult.source),
fetchMusicLyric(searchResult.lyric_id || searchResult.id, searchResult.source, searchResult.name),
]);
let cover = coverResult.status === 'fulfilled' ? coverResult.value : '';
if (!cover && (searchResult.pic_id?.startsWith('http://') || searchResult.pic_id?.startsWith('https://'))) {
cover = searchResult.pic_id;
}
const lyrics = lyricResult.status === 'fulfilled'
? lyricResult.value
: { lyric: '', tlyric: '' };
return {
id: searchResult.id,
title: toSimplifiedChinese(searchResult.name),
artist: formattedArtist,
album: toSimplifiedChinese(searchResult.album || '单曲'),
src: buildMusicStreamUrl(searchResult.url_id || searchResult.id, searchResult.source, searchResult.name),
cover,
picId: searchResult.pic_id,
urlId: searchResult.url_id || searchResult.id,
lyricId: searchResult.lyric_id || searchResult.id,
lyric: lyrics.lyric,
tlyric: lyrics.tlyric,
source: searchResult.source,
};
}
export interface ParsedPlaylist {
source: MusicSource;
id: string;
}
/**
* 智能解析网易云音乐歌单分享链接或纯数字ID
*/
export function parsePlaylistUrl(input: string, defaultSource: MusicSource = 'netease'): ParsedPlaylist | null {
const text = input.trim();
if (!text) return null;
// 网易云音乐 (netease)
if (text.includes('163.com') || text.includes('163cn.tv')) {
const idMatch = text.match(/[?&]id=(\d+)/);
if (idMatch) return { source: 'netease', id: idMatch[1] };
}
// 纯数字/字母 ID,默认设为 netease
if (/^[a-zA-Z0-9_]+$/.test(text)) {
return { source: defaultSource, id: text };
}
return null;
}
/**
* 歌单导入:1 次请求拉取全歌单元数据,每首曲目的播放流与资源采用懒加载机制
*/
export async function fetchPlaylist(
id: string,
source: MusicSource = 'netease'
): Promise<TrackDetail[]> {
try {
const res = await axios.get<ApiSearchResult[]>(MUSIC_API_URL, {
params: {
types: 'playlist',
source,
id,
},
timeout: 12000,
});
const items = Array.isArray(res.data) ? res.data : [];
if (items.length === 0) {
throw new MusicApiError('未在歌单中找到有效曲目,请检查歌单ID或公开权限', 'TRACK_UNAVAILABLE');
}
return items.map((item) => {
const rawArtist = Array.isArray(item.artist)
? item.artist.join(' / ')
: item.artist || '未知歌手';
const formattedArtist = toSimplifiedChinese(rawArtist);
return {
id: item.id,
title: toSimplifiedChinese(item.name || '未知曲目'),
artist: formattedArtist,
album: toSimplifiedChinese(item.album || '歌单导入'),
src: buildMusicStreamUrl(item.url_id || item.id, item.source || source, item.name),
cover: '',
picId: item.pic_id,
urlId: item.url_id || item.id,
lyricId: item.lyric_id || item.id,
lyric: '',
tlyric: '',
source: item.source || source,
};
});
} catch (error) {
throw normalizeMusicError(error);
}
}
+395
View File
@@ -0,0 +1,395 @@
import { isIP } from 'node:net';
import { NextResponse } from 'next/server';
import type { MusicApiErrorCode, MusicSource } from '@/interface/music';
const MUSIC_API_URL = 'https://music-api.gdstudio.xyz/api.php';
const ALLOWED_SOURCES = new Set<MusicSource>(['netease', 'tencent', 'kugou', 'kuwo', 'bilibili', 'joox']);
const ALLOWED_TYPES = new Set(['search', 'url', 'pic', 'lyric', 'stream', 'playlist']);
function errorResponse(code: MusicApiErrorCode, message: string, status: number) {
return NextResponse.json({ code, message }, { status });
}
function isPrivateIpv4(hostname: string) {
const parts = hostname.split('.').map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part))) return false;
return parts[0] === 10 || parts[0] === 127 ||
(parts[0] === 169 && parts[1] === 254) ||
(parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
(parts[0] === 192 && parts[1] === 168);
}
function isSafeStreamUrl(value: string) {
try {
const url = new URL(value);
const hostname = url.hostname.toLowerCase();
if ((url.protocol !== 'https:' && url.protocol !== 'http:') || hostname === 'localhost' || hostname.endsWith('.local')) return false;
if (isPrivateIpv4(hostname)) return false;
if (isIP(hostname) === 6 && (hostname === '::1' || hostname.startsWith('fc') || hostname.startsWith('fd'))) return false;
return true;
} catch {
return false;
}
}
async function requestMusicApi(
requestType: string,
params: { source: MusicSource; name?: string; id?: string; br?: string; size?: string; count?: string; pages?: string },
) {
const targetUrl = new URL(MUSIC_API_URL);
targetUrl.searchParams.set('types', requestType);
targetUrl.searchParams.set('source', params.source);
if (params.name) targetUrl.searchParams.set('name', params.name);
if (params.id) targetUrl.searchParams.set('id', params.id);
if (params.br) targetUrl.searchParams.set('br', params.br);
if (params.size) targetUrl.searchParams.set('size', params.size);
if (params.count) targetUrl.searchParams.set('count', params.count);
if (params.pages) targetUrl.searchParams.set('pages', params.pages);
const response = await fetch(targetUrl, {
headers: {
Accept: 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/122 Safari/537.36',
},
cache: requestType === 'url' ? 'no-store' : undefined,
next: requestType === 'url' ? undefined : { revalidate: 60 },
signal: AbortSignal.timeout(8_000),
});
if (!response.ok) throw new Error(`第三方接口响应失败 (${response.status})`);
const text = await response.text();
if (!text.trim()) throw new Error('第三方接口返回无内容');
let data: unknown;
try {
data = JSON.parse(text);
} catch {
throw new Error('解析第三方接口响应失败');
}
if (data && typeof data === 'object' && !Array.isArray(data)) {
const obj = data as Record<string, unknown>;
if (obj.error && typeof obj.error === 'string' && obj.error.length > 0) throw new Error(obj.error);
if (obj.message && typeof obj.code === 'number' && obj.code !== 200 && obj.code !== 0) {
throw new Error(String(obj.message));
}
}
return data;
}
/**
* 智能多源音频 URL 降级解析
* 1. 尝试当前源不同码率 (320k -> 192k -> 128k)
* 2. 若缺少 name,根据 id 尝试查找歌名
* 3. 跨源(netease -> kuwo -> joox -> bilibili)同名匹配多码率可播放音轨
*/
async function resolveAudioUrlWithFallback(source: MusicSource, id: string, name?: string, br = '320000'): Promise<string> {
const bitrates = [br, '320000', '192000', '128000'].filter((v, i, a) => a.indexOf(v) === i);
// 1. 尝试当前源的多码率
for (const rate of bitrates) {
try {
const res = (await requestMusicApi('url', { source, id, br: rate })) as { url?: string };
if (res?.url && isSafeStreamUrl(res.url)) return res.url;
} catch {
// continue
}
}
// 2. 如果缺少 name,尝试通过 search 反查歌名
let trackName = name?.trim();
if (!trackName) {
try {
const searchRes = (await requestMusicApi('search', { source, name: id, count: '1' })) as Array<{ name?: string }>;
if (Array.isArray(searchRes) && searchRes[0]?.name) {
trackName = searchRes[0].name;
}
} catch {
// ignore
}
}
// 3. 跨源降级匹配同名音轨 (只使用 netease, kuwo, bilibili,绝不使用会偷换音轨的 joox)
if (trackName) {
const fallbackSources: MusicSource[] = (['netease', 'kuwo', 'bilibili'] as MusicSource[]).filter((s) => s !== source);
for (const fbSource of fallbackSources) {
try {
const searchRes = (await requestMusicApi('search', { source: fbSource, name: trackName, count: '3' })) as Array<{ id: string; name?: string }>;
if (Array.isArray(searchRes)) {
for (const item of searchRes) {
// 确保匹配到的歌曲名称包含要找的歌名关键字
if (item.name && !item.name.toLowerCase().includes(trackName.toLowerCase()) && !trackName.toLowerCase().includes(item.name.toLowerCase())) {
continue;
}
for (const rate of ['320000', '128000']) {
try {
const fbUrlRes = (await requestMusicApi('url', { source: fbSource, id: item.id, br: rate })) as { url?: string };
if (fbUrlRes?.url && isSafeStreamUrl(fbUrlRes.url)) {
return fbUrlRes.url;
}
} catch {
continue;
}
}
}
}
} catch {
continue;
}
}
}
return '';
}
import { toSimplifiedChinese } from '@/lib/chinese';
/**
* 智能多源歌词降级解析
* 当指定源(如 joox)无歌词时,自动尝试其他源(netease -> kuwo)检索同名曲目获取歌词
*/
async function resolveLyricWithFallback(source: MusicSource, id: string, name?: string): Promise<{ lyric: string; tlyric: string; from: string }> {
try {
const res = (await requestMusicApi('lyric', { source, id })) as { lyric?: string; tlyric?: string; from?: string };
if (res?.lyric && res.lyric.trim().length > 0) {
return {
lyric: toSimplifiedChinese(res.lyric),
tlyric: toSimplifiedChinese(res.tlyric || ''),
from: res.from || 'music.gdstudio.xyz',
};
}
} catch {
// continue to fallback
}
if (name) {
const fallbackSources: MusicSource[] = (['netease', 'kuwo', 'bilibili'] as MusicSource[]).filter((s) => s !== source);
for (const fbSource of fallbackSources) {
try {
const searchRes = (await requestMusicApi('search', { source: fbSource, name, count: '1' })) as Array<{ lyric_id?: string; id: string }>;
if (Array.isArray(searchRes) && searchRes.length > 0) {
const fbLyricRes = (await requestMusicApi('lyric', { source: fbSource, id: searchRes[0].lyric_id || searchRes[0].id })) as { lyric?: string; tlyric?: string; from?: string };
if (fbLyricRes?.lyric && fbLyricRes.lyric.trim().length > 0) {
return {
lyric: toSimplifiedChinese(fbLyricRes.lyric),
tlyric: toSimplifiedChinese(fbLyricRes.tlyric || ''),
from: fbLyricRes.from || 'music.gdstudio.xyz',
};
}
}
} catch {
continue;
}
}
}
return { lyric: '', tlyric: '', from: 'music.gdstudio.xyz' };
}
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const requestType = searchParams.get('types') || 'search';
const source = (searchParams.get('source') || 'netease') as MusicSource;
const name = searchParams.get('name')?.trim() || '';
const id = searchParams.get('id')?.trim() || '';
const br = searchParams.get('br') || '320000';
const size = searchParams.get('size') || '300';
const count = searchParams.get('count') || '12';
const pages = searchParams.get('pages') || '1';
if (!ALLOWED_TYPES.has(requestType)) return errorResponse('INVALID_REQUEST', '不支持的音乐请求类型', 400);
if (!ALLOWED_SOURCES.has(source)) return errorResponse('INVALID_REQUEST', '不支持的音乐来源', 400);
if (requestType === 'search' && !name) return errorResponse('INVALID_REQUEST', '搜索关键词不能为空', 400);
if (requestType !== 'search' && !id) return errorResponse('INVALID_REQUEST', '曲目标识不能为空', 400);
const params = { source, name, id, br, size, count, pages };
try {
if (requestType === 'search') {
let data = await requestMusicApi('search', params);
if (Array.isArray(data) && data.length === 0) {
const fallbackSource: MusicSource = source === 'netease' ? 'kuwo' : 'netease';
data = await requestMusicApi('search', { ...params, source: fallbackSource });
}
return NextResponse.json(Array.isArray(data) ? data : []);
}
if (requestType === 'lyric') {
const lyricData = await resolveLyricWithFallback(source, id, name);
return NextResponse.json(lyricData);
}
if (requestType === 'stream') {
const audioUrl = await resolveAudioUrlWithFallback(source, id, name, br);
if (!audioUrl) {
return errorResponse('TRACK_UNAVAILABLE', '全网暂无可用的音频播放路径', 404);
}
return NextResponse.redirect(audioUrl, { status: 302 });
}
if (requestType === 'playlist') {
if (source === 'tencent') {
const dataPayload = {
req_0: {
module: 'music.srfDissInfo.aiDissInfo',
method: 'uniform_get_Dissinfo',
param: { disstid: Number(id) || id, enc_host_uin: '' },
},
};
const qqUrl = `https://u.y.qq.com/cgi-bin/musicu.fcg?g_tk=5381&format=json&data=${encodeURIComponent(JSON.stringify(dataPayload))}`;
const response = await fetch(qqUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
Referer: 'https://y.qq.com/',
},
signal: AbortSignal.timeout(10_000),
});
if (!response.ok) throw new Error(`QQ音乐接口响应失败 (${response.status})`);
const json = await response.json();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const songlist = json?.req_0?.data?.songlist || [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const items = songlist.map((song: any) => ({
id: song.mid || String(song.id),
name: song.name || song.title || '未知曲目',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
artist: Array.isArray(song.singer) ? song.singer.map((s: any) => s.name) : (song.singer?.name || '未知歌手'),
album: song.album?.name || 'QQ音乐歌单',
pic_id: song.album?.mid ? `https://y.gtimg.cn/music/photo_new/T002R300x300M000${song.album.mid}.jpg` : (song.mid || String(song.id)),
url_id: song.name,
lyric_id: song.mid || String(song.id),
source: 'tencent',
}));
return NextResponse.json(items);
}
if (source === 'kugou') {
const kgUrl = `https://mobilecdnbj.kugou.com/api/v3/special/song?specialid=${encodeURIComponent(id)}&page=1&pagesize=100`;
const response = await fetch(kgUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
},
signal: AbortSignal.timeout(10_000),
});
if (!response.ok) throw new Error(`酷狗音乐接口响应失败 (${response.status})`);
const json = await response.json();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const songlist = json?.data?.info || [];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const items = songlist.map((item: any) => {
const parts = (item.filename || '').split(' - ');
const artist = parts.length > 1 ? parts[0].trim() : '未知歌手';
const name = parts.length > 1 ? parts.slice(1).join(' - ').trim() : (item.filename || '未知曲目');
return {
id: item.hash || String(item.audio_id),
name,
artist,
album: '酷狗歌单',
pic_id: item.hash,
url_id: name,
lyric_id: item.hash,
source: 'kugou',
};
});
return NextResponse.json(items);
}
if (source === 'netease') {
try {
const neteaseUrl = `https://music.163.com/api/v1/playlist/detail?id=${encodeURIComponent(id)}`;
const response = await fetch(neteaseUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
Referer: 'https://music.163.com/',
},
signal: AbortSignal.timeout(10_000),
});
if (response.ok) {
const json = await response.json();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const playlistData = json?.playlist || json?.result;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const trackIds = (playlistData?.trackIds || []).map((t: any) => t.id).filter(Boolean);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let rawTracks: any[] = [];
if (trackIds.length > 0) {
const chunkSize = 500;
for (let i = 0; i < Math.min(trackIds.length, 1000); i += chunkSize) {
const chunkIds = trackIds.slice(i, i + chunkSize);
const cParam = JSON.stringify(chunkIds.map((tid: number | string) => ({ id: tid })));
const detailUrl = `https://music.163.com/api/v3/song/detail?c=${encodeURIComponent(cParam)}`;
const detailRes = await fetch(detailUrl, {
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
Referer: 'https://music.163.com/',
},
signal: AbortSignal.timeout(10_000),
});
if (detailRes.ok) {
const detailJson = await detailRes.json();
if (Array.isArray(detailJson?.songs)) {
rawTracks.push(...detailJson.songs);
}
}
}
}
if (rawTracks.length === 0) {
rawTracks = playlistData?.tracks || [];
}
if (Array.isArray(rawTracks) && rawTracks.length > 0) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const items = rawTracks.map((track: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const artistList = track.ar || track.artists || [];
const artist = Array.isArray(artistList)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
? artistList.map((a: any) => a.name).join(' / ')
: (artistList.name || '未知歌手');
const album = track.al?.name || track.album?.name || '网易云歌单';
const picId = track.al?.picUrl || track.album?.picUrl || track.al?.pic_str || track.al?.pic || track.album?.picId || String(track.id);
return {
id: String(track.id),
name: track.name || '未知曲目',
artist,
album,
pic_id: String(picId),
url_id: String(track.id),
lyric_id: String(track.id),
source: 'netease',
};
});
return NextResponse.json(items);
}
}
} catch {
// fallback to requestMusicApi
}
}
const data = await requestMusicApi('playlist', params);
return NextResponse.json(Array.isArray(data) ? data : []);
}
const data = await requestMusicApi(requestType, params);
if (requestType === 'url' && !(data as { url?: string })?.url) {
const audioUrl = await resolveAudioUrlWithFallback(source, id, name, br);
if (audioUrl) {
return NextResponse.json({ url: audioUrl });
}
return errorResponse('TRACK_UNAVAILABLE', '全网暂无可用的音频播放路径', 404);
}
return NextResponse.json(data);
} catch (error) {
const message = error instanceof Error
? (error.name === 'TimeoutError' ? '音乐服务响应超时' : error.message)
: '音乐服务暂时不可用';
return errorResponse('UPSTREAM_UNAVAILABLE', message, 502);
}
}
+15
View File
@@ -388,6 +388,8 @@ html.lenis, html.lenis body {
transition here so the scroll-scrubbed cross-dissolve is not double-eased. */
}
.footer-peekers-floating-image {
position: relative;
z-index: 1;
@@ -580,4 +582,17 @@ nextjs-portal, #__next-prerender-indicator {
display: none !important;
}
/* 黑胶唱片 360 度平滑旋转动画 */
@keyframes spin-linear {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.animate-spin-slow {
animation: spin-linear 20s linear infinite;
}
+16 -23
View File
@@ -3,13 +3,13 @@ import { Inter, Cormorant_Garamond, Playfair_Display, Space_Grotesk, Space_Mono,
import "./globals.css";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import FloatingFooterPeekers from "@/components/ui/FloatingFooterPeekers";
import SmoothScroll from "@/components/ui/SmoothScroll";
import StyleConsole from "@/components/ui/StyleConsole";
import BackToTop from "@/components/ui/BackToTop";
import TapeStation from "@/components/ui/TapeStation";
import ArchivePlayer from "@/components/ui/ArchivePlayer";
import ThemeApplier from "@/components/ui/ThemeApplier";
import { fetchPublicConfigForServer } from "@/api/config";
import { getPublicConfigSnapshot } from "@/api/config";
import { SysConfigProvider } from "@/hooks/useSysConfig";
const inter = Inter({
variable: "--font-inter",
@@ -65,21 +65,13 @@ const maShanZheng = Ma_Shan_Zheng({
export async function generateMetadata(): Promise<Metadata> {
let title = "春风不解别离 | 个人生活档案馆";
let faviconUrl = "/icon.png";
try {
const data = await fetchPublicConfigForServer({ next: { revalidate: 10 } });
if (data.code === 200 && Array.isArray(data.data)) {
const titleItem = data.data.find((c: any) => c.configKey === "site.title.default");
if (titleItem?.configValue) {
title = titleItem.configValue;
}
const favItem = data.data.find((c: any) => c.configKey === "site.favicon.url");
if (favItem?.configValue) {
faviconUrl = favItem.configValue;
}
const configs = await getPublicConfigSnapshot();
const titleItem = configs.find((config) => config.configKey === "site.title.default");
if (titleItem?.configValue) title = titleItem.configValue;
const faviconItem = configs.find((config) => config.configKey === "site.favicon.url");
if (faviconItem?.configValue) {
faviconUrl = faviconItem.configValue;
}
} catch (e) {
console.warn("Failed to fetch root metadata:", e);
}
return {
title,
@@ -90,17 +82,20 @@ export async function generateMetadata(): Promise<Metadata> {
};
}
export default function RootLayout({
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const configs = await getPublicConfigSnapshot();
return (
<html
lang="zh"
className={`${inter.variable} ${cormorant.variable} ${playfair.variable} ${spaceGrotesk.variable} ${spaceMono.variable} ${jost.variable} ${notoSerifSC.variable} ${maShanZheng.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col text-charcoal bg-transparent">
<SysConfigProvider initialConfigs={configs}>
<ThemeApplier />
{/* 1. 全局底色层 (z-0) */}
<div className="fixed inset-0 z-0 bg-cream pointer-events-none" />
@@ -129,17 +124,15 @@ export default function RootLayout({
</SmoothScroll>
</div>
{/* 5. 全站底部趴窗装饰,接近 footer 时停靠到 footer 顶部 */}
<FloatingFooterPeekers />
{/* 6. 悬浮的视觉控制中心 */}
<StyleConsole />
{/* 7. 全局回到顶部按钮 */}
<BackToTop />
{/* 8. 治愈系磁带播放器 */}
<TapeStation />
{/* 8. 沉浸式音乐播放器 */}
<ArchivePlayer />
</SysConfigProvider>
</body>
</html>
);
-1
View File
@@ -37,7 +37,6 @@ export default function LetterPage() {
content: item.content || "",
images: item.images || ""
}));
console.log("[岁月信箱] 动态加载的未来信札列表:", list);
setLetters(list);
}
} catch (err) {
+11 -20
View File
@@ -3,7 +3,8 @@ import { galleryData } from "@/data/gallery";
import { writingData, Post } from "@/data/writing";
import { getBlogsList } from "@/api/blogs";
import { getGalleryList } from "@/api/gallery";
import { getPublicConfig } from "@/api/config";
import { getPublicConfigSnapshot } from "@/api/config";
import { reportUnexpectedFallback } from "@/lib/fallback-log";
async function getFeaturedPosts(): Promise<Post[]> {
try {
@@ -23,7 +24,7 @@ async function getFeaturedPosts(): Promise<Post[]> {
})).slice(0, 3);
}
} catch (err) {
console.warn("Home page: API unavailable, using local writingData static fallback.", err);
reportUnexpectedFallback("home-posts", "首页文章使用本地数据", err);
}
return writingData.slice(0, 3);
}
@@ -48,33 +49,23 @@ async function getFeaturedPhotos(): Promise<any[]> {
})).slice(0, 4);
}
} catch (err) {
console.warn("Home page gallery: API unavailable, using local galleryData static fallback.", err);
reportUnexpectedFallback("home-gallery", "首页相册使用本地数据", err);
}
return galleryData.slice(0, 4);
}
async function getPublicConfigs(): Promise<Record<string, string>> {
try {
const res = await getPublicConfig();
const data = res.data;
if (data && data.code === 200 && Array.isArray(data.data)) {
const configMap: Record<string, string> = {};
data.data.forEach((item: any) => {
configMap[item.configKey] = item.configValue;
});
return configMap;
}
} catch (err) {
console.warn("Home page configs: API unavailable, using empty config fallback.", err);
}
return {};
const configs = await getPublicConfigSnapshot();
return Object.fromEntries(configs.map((item) => [item.configKey, item.configValue]));
}
export default async function HomePage() {
const featuredPosts = await getFeaturedPosts();
const featuredPhotos = await getFeaturedPhotos();
const configs = await getPublicConfigs();
const [featuredPosts, featuredPhotos, configs] = await Promise.all([
getFeaturedPosts(),
getFeaturedPhotos(),
getPublicConfigs(),
]);
return (
<HomePageClient
featuredPosts={featuredPosts}
+7 -1
View File
@@ -1,5 +1,6 @@
"use client";
import { useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { ArrowDown, Camera, Feather, PenLine } from "lucide-react";
@@ -24,17 +25,21 @@ export default function HomeHero({
welcomeSubtitle,
logoText
}: HomeHeroProps) {
const [mediaFailed, setMediaFailed] = useState(false);
return (
<section className="relative isolate min-h-[100dvh] overflow-hidden bg-charcoal px-4 pt-24 text-cream sm:px-6 lg:px-8">
<div className="absolute inset-0">
{heroBgUrl ? (
{heroBgUrl && !mediaFailed ? (
heroBgUrl.match(/\.(mp4|webm|ogg|mov|m4v)($|\?)/i) ? (
<video
src={heroBgUrl}
poster="/bg-image.png"
autoPlay
loop
muted
playsInline
onError={() => setMediaFailed(true)}
className="absolute inset-0 h-full w-full object-cover object-[62%_center] brightness-[0.82] saturate-[1.14] dark:brightness-[0.7]"
/>
) : (
@@ -44,6 +49,7 @@ export default function HomeHero({
fill
priority
sizes="100vw"
onError={() => setMediaFailed(true)}
className="object-cover object-[62%_center] brightness-[0.82] saturate-[1.14] dark:brightness-[0.7]"
/>
)
-19
View File
@@ -50,25 +50,6 @@ export default function LetterModal({
const isPast = letter ? parseTargetDate(letter.targetDate).getTime() < new Date().getTime() : false;
const canRead = isUnlocked || isPast;
useEffect(() => {
if (letter) {
console.log(
"[岁月信箱] 弹窗属性 - ID:",
letter.id,
"canRead:",
canRead,
"isPast:",
isPast,
"isUnlocked:",
isUnlocked,
"bypassCode:",
letter.bypassCode,
"content字数:",
letter.content?.length
);
}
}, [letter, canRead, isPast, isUnlocked]);
// 根据信件 ID 匹配回忆照片堆
const is2027 = letter ? letter.id.includes("2027") : false;
const customImages = letter?.images ? letter.images.split(",").map(s => s.trim()).filter(Boolean) : [];
+85
View File
@@ -0,0 +1,85 @@
@keyframes listFadeIn {
from {
opacity: 0;
transform: translate3d(0, 10px, 0) scale(0.98);
}
to {
opacity: 1;
transform: translate3d(0, 0, 0) scale(1);
}
}
.scroll-list-container {
position: relative;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
overflow: hidden;
contain: layout style paint;
}
.scroll-list {
flex-grow: 1;
min-height: 0;
overflow-y: auto;
padding: 4px 2px;
-webkit-overflow-scrolling: touch;
will-change: scroll-position;
transform: translateZ(0);
}
.scroll-list::-webkit-scrollbar {
width: 6px;
}
.scroll-list::-webkit-scrollbar-track {
background: transparent;
}
.scroll-list::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.18);
border-radius: 9999px;
}
.no-scrollbar::-webkit-scrollbar {
display: none;
}
.no-scrollbar {
-ms-overflow-style: none;
scrollbar-width: none;
}
.animated-item-wrapper {
margin-bottom: 0.5rem;
cursor: pointer;
will-change: opacity, transform;
transform: translateZ(0);
backface-visibility: hidden;
animation: listFadeIn 0.22s cubic-bezier(0.16, 1, 0.3, 1) forwards;
}
.top-gradient {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 32px;
background: linear-gradient(to bottom, var(--bg-dark-color, #120F17), transparent);
pointer-events: none;
z-index: 20;
transition: opacity 0.2s ease;
}
.bottom-gradient {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 40px;
background: linear-gradient(to top, var(--bg-dark-color, #120F17), transparent);
pointer-events: none;
z-index: 20;
transition: opacity 0.2s ease;
}
+137
View File
@@ -0,0 +1,137 @@
"use client";
import React, { useRef, useState, useCallback, memo } from "react";
import "./AnimatedList.css";
export interface AnimatedItemProps {
children: React.ReactNode;
index: number;
onMouseEnter?: () => void;
onClick?: () => void;
}
export const AnimatedItem: React.FC<AnimatedItemProps> = memo(({
children,
index,
onMouseEnter,
onClick,
}) => {
// 只在前 15 个元素计算交错入场动画延迟,之后的瞬间展示,避免滚动时滞后
const animationDelay = index < 15 ? `${index * 0.025}s` : "0s";
return (
<div
data-index={index}
onMouseEnter={onMouseEnter}
onClick={onClick}
className="animated-item-wrapper"
style={{ animationDelay }}
>
{children}
</div>
);
});
AnimatedItem.displayName = "AnimatedItem";
export interface AnimatedListProps<T = any> {
items?: T[];
onItemSelect?: (item: T, index: number) => void;
showGradients?: boolean;
enableArrowNavigation?: boolean;
className?: string;
itemClassName?: string;
displayScrollbar?: boolean;
initialSelectedIndex?: number;
renderItem?: (item: T, index: number, isSelected: boolean) => React.ReactNode;
onScroll?: (e: React.UIEvent<HTMLDivElement>) => void;
getItemKey?: (item: T, index: number) => string | number;
}
export default function AnimatedList<T = any>({
items = [],
onItemSelect,
showGradients = false,
className = "",
itemClassName = "",
displayScrollbar = true,
initialSelectedIndex = -1,
renderItem,
onScroll,
getItemKey,
}: AnimatedListProps<T>) {
const listRef = useRef<HTMLDivElement>(null);
const [selectedIndex, setSelectedIndex] = useState(initialSelectedIndex);
const [topGradientOpacity, setTopGradientOpacity] = useState(0);
const [bottomGradientOpacity, setBottomGradientOpacity] = useState(1);
const handleItemMouseEnter = useCallback((index: number) => {
setSelectedIndex(index);
}, []);
const handleItemClick = useCallback(
(item: T, index: number) => {
setSelectedIndex(index);
if (onItemSelect) {
onItemSelect(item, index);
}
},
[onItemSelect]
);
const handleScroll = useCallback(
(e: React.UIEvent<HTMLDivElement>) => {
if (showGradients) {
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
setTopGradientOpacity(Math.min(scrollTop / 30, 1));
const bottomDistance = scrollHeight - (scrollTop + clientHeight);
setBottomGradientOpacity(scrollHeight <= clientHeight ? 0 : Math.min(bottomDistance / 30, 1));
}
if (onScroll) {
onScroll(e);
}
},
[showGradients, onScroll]
);
return (
<div className={`scroll-list-container ${className}`}>
<div
ref={listRef}
data-lenis-prevent
className={`scroll-list overscroll-contain ${!displayScrollbar ? "no-scrollbar" : ""}`}
onScroll={handleScroll}
onWheel={(e) => e.stopPropagation()}
onTouchMove={(e) => e.stopPropagation()}
>
{items.map((item, index) => {
const isSelected = selectedIndex === index;
const key = getItemKey ? getItemKey(item, index) : index;
return (
<AnimatedItem
key={key}
index={index}
onMouseEnter={() => handleItemMouseEnter(index)}
onClick={() => handleItemClick(item, index)}
>
{renderItem ? (
renderItem(item, index, isSelected)
) : (
<div className={`item ${isSelected ? "selected" : ""} ${itemClassName}`}>
<p className="item-text">{typeof item === "string" ? item : JSON.stringify(item)}</p>
</div>
)}
</AnimatedItem>
);
})}
</div>
{showGradients && (
<>
<div className="top-gradient" style={{ opacity: topGradientOpacity }} />
<div className="bottom-gradient" style={{ opacity: bottomGradientOpacity }} />
</>
)}
</div>
);
}
+267
View File
@@ -0,0 +1,267 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { searchMusic } from "@/api/music";
import { useAudioPlayer } from "@/hooks/useAudioPlayer";
import { usePlayerFavorites } from "@/hooks/usePlayerFavorites";
import { usePlayerPlaylists } from "@/hooks/usePlayerPlaylists";
import PlayerToast from "./player/PlayerToast";
import PlayerCapsuleBar from "./player/PlayerCapsuleBar";
import PlayerDrawerSheet from "./PlayerDrawerSheet";
import ExpandedPlayerModal from "./ExpandedPlayerModal";
import type { ApiSearchResult, TrackDetail } from "@/interface/music";
function formatTime(seconds: number) {
if (!Number.isFinite(seconds) || seconds < 0) return "00:00";
const minutes = Math.floor(seconds / 60);
const remaining = Math.floor(seconds % 60);
return `${String(minutes).padStart(2, "0")}:${String(remaining).padStart(2, "0")}`;
}
export default function ArchivePlayer() {
const {
playlist,
setPlaylist,
currentIndex,
setCurrentIndex,
currentTrack,
isPlaying,
setIsPlaying,
playMode,
currentTime,
duration,
volume,
setVolume,
isMuted,
setIsMuted,
selectedSource,
setSelectedSource,
isResolvingTrack,
playerMessage,
brokenCovers,
setBrokenCovers,
toastMessage,
setToastMessage,
showToast,
selectTrack,
playNext,
playPrevious,
cycleMode,
seek,
removeTrack,
resolveAndPlay,
} = useAudioPlayer();
const {
favorites,
isFavorite,
toggleFavorite,
playFavorites,
clearFavorites,
playFavoriteTrack,
} = usePlayerFavorites({
showToast,
setPlaylist,
setCurrentIndex,
setIsPlaying,
});
const {
playlists,
createPlaylist,
renamePlaylist,
removePlaylist,
addTracksToPlaylist,
removeTrackFromPlaylist,
handleTrackPlayback,
addPlaylistToQueue,
playPlaylistTrack,
} = usePlayerPlaylists({
setPlaylist,
setCurrentIndex,
setIsPlaying,
showToast,
});
// 包裹原本的导入逻辑:导入歌曲时,支持导入到已有的指定文件夹或自动新建文件夹
const handleImportPlaylistAndCreateFolder = useCallback(
(importedTracks: TrackDetail[], targetPlaylistId?: string) => {
// 根据目标文件夹选择决定是新建还是追加
if (!targetPlaylistId || targetPlaylistId === "create_new") {
const now = new Date();
const dateStr = `${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")} ${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}`;
const folderName = `导入歌单 - ${dateStr}`;
createPlaylist(folderName, importedTracks);
} else {
// 追加到指定已有歌单
addTracksToPlaylist(targetPlaylistId, importedTracks);
}
},
[createPlaylist, addTracksToPlaylist]
);
// 向当前播放队列追加单首曲目
const handleAddTrackToQueue = useCallback(
(track: TrackDetail) => {
setPlaylist((prev) => {
const exists = prev.some((t) => t.id === track.id && t.source === track.source);
if (exists) {
showToast(`《${track.title}》已在播放列表中`);
return prev;
}
showToast(`已将《${track.title}》追加到播放队列`);
return [...prev, track];
});
},
[setPlaylist, showToast]
);
// 一键清空当前播放队列
const handleClearPlaylist = useCallback(() => {
setPlaylist([]);
setCurrentIndex(0);
setIsPlaying(false);
showToast("播放队列已一键清空");
}, [setPlaylist, setCurrentIndex, setIsPlaying, showToast]);
// 当切歌或播放时,自动在后台产出海报并更新对应歌单的封面
useEffect(() => {
if (isPlaying && currentTrack) {
void handleTrackPlayback(currentTrack);
}
}, [isPlaying, currentTrack?.id, currentTrack?.source, handleTrackPlayback]);
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
const [isExpandedModalOpen, setIsExpandedModalOpen] = useState(false);
// 搜索相关状态
const [searchQuery, setSearchQuery] = useState("");
const [searchResults, setSearchResults] = useState<ApiSearchResult[]>([]);
const [isSearching, setIsSearching] = useState(false);
const [searchMessage, setSearchMessage] = useState("");
const handleExecuteSearch = useCallback(async () => {
if (!searchQuery.trim() || isSearching) return;
setIsSearching(true);
setSearchMessage("正在全网检索曲目...");
try {
const results = await searchMusic(searchQuery, selectedSource, 15);
setSearchResults(results);
setSearchMessage(results.length === 0 ? "未检索到相关曲目,换个关键词试一试" : "");
} catch {
setSearchMessage("检索音乐服务异常,请稍后重试");
} finally {
setIsSearching(false);
}
}, [searchQuery, selectedSource, isSearching]);
const handleMarkBrokenCover = useCallback((id: string) => {
setBrokenCovers((prev) => new Set(prev).add(id));
}, [setBrokenCovers]);
return (
<>
<PlayerToast
message={toastMessage}
onClose={() => setToastMessage(null)}
/>
<PlayerCapsuleBar
currentTrack={currentTrack}
playlistLength={playlist.length}
isPlaying={isPlaying}
isResolvingTrack={isResolvingTrack}
playMode={playMode}
currentTime={currentTime}
duration={duration}
volume={volume}
isMuted={isMuted}
brokenCovers={brokenCovers}
playerMessage={playerMessage}
isFavorite={isFavorite(currentTrack)}
onTogglePlay={() => setIsPlaying((p) => !p)}
onPlayNext={playNext}
onPlayPrev={playPrevious}
onCycleMode={cycleMode}
onSeek={seek}
onVolumeChange={setVolume}
onToggleMute={() => setIsMuted((m) => !m)}
onToggleFavorite={() => toggleFavorite(currentTrack)}
onOpenDrawer={() => setIsDrawerOpen(true)}
onOpenExpandedModal={() => setIsExpandedModalOpen(true)}
onMarkBrokenCover={handleMarkBrokenCover}
formatTime={formatTime}
/>
<PlayerDrawerSheet
isOpen={isDrawerOpen}
onClose={() => setIsDrawerOpen(false)}
playlist={playlist}
currentIndex={currentIndex}
isPlaying={isPlaying}
currentTrack={currentTrack}
onSelectTrack={selectTrack}
onRemoveTrack={removeTrack}
onImportPlaylist={handleImportPlaylistAndCreateFolder}
selectedSource={selectedSource}
onSourceChange={setSelectedSource}
searchQuery={searchQuery}
onSearchQueryChange={setSearchQuery}
onExecuteSearch={() => void handleExecuteSearch()}
isSearching={isSearching}
searchResults={searchResults}
searchMessage={searchMessage}
onResolveAndPlay={resolveAndPlay}
isResolvingTrack={isResolvingTrack}
favorites={favorites}
onToggleFavorite={toggleFavorite}
onPlayFavorites={playFavorites}
onClearFavorites={clearFavorites}
isFavorite={isFavorite}
onPlayFavoriteTrack={playFavoriteTrack}
playlists={playlists}
createPlaylist={createPlaylist}
renamePlaylist={renamePlaylist}
removePlaylist={removePlaylist}
removeTrackFromPlaylist={removeTrackFromPlaylist}
addPlaylistToQueue={addPlaylistToQueue}
playPlaylistTrack={playPlaylistTrack}
onAddTrackToQueue={handleAddTrackToQueue}
onClearPlaylist={handleClearPlaylist}
/>
<ExpandedPlayerModal
isOpen={isExpandedModalOpen}
onClose={() => setIsExpandedModalOpen(false)}
currentTrack={currentTrack}
isPlaying={isPlaying}
currentTime={currentTime}
duration={duration}
playMode={playMode}
bgmVolume={volume}
isMuted={isMuted}
brokenCovers={brokenCovers}
playerMessage={playerMessage}
isResolvingTrack={isResolvingTrack}
isFavorite={isFavorite(currentTrack)}
onToggleFavorite={() => toggleFavorite(currentTrack)}
onTogglePlay={() => setIsPlaying((p) => !p)}
onPlayNext={playNext}
onPlayPrev={playPrevious}
onCycleMode={cycleMode}
onSeek={seek}
onVolumeChange={setVolume}
onToggleMute={() => setIsMuted((m) => !m)}
onOpenDrawer={() => {
setIsExpandedModalOpen(false);
setIsDrawerOpen(true);
}}
onMarkBrokenCover={handleMarkBrokenCover}
playlistLength={playlist.length}
formatTime={formatTime}
/>
</>
);
}
+93
View File
@@ -0,0 +1,93 @@
"use client";
import React from "react";
interface AudioVisualizerProps {
isPlaying: boolean;
size?: "sm" | "md" | "lg";
barCount?: number;
className?: string;
}
/**
* 🌊 动态音频 Equalizer 柱波浪组件
* 参考 Apple Music / 网易云经典 4-6 柱圆角跳动频波
* 当 isPlaying 为 true 时产生平滑振幅跃动,暂停时优雅平缓归底
*/
export default function AudioVisualizer({
isPlaying,
size = "md",
barCount = 5,
className = "",
}: AudioVisualizerProps) {
// 根据 size 配置不同的柱体尺寸与间距
const sizeStyles = {
sm: {
container: "h-4 gap-0.5 px-1",
bar: "w-1",
minHeight: "h-1",
},
md: {
container: "h-7 gap-1 px-2",
bar: "w-1.5",
minHeight: "h-1.5",
},
lg: {
container: "h-12 gap-1.5 px-3",
bar: "w-2.5",
minHeight: "h-2",
},
};
const style = sizeStyles[size] || sizeStyles.md;
// 生成指定数量柱子的随机动画延迟与振幅倍数
const bars = Array.from({ length: barCount }, (_, i) => {
const delay = (i * 150) % 600;
const duration = 0.5 + (i % 3) * 0.25; // 0.5s - 1.0s
return { id: i, delay, duration };
});
return (
<div className={`flex items-end justify-center select-none ${style.container} ${className}`}>
{bars.map((bar) => (
<span
key={bar.id}
className={`rounded-full transition-all duration-300 ${style.bar} ${
isPlaying
? "bg-[#E07A5F] dark:bg-[#F28482] shadow-[0_0_10px_rgba(224,122,95,0.5)]"
: `bg-[#E07A5F]/40 dark:bg-[#F28482]/40 ${style.minHeight}`
}`}
style={{
animation: isPlaying
? `equalizer-bounce ${bar.duration}s ease-in-out infinite alternate`
: "none",
animationDelay: `${bar.delay}ms`,
}}
/>
))}
{/* 动态均衡器 Keyframes 注入 */}
<style jsx global>{`
@keyframes equalizer-bounce {
0% {
height: 15%;
opacity: 0.6;
}
30% {
height: 85%;
opacity: 1;
}
65% {
height: 35%;
opacity: 0.75;
}
100% {
height: 100%;
opacity: 1;
}
}
`}</style>
</div>
);
}
+201
View File
@@ -0,0 +1,201 @@
"use client";
import { RefObject, useEffect, useRef, useState } from "react";
interface AudioWaveformProps {
audioRef: RefObject<HTMLAudioElement | null>;
isPlaying: boolean;
currentTime: number;
duration: number;
onSeek: (time: number) => void;
}
interface AudioGraph {
context: AudioContext;
analyser: AnalyserNode;
}
const audioGraphs = new WeakMap<HTMLAudioElement, AudioGraph>();
function getAudioGraph(audio: HTMLAudioElement) {
const existing = audioGraphs.get(audio);
if (existing && existing.context.state !== "closed") return existing;
const AudioContextClass = window.AudioContext;
const context = new AudioContextClass();
const analyser = context.createAnalyser();
const source = context.createMediaElementSource(audio);
analyser.fftSize = 128;
analyser.smoothingTimeConstant = 0.8;
source.connect(analyser);
analyser.connect(context.destination);
const graph = { context, analyser };
audioGraphs.set(audio, graph);
return graph;
}
export default function AudioWaveform({
audioRef,
isPlaying,
currentTime,
duration,
onSeek,
}: AudioWaveformProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const graphRef = useRef<AudioGraph | null>(null);
const frameRef = useRef<number | null>(null);
const frequencyDataRef = useRef<Uint8Array<ArrayBuffer>>(new Uint8Array(64));
const [isHovered, setIsHovered] = useState(false);
const [hoverProgress, setHoverProgress] = useState(0);
// 基础波形柱的高度分布 (48 根柱子)
const BAR_COUNT = 48;
const baseHeightsRef = useRef<Float32Array>(
Float32Array.from({ length: BAR_COUNT }, (_, i) => {
const x = i / BAR_COUNT;
const wave = Math.sin(x * Math.PI * 3) * 0.3;
const pulse = Math.cos(x * Math.PI * 1.5) * 0.25;
return Math.min(1, Math.max(0.2, 0.45 + wave + pulse));
})
);
useEffect(() => {
if (!isPlaying || !audioRef.current) return;
try {
const sourceUrl = new URL(audioRef.current.currentSrc || audioRef.current.src, window.location.origin);
if (sourceUrl.origin !== window.location.origin) return;
const graph = getAudioGraph(audioRef.current);
graphRef.current = graph;
void graph.context.resume();
} catch {
// AudioContext CORS fallback
}
}, [audioRef, isPlaying]);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const context = canvas.getContext("2d");
if (!context) return;
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const resize = () => {
const rect = canvas.getBoundingClientRect();
const ratio = Math.min(window.devicePixelRatio || 1, 2);
canvas.width = Math.max(1, Math.round(rect.width * ratio));
canvas.height = Math.max(1, Math.round(rect.height * ratio));
context.setTransform(ratio, 0, 0, ratio, 0, 0);
};
const observer = new ResizeObserver(resize);
observer.observe(canvas);
resize();
const render = () => {
const rect = canvas.getBoundingClientRect();
const width = rect.width;
const height = rect.height;
if (width === 0 || height === 0) return;
context.clearRect(0, 0, width, height);
const analyser = graphRef.current?.analyser;
const freqData = frequencyDataRef.current;
if (analyser && isPlaying) {
analyser.getByteFrequencyData(freqData);
}
const progress = duration > 0 ? currentTime / duration : 0;
const barWidth = 3;
const gap = (width - BAR_COUNT * barWidth) / (BAR_COUNT - 1);
for (let i = 0; i < BAR_COUNT; i++) {
const x = i * (barWidth + gap);
const barProgress = i / BAR_COUNT;
let heightFactor = baseHeightsRef.current[i];
if (isPlaying && !reduceMotion) {
if (analyser && freqData[i % freqData.length]) {
const freqVal = freqData[i % freqData.length] / 255;
heightFactor = 0.2 + freqVal * 0.8;
} else {
const time = performance.now() * 0.003;
const dynamicWave = Math.sin(time + i * 0.4) * 0.25;
heightFactor = Math.min(1, Math.max(0.2, heightFactor + dynamicWave));
}
}
const barHeight = Math.max(3, heightFactor * height * 0.85);
const y = (height - barHeight) / 2;
const isPassed = barProgress <= progress;
context.beginPath();
context.roundRect(x, y, barWidth, barHeight, 1.5);
if (isPassed) {
context.fillStyle = "#E07A5F"; // 进度高亮 Accent 色
context.shadowColor = "rgba(224, 122, 95, 0.6)";
context.shadowBlur = isPlaying ? 6 : 0;
} else {
context.fillStyle = "rgba(255, 255, 255, 0.22)";
context.shadowBlur = 0;
}
context.fill();
}
if (isPlaying && !reduceMotion) {
frameRef.current = requestAnimationFrame(render);
}
};
render();
return () => {
observer.disconnect();
if (frameRef.current !== null) cancelAnimationFrame(frameRef.current);
};
}, [currentTime, duration, isPlaying]);
const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (!containerRef.current) return;
const rect = containerRef.current.getBoundingClientRect();
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
setHoverProgress(x / rect.width);
};
const handleSeek = (e: React.MouseEvent<HTMLDivElement>) => {
if (!containerRef.current || duration <= 0) return;
const rect = containerRef.current.getBoundingClientRect();
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
const nextTime = (x / rect.width) * duration;
onSeek(nextTime);
};
return (
<div
ref={containerRef}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
onPointerMove={handlePointerMove}
onClick={handleSeek}
className="relative w-full h-4 py-1 cursor-pointer group flex items-center select-none"
title="点击或拖动调节进度"
>
<canvas ref={canvasRef} className="w-full h-full pointer-events-none" />
{/* Hover 时的细游标与时间提示 */}
{isHovered && (
<div
className="absolute top-0 bottom-0 w-0.5 bg-white shadow-[0_0_8px_white] pointer-events-none z-10"
style={{ left: `${hoverProgress * 100}%` }}
/>
)}
</div>
);
}
+1 -1
View File
@@ -55,7 +55,7 @@ export default function BackToTop() {
return (
<button
onClick={handleLaunch}
className={`fixed right-6 bottom-20 z-[1000] flex h-12 w-12 items-center justify-center rounded-full border border-charcoal/10 dark:border-white/10 bg-cream/90 dark:bg-charcoal/90 text-charcoal shadow-lg backdrop-blur-md transition-all duration-300 cursor-pointer pointer-events-auto hover:border-gold hover:text-gold hover:scale-105 active:scale-95 group ${
className={`fixed right-5 bottom-32 z-60 flex h-11 w-11 items-center justify-center rounded-full border border-charcoal/10 dark:border-white/10 bg-cream/90 dark:bg-charcoal/90 text-charcoal shadow-lg backdrop-blur-md transition-all duration-300 cursor-pointer pointer-events-auto hover:border-gold hover:text-gold hover:scale-105 active:scale-95 group sm:right-6 sm:bottom-36 ${
isVisible ? "opacity-100 translate-y-0 scale-100" : "opacity-0 translate-y-8 scale-75 pointer-events-none"
}`}
aria-label="返回顶部"
+484
View File
@@ -0,0 +1,484 @@
"use client";
import React, { useEffect, useRef, useMemo } from "react";
import { createPortal } from "react-dom";
import gsap from "gsap";
import {
Play,
Pause,
SkipForward,
SkipBack,
X,
Volume2,
VolumeX,
Repeat,
Repeat1,
Shuffle,
Music2,
ListMusic,
Radio,
Loader2,
Heart,
} from "lucide-react";
import type { TrackDetail } from "@/interface/music";
const DefaultVinylCover = () => (
<div className="size-full bg-radial from-[#22232a] to-[#0f1015] flex items-center justify-center relative shadow-inner select-none pointer-events-none">
{/* 唱片的同心圆纹路 */}
<div className="absolute inset-2 rounded-full border border-white/5" />
<div className="absolute inset-5 rounded-full border border-white/5" />
<div className="absolute inset-9 rounded-full border border-white/5" />
{/* 红心胶心 */}
<div className="size-10 rounded-full bg-rose-500 flex items-center justify-center shadow-xs">
<Music2 className="w-5 h-5 text-white/80" />
</div>
</div>
);
export interface LyricLine {
time: number;
text: string;
translation?: string;
}
function parseLyric(lrc?: string, tlrc?: string): LyricLine[] {
if (!lrc && !tlrc) return [];
const parseSingle = (content?: string) => {
if (!content) return [];
const lines = content.split("\n");
const result: { time: number; text: string }[] = [];
const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/;
for (const line of lines) {
const match = timeRegex.exec(line);
if (match) {
const minutes = parseInt(match[1], 10);
const seconds = parseInt(match[2], 10);
const milliseconds = parseInt(match[3], 10);
const time = minutes * 60 + seconds + (milliseconds > 99 ? milliseconds / 1000 : milliseconds / 100);
const text = line.replace(timeRegex, "").trim();
if (text) {
result.push({ time, text });
}
}
}
return result;
};
const mainLines = parseSingle(lrc);
const transLines = parseSingle(tlrc);
const resultMap = new Map<number, LyricLine>();
for (const item of mainLines) {
const key = Math.floor(item.time * 10) / 10;
resultMap.set(key, { time: item.time, text: item.text });
}
for (const item of transLines) {
const key = Math.floor(item.time * 10) / 10;
const existing = resultMap.get(key);
if (existing) {
existing.translation = item.text;
} else {
resultMap.set(key, { time: item.time, text: item.text, translation: item.text });
}
}
return Array.from(resultMap.values()).sort((a, b) => a.time - b.time);
}
interface ExpandedPlayerModalProps {
isOpen: boolean;
onClose: () => void;
currentTrack: TrackDetail;
isPlaying: boolean;
isResolvingTrack?: boolean;
isLoadingAudio?: boolean;
onTogglePlay: () => void;
onPlayNext: () => void;
onPlayPrev: () => void;
currentTime: number;
duration: number;
onSeek: (time: number) => void;
bgmVolume: number;
isMuted: boolean;
onVolumeChange: (val: number) => void;
onToggleMute: () => void;
playMode: "sequence" | "repeat" | "shuffle";
onCycleMode: () => void;
formatTime: (seconds: number) => string;
onOpenDrawer: () => void;
isFavorite?: boolean;
onToggleFavorite?: () => void;
brokenCovers?: Set<string>;
playerMessage?: string;
onMarkBrokenCover?: (id: string) => void;
playlistLength?: number;
}
export default function ExpandedPlayerModal({
isOpen,
onClose,
currentTrack,
isPlaying,
isResolvingTrack = false,
isLoadingAudio = false,
onTogglePlay,
onPlayNext,
onPlayPrev,
currentTime,
duration,
onSeek,
bgmVolume,
isMuted,
onVolumeChange,
onToggleMute,
playMode,
onCycleMode,
formatTime,
onOpenDrawer,
isFavorite = false,
onToggleFavorite,
brokenCovers,
playerMessage,
onMarkBrokenCover,
playlistLength = 0,
}: ExpandedPlayerModalProps) {
const [mounted, setMounted] = React.useState(false);
const lyricScrollRef = useRef<HTMLDivElement>(null);
const activeLyricRef = useRef<HTMLParagraphElement>(null);
const backdropRef = useRef<HTMLDivElement>(null);
const cardRef = useRef<HTMLDivElement>(null);
useEffect(() => {
setMounted(true);
}, []);
const [localCoverFailed, setLocalCoverFailed] = React.useState(false);
useEffect(() => {
setLocalCoverFailed(false);
}, [currentTrack?.id]);
const lyricLines = useMemo(
() => parseLyric(currentTrack?.lyric, currentTrack?.tlyric),
[currentTrack?.lyric, currentTrack?.tlyric]
);
const activeIndex = useMemo(() => {
if (lyricLines.length === 0) return -1;
const index = lyricLines.findIndex((line) => line.time > currentTime);
if (index === -1) return lyricLines.length - 1;
return Math.max(0, index - 1);
}, [currentTime, lyricLines]);
// 滚动高亮歌词到视图中央
useEffect(() => {
if (activeLyricRef.current && lyricScrollRef.current) {
const activeEl = activeLyricRef.current;
const containerEl = lyricScrollRef.current;
const top = activeEl.offsetTop - containerEl.offsetTop - containerEl.clientHeight / 2 + activeEl.clientHeight / 2;
containerEl.scrollTo({ top: Math.max(0, top), behavior: "smooth" });
}
}, [activeIndex]);
// GSAP 打开/收起动画
useEffect(() => {
if (!mounted) return;
const backdrop = backdropRef.current;
const card = cardRef.current;
if (!backdrop || !card) return;
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const ctx = gsap.context(() => {
if (isOpen) {
gsap.set(backdrop, { display: "flex", autoAlpha: 0 });
gsap.set(card, { scale: 0.95, y: 20, autoAlpha: 0 });
gsap.to(backdrop, {
autoAlpha: 1,
duration: reduceMotion ? 0 : 0.3,
ease: "power2.out",
});
gsap.to(card, {
scale: 1,
y: 0,
autoAlpha: 1,
duration: reduceMotion ? 0 : 0.4,
ease: "back.out(1.2)",
});
} else {
gsap.to(card, {
scale: 0.95,
y: 20,
autoAlpha: 0,
duration: reduceMotion ? 0 : 0.25,
ease: "power2.in",
});
gsap.to(backdrop, {
autoAlpha: 0,
duration: reduceMotion ? 0 : 0.3,
ease: "power2.in",
onComplete: () => {
if (backdrop) gsap.set(backdrop, { display: "none" });
},
});
}
});
return () => ctx.revert();
}, [isOpen, mounted]);
if (!isOpen || !mounted || typeof document === "undefined") return null;
const isLoading = isResolvingTrack || isLoadingAudio;
const coverIsAvailable = Boolean(
playlistLength > 0 &&
currentTrack?.cover &&
!brokenCovers?.has(currentTrack.id) &&
!localCoverFailed
);
const modalContent = (
<div
ref={backdropRef}
className="fixed inset-0 z-200 bg-black/75 backdrop-blur-2xl flex items-center justify-center p-4 md:p-8 transition-opacity"
onClick={onClose}
aria-hidden={!isOpen}
>
<div
ref={cardRef}
onClick={(e) => e.stopPropagation()}
className="w-full max-w-5xl h-[85vh] max-h-[750px] bg-(--bg-dark-color)/95 border border-(--border-line-color) rounded-3xl shadow-[0_25px_80px_rgba(0,0,0,0.5)] flex flex-col md:flex-row overflow-hidden relative"
>
<button
type="button"
onClick={onClose}
className="absolute top-4 right-4 z-30 p-2.5 rounded-full bg-(--fg-color)/10 hover:bg-(--fg-color)/20 text-(--fg-color) transition-colors cursor-pointer"
aria-label="关闭黑胶唱片大屏"
>
<X className="w-5 h-5" />
</button>
{/* 1. 左侧:黑胶唱片与控制 */}
<div className="w-full md:w-1/2 h-1/2 md:h-full p-6 md:p-10 flex flex-col justify-between items-center border-b md:border-b-0 md:border-r border-(--border-line-color) relative">
<div className="w-full flex items-center justify-between">
<span className="text-xs font-semibold px-3 py-1 rounded-full bg-(--accent-color)/15 text-(--accent-color) border border-(--accent-color)/30">
{currentTrack?.source || "netease"} 音源
</span>
{onToggleFavorite && (
<button
type="button"
onClick={onToggleFavorite}
className={`p-2 rounded-full transition-all cursor-pointer ${
isFavorite
? "text-rose-500 bg-rose-500/10 hover:bg-rose-500/20"
: "text-(--fg-color)/50 hover:text-rose-500 hover:bg-(--fg-color)/10"
}`}
title={isFavorite ? "取消收藏" : "加入收藏"}
>
<Heart className={`w-5 h-5 ${isFavorite ? "fill-current" : ""}`} />
</button>
)}
</div>
{/* 拟物黑胶唱片 */}
<div className="relative my-auto size-48 sm:size-60 md:size-64 rounded-full bg-linear-to-tr from-zinc-900 via-zinc-800 to-zinc-950 p-3 shadow-2xl border-4 border-zinc-800 flex items-center justify-center shrink-0">
<div className="absolute inset-0 rounded-full border border-white/5 pointer-events-none" />
<div
className={`relative size-full rounded-full overflow-hidden border-2 border-zinc-700/50 shadow-inner ${
isPlaying ? "animate-spin-slow" : ""
}`}
style={{ animationPlayState: isPlaying ? "running" : "paused", willChange: "transform", transform: "translateZ(0)" }}
>
{coverIsAvailable ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={currentTrack.cover}
alt={currentTrack.title}
className="size-full object-cover"
onError={() => {
onMarkBrokenCover?.(currentTrack.id);
setLocalCoverFailed(true);
}}
/>
) : (
<DefaultVinylCover />
)}
</div>
<div className="absolute size-10 rounded-full bg-zinc-900 border-4 border-zinc-800 shadow-inner flex items-center justify-center pointer-events-none">
<div className="size-3 rounded-full bg-zinc-950" />
</div>
</div>
<div className="w-full text-center space-y-1 mt-2">
<h3 className="text-lg md:text-xl font-bold text-(--fg-color) truncate px-4">
{currentTrack?.title || "暂无歌曲播放"}
</h3>
<p className="text-xs md:text-sm text-(--fg-color)/60 truncate">
{currentTrack?.artist || "未知歌手"} • {currentTrack?.album || "生活档案馆"}
</p>
</div>
<div className="w-full space-y-1.5 my-3">
<div className="w-full flex items-center gap-3 text-xs font-mono text-(--fg-color)/60">
<span className="w-10 text-right shrink-0">{formatTime(currentTime)}</span>
<div className="grow relative flex items-center group h-3 cursor-pointer">
<input
type="range"
min={0}
max={duration || 100}
value={currentTime}
onChange={(e) => onSeek(parseFloat(e.target.value))}
className="w-full h-1.5 bg-(--fg-color)/20 rounded-lg appearance-none cursor-pointer accent-(--accent-color) focus:outline-none"
/>
</div>
<span className="w-10 shrink-0">{formatTime(duration)}</span>
</div>
</div>
<div className="w-full flex items-center justify-between pt-2 px-2">
<button
type="button"
onClick={onCycleMode}
className="p-2 text-(--fg-color)/60 hover:text-(--fg-color) transition-colors cursor-pointer"
title={playMode === "sequence" ? "顺序播放" : playMode === "repeat" ? "单曲循环" : "随机播放"}
>
{playMode === "sequence" && <Repeat className="w-4 h-4" />}
{playMode === "repeat" && <Repeat1 className="w-4 h-4 text-(--accent-color)" />}
{playMode === "shuffle" && <Shuffle className="w-4 h-4 text-(--accent-color)" />}
</button>
<div className="flex items-center gap-6">
<button
type="button"
onClick={onPlayPrev}
className="text-(--fg-color)/80 hover:text-(--fg-color) transition-transform active:scale-90 cursor-pointer"
title="上一首"
>
<SkipBack className="w-6 h-6 fill-current" />
</button>
<button
type="button"
onClick={onTogglePlay}
disabled={isLoading}
className="w-13 h-13 rounded-full text-white flex items-center justify-center shadow-lg hover:scale-105 active:scale-95 transition-all cursor-pointer disabled:opacity-50"
style={{ backgroundColor: "var(--accent-color, #E07A5F)" }}
title={isPlaying ? "暂停" : "播放"}
>
{isLoading ? (
<Loader2 className="w-6 h-6 animate-spin" />
) : isPlaying ? (
<Pause className="w-6 h-6 fill-current" />
) : (
<Play className="w-6 h-6 fill-current translate-x-0.5" />
)}
</button>
<button
type="button"
onClick={onPlayNext}
className="text-(--fg-color)/80 hover:text-(--fg-color) transition-transform active:scale-90 cursor-pointer"
title="下一首"
>
<SkipForward className="w-6 h-6 fill-current" />
</button>
</div>
<button
type="button"
onClick={onOpenDrawer}
className="p-2 text-(--fg-color)/60 hover:text-(--fg-color) transition-colors cursor-pointer"
title="打开播放列表与搜索"
>
<ListMusic className="w-5 h-5" />
</button>
</div>
</div>
{/* 2. 右侧:独立流动歌词面板 */}
<div className="w-full md:w-1/2 h-1/2 md:h-full p-6 md:p-10 flex flex-col justify-between bg-(--fg-color)/2 relative">
<div className="w-full pb-4 border-b border-(--border-line-color) flex items-center justify-between shrink-0">
<div className="flex items-center gap-2">
<Music2 className="w-4 h-4 text-(--accent-color)" />
<h4 className="font-bold text-sm text-(--fg-color)/80">
歌词中心 <span className="text-[10px] font-normal text-(--fg-color)/40 ml-1">(点击歌词可跳转播放进度)</span>
</h4>
</div>
<div className="flex items-center gap-3">
<button
type="button"
onClick={onToggleMute}
className="text-(--fg-color)/60 hover:text-(--fg-color) cursor-pointer"
>
{isMuted || bgmVolume === 0 ? <VolumeX className="w-4 h-4" /> : <Volume2 className="w-4 h-4" />}
</button>
<input
type="range"
min={0}
max={1}
step={0.01}
value={isMuted ? 0 : bgmVolume}
onChange={(e) => onVolumeChange(parseFloat(e.target.value))}
className="w-20 h-1 bg-(--fg-color)/20 rounded-lg appearance-none cursor-pointer accent-(--accent-color) focus:outline-none"
/>
</div>
</div>
<div
ref={lyricScrollRef}
className="w-full grow overflow-y-auto py-12 px-2 space-y-6 scrollbar-none transition-all overscroll-contain"
onWheel={(e) => e.stopPropagation()}
style={{ scrollBehavior: "smooth" }}
>
{lyricLines.length > 0 ? (
lyricLines.map((line, idx) => {
const isActive = idx === activeIndex;
return (
<div
key={idx}
ref={isActive ? activeLyricRef : null}
onClick={() => onSeek(line.time)}
className={`transition-all duration-300 text-center leading-relaxed cursor-pointer select-none hover:scale-105 active:scale-95 ${
isActive
? "text-xl md:text-2xl font-bold text-(--accent-color) scale-105 drop-shadow-[0_0_12px_rgba(224,122,95,0.4)]"
: "text-sm md:text-base text-(--fg-color)/40 hover:text-(--fg-color)/80"
}`}
title={`点击跳转至 ${formatTime(line.time)}`}
>
<p>{line.text}</p>
{line.translation && (
<p className={`text-xs md:text-sm mt-1 font-normal ${isActive ? "text-(--accent-color)/80" : "text-(--fg-color)/30"}`}>
{line.translation}
</p>
)}
</div>
);
})
) : (
<div className="h-full flex flex-col items-center justify-center text-(--fg-color)/40 space-y-2">
<Radio className="w-10 h-10 stroke-1 opacity-40 animate-pulse" />
<p className="text-sm font-mono">纯音乐 / 暂无歌词</p>
<p className="text-xs text-(--fg-color)/30">
{currentTrack?.album || "生活档案馆 • 治愈听觉体验"}
</p>
</div>
)}
</div>
<div className="w-full pt-3 text-center text-[11px] text-(--fg-color)/50 font-mono border-t border-(--border-line-color) shrink-0">
{currentTrack?.title} - {currentTrack?.artist}
</div>
</div>
</div>
</div>
);
return createPortal(modalContent, document.body);
}
+348
View File
@@ -0,0 +1,348 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import gsap from "gsap";
import { musicIcons } from "@/icon/music";
import type { ApiSearchResult, MusicSource, TrackDetail } from "@/interface/music";
import DrawerPlaylistTab from "./player/DrawerPlaylistTab";
import DrawerFavoritesTab from "./player/DrawerFavoritesTab";
import DrawerSearchTab from "./player/DrawerSearchTab";
import DrawerImportTab from "./player/DrawerImportTab";
import DrawerPlaylistsTab from "./player/DrawerPlaylistsTab";
import type { PlaylistFolder } from "@/hooks/usePlayerPlaylists";
const {
close: CloseIcon,
heart: HeartIcon,
folder: FolderIcon,
trash: TrashIcon,
} = musicIcons;
interface PlayerDrawerSheetProps {
isOpen: boolean;
onClose: () => void;
playlist: TrackDetail[];
currentIndex: number;
isPlaying: boolean;
currentTrack: TrackDetail;
onSelectTrack: (index: number) => void;
onRemoveTrack?: (index: number) => void;
onImportPlaylist?: (tracks: TrackDetail[], targetPlaylistId?: string) => void;
selectedSource: MusicSource;
onSourceChange: (source: MusicSource) => void;
searchQuery: string;
onSearchQueryChange: (query: string) => void;
onExecuteSearch: () => void;
isSearching: boolean;
searchResults: ApiSearchResult[];
searchMessage: string;
onResolveAndPlay: (result: ApiSearchResult) => void;
isResolvingTrack: boolean;
favorites?: TrackDetail[];
onToggleFavorite?: (track: TrackDetail) => void;
onPlayFavorites?: () => void;
onClearFavorites?: () => void;
isFavorite?: (track: TrackDetail) => boolean;
onPlayFavoriteTrack?: (track: TrackDetail) => void;
// 我的歌单相关 props
playlists?: PlaylistFolder[];
createPlaylist?: (name: string, tracks?: TrackDetail[]) => string;
renamePlaylist?: (id: string, name: string) => void;
removePlaylist?: (id: string) => void;
removeTrackFromPlaylist?: (playlistId: string, trackId: string, source: MusicSource) => void;
addPlaylistToQueue?: (playlistId: string, append?: boolean) => void;
playPlaylistTrack?: (track: TrackDetail) => void;
onAddTrackToQueue?: (track: TrackDetail) => void;
onClearPlaylist?: () => void;
}
export default function PlayerDrawerSheet({
isOpen,
onClose,
playlist,
currentIndex,
isPlaying,
currentTrack,
onSelectTrack,
onRemoveTrack,
onImportPlaylist,
selectedSource,
onSourceChange,
searchQuery,
onSearchQueryChange,
onExecuteSearch,
isSearching,
searchResults,
searchMessage,
onResolveAndPlay,
isResolvingTrack,
favorites = [],
onToggleFavorite,
onPlayFavorites,
onClearFavorites,
isFavorite,
onPlayFavoriteTrack,
playlists = [],
createPlaylist,
renamePlaylist,
removePlaylist,
removeTrackFromPlaylist,
addPlaylistToQueue,
playPlaylistTrack,
onAddTrackToQueue,
onClearPlaylist,
}: PlayerDrawerSheetProps) {
const [activeTab, setActiveTab] = useState<"playlist" | "favorites" | "playlists" | "search" | "import">("playlist");
const [mounted, setMounted] = useState(false);
const backdropRef = useRef<HTMLDivElement>(null);
const drawerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
setMounted(true);
}, []);
useEffect(() => {
if (!mounted) return;
const backdrop = backdropRef.current;
const drawer = drawerRef.current;
if (!backdrop || !drawer) return;
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const ctx = gsap.context(() => {
if (isOpen) {
gsap.killTweensOf([backdrop, drawer]);
gsap.set(backdrop, { display: "block", autoAlpha: 0 });
gsap.set(drawer, { yPercent: 100, autoAlpha: 0 });
gsap.to(backdrop, {
autoAlpha: 1,
duration: reduceMotion ? 0 : 0.3,
ease: "power2.out",
force3D: true,
});
gsap.to(drawer, {
yPercent: 0,
autoAlpha: 1,
duration: reduceMotion ? 0 : 0.4,
ease: "power3.out",
force3D: true,
});
} else {
gsap.killTweensOf([backdrop, drawer]);
gsap.to(drawer, {
yPercent: 100,
autoAlpha: 0,
duration: reduceMotion ? 0 : 0.3,
ease: "power3.in",
force3D: true,
});
gsap.to(backdrop, {
autoAlpha: 0,
duration: reduceMotion ? 0 : 0.25,
ease: "power2.in",
force3D: true,
onComplete: () => {
if (backdrop) gsap.set(backdrop, { display: "none" });
},
});
}
});
return () => ctx.revert();
}, [isOpen, mounted]);
const content = (
<div
ref={backdropRef}
className="fixed inset-0 z-160 bg-black/50 select-none"
onClick={onClose}
aria-hidden={!isOpen}
>
<div
ref={drawerRef}
onClick={(e) => e.stopPropagation()}
onWheel={(e) => e.stopPropagation()}
className="absolute inset-x-0 bottom-0 mx-auto w-[calc(100%-2rem)] max-w-6xl h-[78vh] max-h-[700px] rounded-t-3xl border-t border-x border-(--border-line-color) bg-(--bg-dark-color)/98 text-(--fg-color) shadow-[0_-20px_60px_rgba(0,0,0,0.4)] flex flex-col pointer-events-auto overflow-hidden"
role="dialog"
aria-label="播放队列与音乐搜索"
>
<div className="w-full pt-3 pb-1 flex flex-col items-center shrink-0">
<div className="w-12 h-1 rounded-full bg-(--fg-color)/20" />
</div>
<header className="flex items-center justify-between border-b border-(--border-line-color) px-6 py-3 shrink-0">
<div className="flex items-center gap-1.5 bg-(--fg-color)/6 p-1 rounded-2xl border border-(--border-line-color)">
<button
type="button"
onClick={() => setActiveTab("playlist")}
className={`px-3.5 py-1.5 text-xs font-semibold rounded-xl transition-all cursor-pointer ${
activeTab === "playlist"
? "bg-(--accent-color) text-white shadow-md"
: "text-(--fg-color)/60 hover:text-(--fg-color)"
}`}
>
播放队列 ({playlist.length})
</button>
<button
type="button"
onClick={() => setActiveTab("favorites")}
className={`px-3.5 py-1.5 text-xs font-semibold rounded-xl transition-all cursor-pointer flex items-center gap-1 ${
activeTab === "favorites"
? "bg-(--accent-color) text-white shadow-md"
: "text-(--fg-color)/60 hover:text-(--fg-color)"
}`}
>
<HeartIcon size={13} weight={activeTab === "favorites" ? "fill" : "regular"} className={activeTab === "favorites" ? "text-white" : "text-rose-400"} />
<span>我的收藏 ({favorites.length})</span>
</button>
<button
type="button"
onClick={() => setActiveTab("playlists")}
className={`px-3.5 py-1.5 text-xs font-semibold rounded-xl transition-all cursor-pointer flex items-center gap-1 ${
activeTab === "playlists"
? "bg-(--accent-color) text-white shadow-md"
: "text-(--fg-color)/60 hover:text-(--fg-color)"
}`}
>
<FolderIcon size={13} weight={activeTab === "playlists" ? "fill" : "regular"} className={activeTab === "playlists" ? "text-white" : "text-amber-400"} />
<span>我的歌单 ({playlists.length})</span>
</button>
<button
type="button"
onClick={() => setActiveTab("search")}
className={`px-3.5 py-1.5 text-xs font-semibold rounded-xl transition-all cursor-pointer ${
activeTab === "search"
? "bg-(--accent-color) text-white shadow-md"
: "text-(--fg-color)/60 hover:text-(--fg-color)"
}`}
>
在线搜索
</button>
<button
type="button"
onClick={() => setActiveTab("import")}
className={`px-3.5 py-1.5 text-xs font-semibold rounded-xl transition-all cursor-pointer ${
activeTab === "import"
? "bg-(--accent-color) text-white shadow-md"
: "text-(--fg-color)/60 hover:text-(--fg-color)"
}`}
>
歌单导入
</button>
</div>
<button
type="button"
onClick={onClose}
className="grid size-9 place-items-center rounded-full bg-(--fg-color)/6 text-(--fg-color)/70 transition-colors hover:bg-(--fg-color)/15 hover:text-(--fg-color) cursor-pointer"
aria-label="关闭播放面板"
>
<CloseIcon size={18} weight="bold" />
</button>
</header>
<div className="flex items-center justify-between px-4 sm:px-6 py-4 border-b border-(--border-line-color)/40 shrink-0">
<div className="flex items-center gap-2 min-w-0">
<span className="text-xs text-(--fg-color)/40 shrink-0">●</span>
<span className="text-xs font-semibold text-(--fg-color)/70 truncate">
正在播放: {playlist.length > 0 && currentTrack ? `${currentTrack.title} - ${currentTrack.artist}` : "暂无歌曲播放"}
</span>
</div>
{activeTab === "playlist" && playlist.length > 0 && onClearPlaylist && (
<button
type="button"
onClick={onClearPlaylist}
className="text-red-500 hover:text-red-600 text-xs font-semibold transition-colors cursor-pointer flex items-center gap-1 active:scale-95 shrink-0 ml-4"
title="一键清空整个播放队列"
>
<TrashIcon size={13} />
<span>清空队列</span>
</button>
)}
</div>
<div className="grow min-h-0 flex flex-col p-6">
{activeTab === "playlist" && (
<DrawerPlaylistTab
playlist={playlist}
currentIndex={currentIndex}
isPlaying={isPlaying}
isResolvingTrack={isResolvingTrack}
onSelectTrack={onSelectTrack}
onRemoveTrack={onRemoveTrack}
onToggleFavorite={onToggleFavorite}
isFavorite={isFavorite}
/>
)}
{activeTab === "favorites" && (
<DrawerFavoritesTab
favorites={favorites}
currentTrack={currentTrack}
isResolvingTrack={isResolvingTrack}
onPlayFavorites={onPlayFavorites}
onClearFavorites={onClearFavorites}
onToggleFavorite={onToggleFavorite}
onPlayFavoriteTrack={onPlayFavoriteTrack}
onSwitchToSearch={() => setActiveTab("search")}
/>
)}
{activeTab === "playlists" && (
<DrawerPlaylistsTab
playlists={playlists}
isPlaying={isPlaying}
currentTrack={currentTrack}
isResolvingTrack={isResolvingTrack}
createPlaylist={createPlaylist || (() => "")}
renamePlaylist={renamePlaylist || (() => {})}
removePlaylist={removePlaylist || (() => {})}
removeTrackFromPlaylist={removeTrackFromPlaylist || (() => {})}
addPlaylistToQueue={addPlaylistToQueue || (() => {})}
playPlaylistTrack={playPlaylistTrack || (() => {})}
onAddTrackToQueue={onAddTrackToQueue}
isFavorite={isFavorite}
onToggleFavorite={onToggleFavorite}
/>
)}
{activeTab === "search" && (
<DrawerSearchTab
selectedSource={selectedSource}
onSourceChange={onSourceChange}
searchQuery={searchQuery}
onSearchQueryChange={onSearchQueryChange}
onExecuteSearch={onExecuteSearch}
isSearching={isSearching}
searchResults={searchResults}
searchMessage={searchMessage}
onResolveAndPlay={onResolveAndPlay}
isResolvingTrack={isResolvingTrack}
onToggleFavorite={onToggleFavorite}
isFavorite={isFavorite}
/>
)}
{activeTab === "import" && (
<DrawerImportTab
selectedSource={selectedSource}
onImportPlaylist={onImportPlaylist}
playlists={playlists}
/>
)}
</div>
</div>
</div>
);
if (!isOpen || !mounted || typeof document === "undefined") return null;
return createPortal(content, document.body);
}
+105
View File
@@ -0,0 +1,105 @@
"use client";
import { memo, useMemo } from "react";
import type { LyricLine } from "@/interface/music";
interface RollingLyricsProps {
lyric?: string;
translatedLyric?: string;
currentTime: number;
fallback: string;
}
function parseTimestamp(minutes: string, seconds: string, fraction = "0") {
const fractionValue = Number(fraction) / 10 ** fraction.length;
return Number(minutes) * 60 + Number(seconds) + fractionValue;
}
function parseLyricText(value?: string) {
if (!value) return [] as LyricLine[];
const result: LyricLine[] = [];
const timestampPattern = /\[(\d{1,2}):(\d{2})(?:[.:](\d{1,3}))?\]/g;
for (const sourceLine of value.split(/\r?\n/)) {
const timestamps = [...sourceLine.matchAll(timestampPattern)];
if (timestamps.length === 0) continue;
const text = sourceLine.replace(timestampPattern, "").trim();
if (!text) continue;
for (const timestamp of timestamps) {
result.push({
time: parseTimestamp(timestamp[1], timestamp[2], timestamp[3]),
text,
});
}
}
return result.sort((left, right) => left.time - right.time);
}
export function parseLrc(lyric?: string, translatedLyric?: string) {
const primary = parseLyricText(lyric);
const translated = parseLyricText(translatedLyric);
if (translated.length === 0) return primary;
return primary.map((line) => {
const matchingLine = translated.find((candidate) => Math.abs(candidate.time - line.time) < 0.08);
return matchingLine ? { ...line, translation: matchingLine.text } : line;
});
}
function RollingLyricsInner({
lyric,
translatedLyric,
currentTime,
fallback,
}: RollingLyricsProps) {
const lines = useMemo(() => parseLrc(lyric, translatedLyric), [lyric, translatedLyric]);
const activeIndex = useMemo(() => {
if (lines.length === 0) return -1;
let index = 0;
for (let cursor = 0; cursor < lines.length; cursor += 1) {
if (currentTime >= lines[cursor].time) index = cursor;
else break;
}
return index;
}, [currentTime, lines]);
if (activeIndex < 0) {
const isAlert = fallback.includes("此音乐没有播放路径") || fallback.includes("正在获取");
return (
<p className={`truncate text-xs ${isAlert ? "font-semibold text-rose-500 dark:text-rose-400" : "text-(--fg-color)/60"}`}>
{fallback}
</p>
);
}
return (
<div className="relative h-8 overflow-hidden contain-strict" aria-live="polite" aria-atomic="true">
<div
className="transition-transform duration-500 ease-out motion-reduce:transition-none will-change-transform"
style={{ transform: `translate3d(0, -${activeIndex * 2}rem, 0)` }}
>
{lines.map((line, index) => (
<div
key={`${line.time}-${index}`}
className={`flex h-8 flex-col justify-center truncate transition-opacity duration-300 motion-reduce:transition-none ${
index === activeIndex ? "opacity-100" : "opacity-24"
}`}
>
<p className="truncate text-xs font-medium text-gold" title={line.text}>
{line.text}
</p>
{line.translation && (
<p className="truncate text-[9px] text-charcoal/42 dark:text-cream/42" title={line.translation}>
{line.translation}
</p>
)}
</div>
))}
</div>
</div>
);
}
const RollingLyrics = memo(RollingLyricsInner);
export default RollingLyrics;
-422
View File
@@ -1,422 +0,0 @@
"use client";
/* eslint-disable @typescript-eslint/no-unused-vars */
import React, { useState, useEffect, useRef } from "react";
import {
Play,
Pause,
SkipForward,
SkipBack,
Volume2,
VolumeX,
ChevronUp,
ChevronDown,
Music,
Wind,
X
} from "lucide-react";
import gsap from "gsap";
import { useSysConfig } from "@/hooks/useSysConfig";
interface BgmTrack {
title: string;
artist: string;
src: string;
}
interface NoiseTrack {
name: string;
src: string;
icon?: string;
}
export default function TapeStation() {
const { configs, loading } = useSysConfig();
// 电台数据状态
const [bgmList, setBgmList] = useState<BgmTrack[]>([
{ title: "You Must Believe in Spring", artist: "Bill Evans", src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3" },
{ title: "Merry Christmas Mr. Lawrence", artist: "Ryuichi Sakamoto", src: "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" }
]);
const [noiseList, setNoiseList] = useState<NoiseTrack[]>([
{ name: "林间细雨 (Rain)", src: "https://assets.mixkit.co/active_storage/sfx/2433/2433-84.wav", icon: "rain" },
{ name: "白噪风声 (Wind)", src: "https://assets.mixkit.co/active_storage/sfx/2544/2544-84.wav", icon: "wind" }
]);
// 从公共系统配置加载真实配置
useEffect(() => {
if (!loading && configs.length > 0) {
const cfg = configs.find(c => c.configKey === "now.content.json");
if (cfg && cfg.configValue) {
try {
const parsed = JSON.parse(cfg.configValue);
if (parsed.radio) {
if (parsed.radio.bgmList && parsed.radio.bgmList.length > 0) {
setBgmList(parsed.radio.bgmList);
}
if (parsed.radio.noiseList && parsed.radio.noiseList.length > 0) {
setNoiseList(parsed.radio.noiseList);
}
}
} catch (e) {
console.warn("Failed to parse radio configurations from now.content.json", e);
}
}
}
}, [configs, loading]);
// 播放状态
const [isOpen, setIsOpen] = useState(false); // 控制面板是否展开
const [isPlaying, setIsPlaying] = useState(false);
const [currentBgmIdx, setCurrentBgmIdx] = useState(0);
const [activeNoiseIdx, setActiveNoiseIdx] = useState<number | null>(null); // 当前播放的白噪音索引,null表示无
// 音量控制 (0 ~ 1)
const [bgmVolume, setBgmVolume] = useState(0.5);
const [noiseVolume, setNoiseVolume] = useState(0.4);
const [isMuted, setIsMuted] = useState(false);
// 音频实例 Ref
const bgmAudioRef = useRef<HTMLAudioElement | null>(null);
const noiseAudioRef = useRef<HTMLAudioElement | null>(null);
// 磁带转轴 DOM Ref
const leftReelRef = useRef<HTMLDivElement>(null);
const rightReelRef = useRef<HTMLDivElement>(null);
const gsapTweenRef = useRef<gsap.core.Tween | null>(null);
// ==================== 播放操作逻辑 ====================
const handleTogglePlay = () => {
setIsPlaying(!isPlaying);
};
const handleNext = () => {
setCurrentBgmIdx((prev) => (prev + 1) % bgmList.length);
};
const handlePrev = () => {
setCurrentBgmIdx((prev) => (prev - 1 + bgmList.length) % bgmList.length);
};
// 1. 初始化及音频事件绑定
useEffect(() => {
bgmAudioRef.current = new Audio();
noiseAudioRef.current = new Audio();
// 默认设置
bgmAudioRef.current.loop = false;
noiseAudioRef.current.loop = true; // 噪音通常是无限循环循环播放
// 歌曲播放结束后自动下一首
const handleBgmEnded = () => {
handleNext();
};
bgmAudioRef.current.addEventListener("ended", handleBgmEnded);
return () => {
if (bgmAudioRef.current) {
bgmAudioRef.current.pause();
bgmAudioRef.current.removeEventListener("ended", handleBgmEnded);
}
if (noiseAudioRef.current) {
noiseAudioRef.current.pause();
}
};
}, [bgmList]);
// 2. 监听歌曲或静音状态变化同步到原生音频
useEffect(() => {
if (bgmAudioRef.current && bgmList[currentBgmIdx]) {
const wasPlaying = isPlaying;
bgmAudioRef.current.src = bgmList[currentBgmIdx].src;
bgmAudioRef.current.volume = isMuted ? 0 : bgmVolume;
if (wasPlaying) {
bgmAudioRef.current.play().catch(e => console.warn("Auto-play blocked", e));
}
}
}, [currentBgmIdx, bgmList]);
useEffect(() => {
if (bgmAudioRef.current) {
bgmAudioRef.current.volume = isMuted ? 0 : bgmVolume;
}
}, [bgmVolume, isMuted]);
// 3. 监听白噪音源及音量变化
useEffect(() => {
if (noiseAudioRef.current) {
if (activeNoiseIdx !== null && noiseList[activeNoiseIdx]) {
noiseAudioRef.current.src = noiseList[activeNoiseIdx].src;
noiseAudioRef.current.volume = isMuted ? 0 : noiseVolume;
if (isPlaying) {
noiseAudioRef.current.play().catch(e => console.warn("Noise play blocked", e));
}
} else {
noiseAudioRef.current.pause();
}
}
}, [activeNoiseIdx, noiseList, isPlaying]);
useEffect(() => {
if (noiseAudioRef.current) {
noiseAudioRef.current.volume = isMuted ? 0 : noiseVolume;
}
}, [noiseVolume, isMuted]);
// ==================== GSAP 磁带物理动画控制 ====================
const startReelAnimation = () => {
if (!gsapTweenRef.current) {
// 左右两个齿轮轴匀速无限旋转旋转
const targets = [leftReelRef.current, rightReelRef.current].filter(Boolean);
if (targets.length > 0) {
gsapTweenRef.current = gsap.to(targets, {
rotation: "+=360",
repeat: -1,
duration: 3,
ease: "none",
paused: true
});
}
}
if (gsapTweenRef.current) {
gsapTweenRef.current.play();
// 让播放速度缓动回 1 (代表重新启动)
gsap.to(gsapTweenRef.current, { timeScale: 1, duration: 0.5, ease: "power2.out" });
}
};
const stopReelAnimation = () => {
if (gsapTweenRef.current) {
// 缓动动画播放速度到 0 (实现阻尼减速回弹物理效果)
gsap.to(gsapTweenRef.current, {
timeScale: 0,
duration: 0.8,
ease: "power2.out",
onComplete: () => {
gsapTweenRef.current?.pause();
}
});
}
};
// 4. 监听全局播放开关
useEffect(() => {
if (isPlaying) {
if (bgmAudioRef.current && bgmAudioRef.current.src) {
bgmAudioRef.current.play().catch(e => {
console.warn("Bgm play failed", e);
setIsPlaying(false);
});
}
if (noiseAudioRef.current && activeNoiseIdx !== null && noiseAudioRef.current.src) {
noiseAudioRef.current.play().catch(e => console.warn("Noise play failed", e));
}
// 启动 GSAP 磁带齿轮旋转动画
startReelAnimation();
} else {
if (bgmAudioRef.current) bgmAudioRef.current.pause();
if (noiseAudioRef.current) noiseAudioRef.current.pause();
// 阻尼停止动画
stopReelAnimation();
}
}, [isPlaying]);
const selectNoise = (idx: number) => {
if (activeNoiseIdx === idx) {
setActiveNoiseIdx(null); // 关闭噪音
} else {
setActiveNoiseIdx(idx);
}
};
return (
<div className="fixed bottom-6 right-6 z-[999] flex flex-col items-end">
{/* 1. 复古磁带播放大面板 (isOpen 为真时以弹窗动画拉伸展开) */}
<div
className={`bg-[#F7F5F0] dark:bg-[#1C221E] border border-charcoal/10 dark:border-white/10 rounded-3xl p-5 shadow-[0_15px_40px_rgba(0,0,0,0.08)] w-[320px] mb-3 overflow-hidden select-none transition-all duration-500 ease-out origin-bottom-right ${
isOpen ? "opacity-100 scale-100 translate-y-0" : "opacity-0 scale-75 translate-y-10 pointer-events-none h-0 p-0 mb-0"
}`}
>
{/* 顶部拟真液晶状态显示屏 (LCD Screen) */}
<div className="bg-[#E2EADA] dark:bg-[#2C3830] border border-charcoal/10 dark:border-black/30 rounded-xl px-4 py-2 mb-4 font-mono shadow-[inset_0_2px_5px_rgba(0,0,0,0.05)]">
<div className="flex justify-between items-center text-[10px] text-charcoal/60 dark:text-cream/50 mb-1 select-none">
<span className="flex items-center gap-1 font-bold">
<span className={`w-2 h-2 rounded-full ${isPlaying ? "bg-red-500 animate-pulse" : "bg-charcoal/30 dark:bg-white/20"}`} />
{isPlaying ? "PLAYING" : "PAUSED"}
</span>
<span>CH: DUAL-MIX</span>
</div>
{/* 跑马灯歌名 */}
<div className="w-full overflow-hidden relative h-5 select-none">
<div className="absolute whitespace-nowrap text-xs font-bold text-charcoal/90 dark:text-cream/90 animate-marquee flex gap-2">
<span>{bgmList[currentBgmIdx]?.title} - {bgmList[currentBgmIdx]?.artist}</span>
<span className="pl-8">{bgmList[currentBgmIdx]?.title} - {bgmList[currentBgmIdx]?.artist}</span>
</div>
</div>
</div>
{/* 2. 拟物化磁带本身 (Physical Cassette Tape Body) */}
<div className="relative bg-[#DDD7CB] dark:bg-[#2F3832] border border-charcoal/15 dark:border-white/5 rounded-2xl p-4 h-[120px] flex flex-col justify-between shadow-[0_6px_12px_rgba(0,0,0,0.03)] mb-4">
{/* 磁带顶部标纸 */}
<div className="h-2 w-full bg-[#C8C0AF] dark:bg-[#3D4741] rounded-full opacity-60 mb-2" />
{/* 磁带卷核心透视槽 */}
<div className="grow bg-[#B2A895] dark:bg-[#1E2521] border border-charcoal/10 dark:border-black/50 rounded-xl flex items-center justify-around relative px-6 overflow-hidden">
{/* 左右齿轮转轴 (GSAP 驱动) */}
<div
ref={leftReelRef}
className="w-10 h-10 rounded-full border-[3px] border-dashed border-[#DDD7CB] dark:border-[#2F3832] bg-[#F7F5F0] dark:bg-[#1C221E] shadow-sm flex items-center justify-center relative origin-center"
>
<div className="w-3 h-3 rounded-full bg-charcoal/80 dark:bg-white/80" />
</div>
{/* 中间半透明磁带卷轴连接线条 */}
<div className="absolute top-1/2 left-[20%] right-[20%] h-[1px] bg-charcoal/20 dark:bg-white/10 -translate-y-1/2 pointer-events-none" />
<div
ref={rightReelRef}
className="w-10 h-10 rounded-full border-[3px] border-dashed border-[#DDD7CB] dark:border-[#2F3832] bg-[#F7F5F0] dark:bg-[#1C221E] shadow-sm flex items-center justify-center relative origin-center"
>
<div className="w-3 h-3 rounded-full bg-charcoal/80 dark:bg-white/80" />
</div>
</div>
{/* 磁带底部螺丝孔与拟真凸起 */}
<div className="flex justify-between items-center text-[8px] font-mono text-charcoal/30 dark:text-white/20 mt-2 select-none px-2">
<span>A-SIDE</span>
<div className="flex gap-2">
<span className="w-1.5 h-1.5 rounded-full bg-charcoal/20 dark:bg-white/10" />
<span className="w-1.5 h-1.5 rounded-full bg-charcoal/20 dark:bg-white/10" />
</div>
<span>TYPE I</span>
</div>
</div>
{/* 3. 背景音乐操作物理按键 (Bgm Control Buttons) */}
<div className="flex items-center justify-between mb-4 px-2">
<button
onClick={handlePrev}
className="w-10 h-10 rounded-full bg-white dark:bg-[#27302A] border border-charcoal/10 dark:border-white/5 flex items-center justify-center shadow-sm hover:scale-105 active:scale-95 transition-all cursor-pointer shrink-0"
style={{ color: "var(--accent-color)" }}
title="上一首"
>
<SkipBack className="w-4 h-4 fill-current" />
</button>
<button
onClick={handleTogglePlay}
className="w-12 h-12 rounded-full text-white flex items-center justify-center shadow-md hover:scale-105 active:scale-95 transition-all cursor-pointer shrink-0"
style={{ backgroundColor: "var(--accent-color)" }}
title={isPlaying ? "暂停" : "播放"}
>
{isPlaying ? (
<Pause className="w-5 h-5 fill-current" />
) : (
<Play className="w-5 h-5 fill-current translate-x-0.5" />
)}
</button>
<button
onClick={handleNext}
className="w-10 h-10 rounded-full bg-white dark:bg-[#27302A] border border-charcoal/10 dark:border-white/5 flex items-center justify-center shadow-sm hover:scale-105 active:scale-95 transition-all cursor-pointer shrink-0"
style={{ color: "var(--accent-color)" }}
title="下一首"
>
<SkipForward className="w-4 h-4 fill-current" />
</button>
</div>
{/* 4. 双音轨混音调节滑块 (Dual Sound mixers) */}
<div className="space-y-3 bg-[#EDEAE3] dark:bg-[#252E28] p-3 rounded-2xl border border-charcoal/5 dark:border-white/5 text-xs">
{/* 音乐音量 */}
<div className="flex items-center gap-2">
<Music className="w-3.5 h-3.5 text-gold shrink-0" />
<span className="w-8 font-mono text-[10px] text-charcoal/50 dark:text-cream/50 select-none">BGM</span>
<input
type="range"
min="0"
max="1"
step="0.05"
value={bgmVolume}
onChange={(e) => setBgmVolume(parseFloat(e.target.value))}
style={{ accentColor: "var(--accent-color)" }}
className="flex-1 h-1 rounded-full cursor-pointer bg-charcoal/10 dark:bg-white/10"
/>
<span className="w-7 font-mono text-[9px] text-right text-charcoal/60 dark:text-cream/60 select-none">{Math.round(bgmVolume * 100)}%</span>
</div>
{/* 环境声选择与音量 */}
<div className="flex items-center gap-2">
<Wind className="w-3.5 h-3.5 text-gold shrink-0" />
<span className="w-8 font-mono text-[10px] text-charcoal/50 dark:text-cream/50 select-none">WIND</span>
<input
type="range"
min="0"
max="1"
step="0.05"
value={noiseVolume}
onChange={(e) => setNoiseVolume(parseFloat(e.target.value))}
disabled={activeNoiseIdx === null}
style={{ accentColor: "var(--accent-color)" }}
className="flex-1 h-1 rounded-full cursor-pointer bg-charcoal/10 dark:bg-white/10 disabled:opacity-40"
/>
<span className="w-7 font-mono text-[9px] text-right text-charcoal/60 dark:text-cream/60 select-none">{activeNoiseIdx === null ? "OFF" : `${Math.round(noiseVolume * 100)}%`}</span>
</div>
{/* 环境音轨切换标签 */}
<div className="flex flex-wrap gap-1.5 pt-1.5 border-t border-charcoal/5 dark:border-white/5 select-none">
{noiseList.map((noise, idx) => (
<button
key={idx}
onClick={() => selectNoise(idx)}
className={`px-2 py-1 rounded-lg text-[9px] font-bold tracking-wide transition-all cursor-pointer flex items-center gap-1 border ${
activeNoiseIdx === idx
? "bg-[#2F3832] dark:bg-[#DDD7CB] text-[#DDD7CB] dark:text-[#1E2521] border-transparent shadow-sm"
: "bg-white/60 dark:bg-white/5 text-charcoal/60 dark:text-cream/60 border-charcoal/10 dark:border-white/10 hover:bg-white/90 dark:hover:bg-white/10"
}`}
>
<span className="w-1.5 h-1.5 rounded-full bg-current" />
<span>{noise.name}</span>
</button>
))}
</div>
</div>
</div>
{/* 2. 悬浮的磁带触发球 (Tape Trigger Sphere) */}
<button
onClick={() => setIsOpen(!isOpen)}
className="w-12 h-12 rounded-full bg-[#F7F5F0] dark:bg-[#202522] border border-charcoal/10 dark:border-white/10 shadow-[0_4px_16px_rgba(0,0,0,0.06)] hover:shadow-[0_8px_24px_rgba(0,0,0,0.12)] flex items-center justify-center text-charcoal/70 dark:text-cream/70 hover:scale-105 active:scale-95 transition-all duration-300 relative group cursor-pointer"
title="治愈音乐电台"
>
{/* 指示光标 */}
<span className={`absolute -top-0.5 -right-0.5 w-3 h-3 rounded-full border-2 border-white dark:border-charcoal ${
isPlaying ? "bg-red-500 animate-ping" : "bg-charcoal/30 dark:bg-white/20"
}`} />
{isOpen ? (
<X className="w-5 h-5 text-charcoal/70 dark:text-cream/70" />
) : (
<Music className="w-5 h-5 text-gold animate-[bounce_3s_infinite]" />
)}
</button>
<style jsx global>{`
@keyframes marquee {
0% { transform: translate3d(0, 0, 0); }
100% { transform: translate3d(-50%, 0, 0); }
}
.animate-marquee {
animation: marquee 16s linear infinite;
}
.animate-marquee:hover {
animation-play-state: paused;
}
`}</style>
</div>
);
}
+10 -13
View File
@@ -1,19 +1,16 @@
"use client";
import { useEffect } from "react";
import { getPublicConfig } from "@/api/config";
import { useSysConfig } from "@/hooks/useSysConfig";
export default function ThemeApplier() {
useEffect(() => {
async function fetchAndApplyTheme() {
try {
const res = await getPublicConfig();
const data = res.data;
if (data.code !== 200 || !data.data) return;
const { configs } = useSysConfig();
const list = data.data as any[];
useEffect(() => {
function applyTheme() {
try {
const configMap: Record<string, string> = {};
list.forEach((item) => {
configs.forEach((item) => {
configMap[item.configKey] = item.configValue;
});
@@ -163,13 +160,13 @@ export default function ThemeApplier() {
}
styleElement.innerHTML = css;
} catch (err) {
console.warn("ThemeApplier dynamic loading failed:", err);
} catch (error) {
console.warn("主题配置格式无效:", error instanceof Error ? error.message : "unknown error");
}
}
fetchAndApplyTheme();
}, []);
applyTheme();
}, [configs]);
return null;
}
@@ -0,0 +1,173 @@
"use client";
import React, { useState } from "react";
import { musicIcons } from "@/icon/music";
import type { TrackDetail } from "@/interface/music";
import AnimatedList from "../AnimatedList";
const {
heart: HeartIcon,
play: PlayIcon,
} = musicIcons;
const DefaultVinylCover = () => (
<div className="size-full bg-radial from-[#22232a] to-[#0f1015] flex items-center justify-center relative shadow-inner select-none pointer-events-none">
{/* 唱片的同心圆纹路 */}
<div className="absolute inset-1 rounded-full border border-white/5" />
<div className="absolute inset-2 rounded-full border border-white/5" />
<div className="absolute inset-3.5 rounded-full border border-white/5" />
{/* 红心胶心 */}
<div className="size-3 rounded-full bg-rose-500 flex items-center justify-center shadow-xs">
<div className="size-1 rounded-full bg-black/60" />
</div>
</div>
);
const TrackCover = ({ coverUrl, title }: { coverUrl?: string; title: string }) => {
const [hasError, setHasError] = useState(false);
if (coverUrl && !hasError) {
return (
// eslint-disable-next-line @next/next/no-img-element
<img
src={coverUrl}
alt={title}
className="size-full object-cover"
onError={() => setHasError(true)}
/>
);
}
return <DefaultVinylCover />;
};
interface DrawerFavoritesTabProps {
favorites: TrackDetail[];
currentTrack: TrackDetail;
isResolvingTrack: boolean;
onPlayFavorites?: () => void;
onClearFavorites?: () => void;
onToggleFavorite?: (track: TrackDetail) => void;
onPlayFavoriteTrack?: (track: TrackDetail) => void;
onSwitchToSearch: () => void;
}
export default function DrawerFavoritesTab({
favorites,
currentTrack,
isResolvingTrack,
onPlayFavorites,
onClearFavorites,
onToggleFavorite,
onPlayFavoriteTrack,
onSwitchToSearch,
}: DrawerFavoritesTabProps) {
return (
<div className="grow min-h-0 flex flex-col space-y-3 overscroll-contain">
{favorites.length > 0 ? (
<>
<div className="flex items-center justify-between px-1 py-1 shrink-0 text-xs">
<span className="text-(--fg-color)/60 font-medium">
共收藏 <strong className="text-(--accent-color)">{favorites.length}</strong> 首曲目
</span>
<div className="flex items-center gap-2">
{onPlayFavorites && (
<button
type="button"
onClick={onPlayFavorites}
className="px-3 py-1 rounded-xl bg-(--accent-color) text-white font-semibold flex items-center gap-1 hover:scale-105 active:scale-95 transition-all cursor-pointer shadow-xs"
>
<PlayIcon size={13} weight="fill" />
<span>全部播放</span>
</button>
)}
{onClearFavorites && (
<button
type="button"
onClick={onClearFavorites}
className="px-3 py-1 rounded-xl bg-(--fg-color)/6 hover:bg-red-500/10 text-(--fg-color)/60 hover:text-red-500 font-medium transition-all cursor-pointer border border-(--border-line-color) hover:border-red-500/20"
>
清空收藏
</button>
)}
</div>
</div>
<AnimatedList
items={favorites}
showGradients={false}
enableArrowNavigation={false}
getItemKey={(track, index) => `fav-${track.source}-${track.id}-${index}`}
renderItem={(track, index) => {
const isCurrent = currentTrack.id === track.id && currentTrack.source === track.source;
return (
<div
onClick={(e) => {
e.stopPropagation();
if (isResolvingTrack) return;
onPlayFavoriteTrack?.(track);
}}
className={`group relative z-10 flex w-full items-center gap-3.5 rounded-2xl px-4 py-3 text-left transition-colors duration-150 border cursor-pointer ${
isCurrent
? "bg-(--accent-color)/12 text-(--fg-color) font-medium border-(--accent-color)/35 shadow-sm"
: "bg-(--fg-color)/4 hover:bg-(--fg-color)/8 border-(--border-line-color)"
}`}
>
<span className="w-5 text-center text-xs font-mono text-(--fg-color)/40 group-hover:text-(--fg-color)/70 shrink-0">
{String(index + 1).padStart(2, "0")}
</span>
<div className="relative size-11 shrink-0 rounded-xl overflow-hidden bg-(--fg-color)/10 border border-(--border-line-color) shadow-sm">
<TrackCover coverUrl={track.cover} title={track.title} />
</div>
<div className="min-w-0 grow">
<p className={`truncate text-sm ${isCurrent ? "text-(--fg-color) font-semibold" : "text-(--fg-color)/90"}`}>
{track.title}
</p>
<p className="truncate text-xs text-(--fg-color)/60 mt-0.5">
{track.artist} {track.album ? `• ${track.album}` : ""}
</p>
</div>
{onToggleFavorite && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onToggleFavorite(track);
}}
className="p-2 rounded-xl text-rose-500 bg-rose-500/10 hover:bg-rose-500/20 transition-all shrink-0 cursor-pointer border border-rose-500/20"
title="取消收藏"
>
<HeartIcon size={15} weight="fill" />
</button>
)}
</div>
);
}}
/>
</>
) : (
<div className="h-full flex flex-col items-center justify-center text-center p-8 space-y-3">
<div className="size-16 rounded-full bg-rose-500/10 border border-rose-500/20 flex items-center justify-center text-rose-500">
<HeartIcon size={32} weight="regular" />
</div>
<div>
<h4 className="text-sm font-semibold text-(--fg-color)">暂无收藏歌曲</h4>
<p className="text-xs text-(--fg-color)/50 mt-1">
在播放队列或搜索列表中点击心形图标,将喜爱的声音加入私藏
</p>
</div>
<button
type="button"
onClick={onSwitchToSearch}
className="px-4 py-2 rounded-2xl bg-(--accent-color) text-white text-xs font-semibold shadow-md transition-all hover:scale-105 active:scale-95 cursor-pointer mt-2"
>
前往在线搜索
</button>
</div>
)}
</div>
);
}
@@ -0,0 +1,186 @@
"use client";
import React, { useState } from "react";
import { musicIcons } from "@/icon/music";
import { fetchPlaylist, parsePlaylistUrl, MusicApiError } from "@/api/music";
import type { MusicSource, TrackDetail } from "@/interface/music";
const {
loading: LoadingIcon,
radio: RadioIcon,
plus: PlusIcon,
folder: FolderIcon,
} = musicIcons;
interface DrawerImportTabProps {
selectedSource: MusicSource;
onImportPlaylist?: (tracks: TrackDetail[], targetPlaylistId?: string) => void;
playlists?: { id: string; name: string }[];
}
export default function DrawerImportTab({
selectedSource,
onImportPlaylist,
playlists = [],
}: DrawerImportTabProps) {
const [playlistInput, setPlaylistInput] = useState("");
const [isImporting, setIsImporting] = useState(false);
const [importMessage, setImportMessage] = useState("");
const [targetPlaylistId, setTargetPlaylistId] = useState("create_new");
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const handleImport = async (inputStr?: string) => {
const query = (inputStr ?? playlistInput).trim();
if (!query || isImporting) return;
const parsed = parsePlaylistUrl(query, selectedSource);
if (!parsed) {
setImportMessage("未识别到有效的歌单链接或ID,请检查格式后重试");
return;
}
setIsImporting(true);
setImportMessage(`正在解析 ${parsed.source} 歌单 (${parsed.id})...`);
try {
const tracks = await fetchPlaylist(parsed.id, parsed.source);
if (onImportPlaylist) {
onImportPlaylist(tracks, targetPlaylistId);
}
setImportMessage(`成功解析并导入 ${tracks.length} 首曲目!`);
setPlaylistInput("");
} catch (error) {
setImportMessage(error instanceof MusicApiError ? error.message : "歌单导入失败,请检查歌单公开权限或网络链接");
} finally {
setIsImporting(false);
}
};
return (
<div className="grow min-h-0 flex flex-col space-y-4 overflow-y-auto pr-1 overscroll-contain">
<div className="p-4 rounded-2xl bg-(--accent-color)/10 border border-(--accent-color)/20 text-xs text-(--fg-color) space-y-1.5">
<p className="font-semibold text-(--accent-color) flex items-center gap-1.5">
<RadioIcon size={16} /> 网易云歌单导入教程
</p>
<div className="text-(--fg-color)/75 leading-relaxed space-y-1 text-[11px]">
<p>1. 打开网易云音乐,进入您要导入的公开歌单或「我喜欢的音乐」</p>
<p>2. 复制浏览器链接(或提取其中的数字 ID)</p>
<p>3. 粘贴到下方输入框中,选择要导入的目标歌单文件夹,点击「一键导入」即可</p>
</div>
</div>
<div className="space-y-2">
<label className="text-xs font-semibold text-(--fg-color)/80 block">
选择导入至哪个文件夹歌单
</label>
<div className="relative">
{/* 自定义触发按钮:在激活和悬停时引入高端的主色调响应及圆润边框 */}
<button
type="button"
onClick={() => setIsDropdownOpen((prev) => !prev)}
onBlur={() => setTimeout(() => setIsDropdownOpen(false), 200)}
className={`w-full px-4 py-2.5 rounded-2xl bg-(--fg-color)/4 border text-xs text-(--fg-color) text-left transition-all cursor-pointer flex items-center justify-between ${
isDropdownOpen
? "border-(--accent-color)/60 shadow-xs bg-(--fg-color)/6"
: "border-(--border-line-color) hover:border-(--fg-color)/20 hover:bg-(--fg-color)/6"
}`}
>
<span className="truncate font-medium flex items-center gap-1.5">
{targetPlaylistId === "create_new" ? (
<>
<PlusIcon size={14} className="text-(--accent-color)" />
<span>自动创建新的歌单文件夹</span>
</>
) : (
<>
<FolderIcon size={14} className="text-(--accent-color)" />
<span>导入并追加到已有歌单:{playlists.find((p) => p.id === targetPlaylistId)?.name || ""}</span>
</>
)}
</span>
<svg
className={`size-4 fill-current text-(--fg-color)/40 transition-transform duration-300 ${
isDropdownOpen ? "rotate-180 text-(--accent-color)" : ""
}`}
viewBox="0 0 20 20"
>
<path d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" />
</svg>
</button>
{/* 高定下拉浮层选项列表:使用高对比反差底色,双层软阴影,以及 iOS 风格圆角子项布局 */}
{isDropdownOpen && (
<div className="absolute left-0 right-0 mt-2 max-h-56 overflow-y-auto rounded-2xl bg-white/95 dark:bg-[#161720]/95 border border-zinc-200/60 dark:border-zinc-800/60 shadow-[0_12px_36px_rgba(0,0,0,0.12)] dark:shadow-[0_12px_36px_rgba(0,0,0,0.45)] z-50 py-2 backdrop-blur-lg animate-in fade-in slide-in-from-top-1 duration-150">
<div
onClick={() => {
setTargetPlaylistId("create_new");
setIsDropdownOpen(false);
}}
className={`px-3 mx-1.5 py-2 rounded-xl text-xs cursor-pointer transition-all flex items-center gap-2 ${
targetPlaylistId === "create_new"
? "bg-(--accent-color)/10 text-(--accent-color) font-bold"
: "text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800/60 hover:text-zinc-950 dark:hover:text-white"
}`}
>
<PlusIcon size={14} className={targetPlaylistId === "create_new" ? "text-(--accent-color)" : "text-zinc-400"} />
<span>自动创建新的歌单文件夹</span>
</div>
<div className="h-px bg-zinc-100 dark:bg-zinc-800/50 my-1 mx-3" />
{playlists.map((pl) => (
<div
key={pl.id}
onClick={() => {
setTargetPlaylistId(pl.id);
setIsDropdownOpen(false);
}}
className={`px-3 mx-1.5 py-2 rounded-xl text-xs cursor-pointer transition-all flex items-center gap-2 ${
targetPlaylistId === pl.id
? "bg-(--accent-color)/10 text-(--accent-color) font-bold"
: "text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-800/60 hover:text-zinc-950 dark:hover:text-white"
}`}
>
<FolderIcon size={14} className={targetPlaylistId === pl.id ? "text-(--accent-color)" : "text-zinc-400"} />
<span className="truncate">导入并追加到已有歌单:{pl.name}</span>
</div>
))}
</div>
)}
</div>
</div>
<div className="space-y-2">
<label className="text-xs font-semibold text-(--fg-color)/80 block">
粘贴网易云歌单链接或歌单 ID
</label>
<div className="flex items-center gap-2">
<input
type="text"
value={playlistInput}
onChange={(e) => setPlaylistInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") void handleImport();
}}
placeholder="例如: https://music.163.com/#/playlist?id=7101058132 或 纯数字ID"
className="grow px-4 py-2.5 rounded-2xl bg-(--fg-color)/6 border border-(--border-line-color) text-xs text-(--fg-color) placeholder-(--fg-color)/40 focus:outline-hidden focus:border-(--accent-color) transition-all"
/>
<button
type="button"
onClick={() => void handleImport()}
disabled={isImporting || !playlistInput.trim()}
className="px-5 py-2.5 rounded-2xl bg-(--accent-color) text-white text-xs font-semibold shadow-md transition-all hover:scale-105 active:scale-95 disabled:opacity-50 cursor-pointer shrink-0"
>
{isImporting ? <LoadingIcon size={16} className="animate-spin" /> : "一键导入"}
</button>
</div>
</div>
{importMessage && (
<div className="p-3.5 rounded-2xl bg-(--fg-color)/6 border border-(--border-line-color) text-xs text-(--fg-color)/90 font-medium flex items-center gap-2 animate-in fade-in duration-200">
{isImporting && <LoadingIcon size={16} className="animate-spin text-(--accent-color) shrink-0" />}
<span>{importMessage}</span>
</div>
)}
</div>
);
}
@@ -0,0 +1,213 @@
"use client";
import React, { useState, useEffect } from "react";
import { musicIcons } from "@/icon/music";
import type { TrackDetail } from "@/interface/music";
import AnimatedList from "../AnimatedList";
const {
heart: HeartIcon,
music: MusicIcon,
trash: TrashIcon,
waveform: WaveformIcon,
} = musicIcons;
interface DrawerPlaylistTabProps {
playlist: TrackDetail[];
currentIndex: number;
isPlaying: boolean;
isResolvingTrack: boolean;
onSelectTrack: (index: number) => void;
onRemoveTrack?: (index: number) => void;
onToggleFavorite?: (track: TrackDetail) => void;
isFavorite?: (track: TrackDetail) => boolean;
}
const DefaultVinylCover = () => (
<div className="size-full bg-radial from-[#22232a] to-[#0f1015] flex items-center justify-center relative shadow-inner select-none pointer-events-none">
{/* 唱片的同心圆纹路 */}
<div className="absolute inset-1 rounded-full border border-white/5" />
<div className="absolute inset-2 rounded-full border border-white/5" />
<div className="absolute inset-3.5 rounded-full border border-white/5" />
{/* 红心胶心 */}
<div className="size-3 rounded-full bg-rose-500 flex items-center justify-center shadow-xs">
<div className="size-1 rounded-full bg-black/60" />
</div>
</div>
);
const TrackCover = ({ coverUrl, title }: { coverUrl?: string; title: string }) => {
const [hasError, setHasError] = useState(false);
if (coverUrl && !hasError) {
return (
// eslint-disable-next-line @next/next/no-img-element
<img
src={coverUrl}
alt={title}
className="size-full object-cover"
onError={() => setHasError(true)}
/>
);
}
return <DefaultVinylCover />;
};
export default function DrawerPlaylistTab({
playlist,
currentIndex,
isPlaying,
isResolvingTrack,
onSelectTrack,
onRemoveTrack,
onToggleFavorite,
isFavorite,
}: DrawerPlaylistTabProps) {
const [visibleLimit, setVisibleLimit] = useState(25);
const [showAll, setShowAll] = useState(false);
// 折叠机制:打开时只展示当前播放歌曲的前 5 首到后面 visibleLimit 首,彻底免去大队列实例化 DOM 造成的卡顿
const startIdx = showAll ? 0 : Math.max(0, currentIndex - 5);
const visibleTracks = playlist.slice(startIdx, startIdx + visibleLimit);
useEffect(() => {
const relativeIndex = currentIndex - startIdx;
if (relativeIndex >= visibleLimit) {
setVisibleLimit(relativeIndex + 25);
}
}, [currentIndex, visibleLimit, startIdx]);
const handlePlaylistScroll = (e: React.UIEvent<HTMLDivElement>) => {
const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
if (scrollHeight - scrollTop - clientHeight < 300) {
if (visibleLimit < playlist.length - startIdx) {
setVisibleLimit((prev) => Math.min(prev + 25, playlist.length - startIdx));
}
}
};
if (playlist.length === 0) {
return (
<div className="grow flex flex-col items-center justify-center p-8 text-center space-y-3">
<div className="size-12 rounded-full bg-(--fg-color)/4 border border-(--border-line-color)/30 flex items-center justify-center text-(--fg-color)/30">
<MusicIcon size={22} />
</div>
<div className="space-y-1">
<p className="text-xs font-semibold text-(--fg-color)/60">暂无歌曲播放</p>
<p className="text-[11px] text-(--fg-color)/40 leading-relaxed">
您可以通过【在线搜索】或【歌单导入】来添加歌曲到播放队列
</p>
</div>
</div>
);
}
return (
<div className="grow min-h-0 flex flex-col gap-2">
{startIdx > 0 && !showAll && (
<div className="flex justify-center shrink-0 px-1">
<button
type="button"
onClick={() => setShowAll(true)}
className="w-full py-2 rounded-2xl bg-(--fg-color)/4 hover:bg-(--fg-color)/8 border border-(--border-line-color)/40 text-center text-xs font-bold text-(--accent-color) transition-all cursor-pointer active:scale-99"
>
显示更早的 {startIdx} 首已播曲目
</button>
</div>
)}
<AnimatedList
items={visibleTracks}
showGradients={false}
enableArrowNavigation={false}
getItemKey={(track, index) => `${track.source}-${track.id}-${startIdx + index}`}
onScroll={handlePlaylistScroll}
renderItem={(track, index) => {
const globalIndex = startIdx + index;
const isCurrent = globalIndex === currentIndex;
return (
<div
onClick={(e) => {
e.stopPropagation();
if (isResolvingTrack) return;
onSelectTrack(globalIndex);
}}
className={`group relative z-10 flex w-full items-center gap-3.5 rounded-2xl px-4 py-3 text-left transition-colors duration-150 border ${
isResolvingTrack ? "pointer-events-none opacity-60" : "cursor-pointer"
} ${
isCurrent
? "bg-(--accent-color)/12 text-(--fg-color) font-medium border-(--accent-color)/35 shadow-sm"
: "bg-(--fg-color)/4 hover:bg-(--fg-color)/8 border-(--border-line-color)"
}`}
>
<span className="w-5 text-center text-xs font-mono text-(--fg-color)/40 group-hover:text-(--fg-color)/70 shrink-0">
{isCurrent ? (
<MusicIcon size={16} weight="fill" className="text-(--accent-color) mx-auto" />
) : (
String(globalIndex + 1).padStart(2, "0")
)}
</span>
<div className="relative size-11 shrink-0 rounded-xl overflow-hidden bg-(--fg-color)/10 border border-(--border-line-color) shadow-sm">
<TrackCover coverUrl={track.cover} title={track.title} />
</div>
<div className="min-w-0 grow">
<div className="flex items-center gap-2">
<p className={`truncate text-sm ${isCurrent ? "text-(--fg-color) font-semibold" : "text-(--fg-color)/90"}`}>
{track.title}
</p>
</div>
<p className="truncate text-xs text-(--fg-color)/60 mt-0.5">
{track.artist} {track.album ? `• ${track.album}` : ""}
</p>
</div>
{isCurrent && isPlaying && (
<WaveformIcon size={18} className="shrink-0 text-(--accent-color) animate-pulse" />
)}
{onToggleFavorite && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onToggleFavorite(track);
}}
className={`p-2 rounded-xl transition-all shrink-0 cursor-pointer border border-transparent ${
isFavorite?.(track)
? "text-rose-500 bg-rose-500/10 border-rose-500/20"
: "opacity-0 group-hover:opacity-100 bg-(--fg-color)/6 text-(--fg-color)/50 hover:text-rose-500 hover:bg-rose-500/10"
}`}
title={isFavorite?.(track) ? "取消收藏" : "加入收藏"}
>
<HeartIcon size={15} weight={isFavorite?.(track) ? "fill" : "regular"} />
</button>
)}
{onRemoveTrack && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
if (isResolvingTrack) return;
onRemoveTrack(globalIndex);
}}
className="opacity-0 group-hover:opacity-100 p-2 rounded-xl bg-(--fg-color)/6 text-(--fg-color)/50 hover:text-red-500 hover:bg-red-500/10 transition-all shrink-0 cursor-pointer border border-transparent hover:border-red-500/20"
title="从播放队列中移除"
>
<TrashIcon size={15} />
</button>
)}
</div>
);
}}
/>
{playlist.length > visibleLimit && (
<div className="py-2 text-center text-[11px] text-(--fg-color)/50 font-mono shrink-0">
已展现 {visibleLimit} / {playlist.length} 首 (向下滚动载入更多)
</div>
)}
</div>
);
}
@@ -0,0 +1,483 @@
"use client";
import React, { useState, useRef } from "react";
import { musicIcons } from "@/icon/music";
import type { TrackDetail, MusicSource } from "@/interface/music";
import type { PlaylistFolder } from "@/hooks/usePlayerPlaylists";
const {
music: MusicIcon,
trash: TrashIcon,
waveform: WaveformIcon,
folder: FolderIcon,
edit: EditIcon,
plus: PlusIcon,
play: PlayIcon,
caretLeft: CaretLeftIcon,
heart: HeartIcon,
} = musicIcons;
interface DrawerPlaylistsTabProps {
playlists: PlaylistFolder[];
isPlaying: boolean;
currentTrack: TrackDetail;
isResolvingTrack: boolean;
createPlaylist: (name: string, tracks?: TrackDetail[]) => string;
renamePlaylist: (id: string, name: string) => void;
removePlaylist: (id: string) => void;
removeTrackFromPlaylist: (playlistId: string, trackId: string, source: MusicSource) => void;
addPlaylistToQueue: (playlistId: string, append?: boolean) => void;
playPlaylistTrack: (track: TrackDetail) => void;
onAddTrackToQueue?: (track: TrackDetail) => void;
isFavorite?: (track: TrackDetail) => boolean;
onToggleFavorite?: (track: TrackDetail) => void;
}
const DefaultVinylCover = () => (
<div className="size-full bg-radial from-[#22232a] to-[#0f1015] flex items-center justify-center relative shadow-inner select-none pointer-events-none">
{/* 唱片的同心圆纹路 */}
<div className="absolute inset-1 rounded-full border border-white/5" />
<div className="absolute inset-2 rounded-full border border-white/5" />
<div className="absolute inset-3.5 rounded-full border border-white/5" />
{/* 红心胶心 */}
<div className="size-3 rounded-full bg-rose-500 flex items-center justify-center shadow-xs">
<div className="size-1 rounded-full bg-black/60" />
</div>
</div>
);
const TrackCover = ({ coverUrl, title }: { coverUrl?: string; title: string }) => {
const [hasError, setHasError] = useState(false);
if (coverUrl && !hasError) {
return (
// eslint-disable-next-line @next/next/no-img-element
<img
src={coverUrl}
alt={title}
className="size-full object-cover"
onError={() => setHasError(true)}
/>
);
}
return <DefaultVinylCover />;
};
export default function DrawerPlaylistsTab({
playlists,
isPlaying,
currentTrack,
isResolvingTrack,
createPlaylist,
renamePlaylist,
removePlaylist,
removeTrackFromPlaylist,
addPlaylistToQueue,
playPlaylistTrack,
onAddTrackToQueue,
isFavorite,
onToggleFavorite,
}: DrawerPlaylistsTabProps) {
const [newPlaylistName, setNewPlaylistName] = useState("");
// 自定义重命名 Modal 状态控制
const [renameTargetId, setRenameTargetId] = useState<string | null>(null);
const [renameInput, setRenameInput] = useState("");
const pointerDownTargetRef = useRef<EventTarget | null>(null);
// 用于视图切换:null 代表一级页面(歌单列表),有值代表二级页面(特定歌单详情页)
const [activePlaylistId, setActivePlaylistId] = useState<string | null>(null);
// 歌单详情页内曲目的分页,防单歌单过大卡顿
const [visibleTracksLimit, setVisibleTracksLimit] = useState(25);
const handleCreatePlaylist = (e: React.FormEvent) => {
e.preventDefault();
const name = newPlaylistName.trim();
if (!name) return;
createPlaylist(name);
setNewPlaylistName("");
};
const handleRename = (folderId: string, currentName: string) => {
setRenameTargetId(folderId);
setRenameInput(currentName);
};
const handleFolderClick = (folderId: string) => {
setActivePlaylistId(folderId);
setVisibleTracksLimit(25); // 进入详情页时重置分页限制
};
const handleLoadMoreTracks = (maxLen: number) => {
setVisibleTracksLimit((prev) => Math.min(prev + 25, maxLen));
};
// 渲染二级页面(歌单详情页)
if (activePlaylistId !== null) {
const folder = playlists.find(pl => pl.id === activePlaylistId);
// 如果对应的文件夹不存在(比如被删除了),安全返回一级页面
if (!folder) {
setActivePlaylistId(null);
return null;
}
const hasCover = Boolean(folder.cover);
return (
<div className="grow min-h-0 flex flex-col space-y-4 overflow-y-auto pr-1 overscroll-contain animate-in fade-in duration-200">
{/* 顶部:返回导航与歌单信息 */}
<div className="flex flex-col gap-3 shrink-0">
<div>
<button
type="button"
onClick={() => setActivePlaylistId(null)}
className="flex items-center gap-1.5 text-xs text-(--fg-color)/70 hover:text-(--fg-color) transition-all cursor-pointer font-semibold py-1.5 px-3.5 rounded-xl bg-(--fg-color)/5 hover:bg-(--fg-color)/10 border border-(--border-line-color)/50 inline-flex"
>
<CaretLeftIcon size={14} weight="bold" />
<span>返回歌单列表</span>
</button>
</div>
<div className="flex gap-4 p-4 rounded-2xl bg-(--fg-color)/4 border border-(--border-line-color)/60">
{/* 歌单封面海报 */}
<div className="relative size-20 sm:size-24 shrink-0 rounded-2xl overflow-hidden bg-gradient-to-br from-neutral-800 to-neutral-900 border border-(--border-line-color) shadow-md flex items-center justify-center text-white">
{hasCover ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={folder.cover}
alt={`${folder.name} 封面`}
className="size-full object-cover"
/>
) : (
<div className="flex flex-col items-center justify-center opacity-70">
<FolderIcon size={32} weight="fill" className="text-neutral-400" />
</div>
)}
</div>
<div className="flex flex-col justify-between py-1 min-w-0 grow">
<div className="min-w-0">
<h3 className="font-bold text-base text-(--fg-color) truncate">
{folder.name}
</h3>
<p className="text-xs text-(--fg-color)/50 mt-1.5">
共 {folder.tracks.length} 首曲目 • 创建于 {new Date(folder.createdAt).toLocaleDateString()}
</p>
</div>
{/* 详情页控制大按钮 */}
<div className="flex items-center gap-2 mt-2">
<button
type="button"
onClick={() => addPlaylistToQueue(folder.id, false)}
className="px-3.5 py-1.5 rounded-xl bg-(--accent-color) hover:bg-(--accent-color)/90 text-white shadow-xs transition-transform active:scale-95 flex items-center gap-1.5 text-xs font-semibold cursor-pointer"
disabled={folder.tracks.length === 0}
>
<PlayIcon size={13} weight="fill" />
<span>播放全部</span>
</button>
<button
type="button"
onClick={() => addPlaylistToQueue(folder.id, true)}
className="px-3.5 py-1.5 rounded-xl bg-(--fg-color)/8 hover:bg-(--fg-color)/15 text-(--fg-color) transition-transform active:scale-95 flex items-center gap-1.5 text-xs font-semibold cursor-pointer border border-(--border-line-color)"
disabled={folder.tracks.length === 0}
>
<PlusIcon size={13} weight="bold" />
<span>追加到队列</span>
</button>
</div>
</div>
</div>
</div>
{/* 歌曲列表 (单独页面渲染,带分页防卡顿) */}
<div className="grow min-h-0 space-y-1.5">
{folder.tracks.length === 0 ? (
<div className="text-center py-16 text-xs text-(--fg-color)/40 font-medium">
歌单内暂无曲目,请在【在线搜索】或【歌单导入】中为歌单添加歌曲。
</div>
) : (
<div className="space-y-1.5">
{folder.tracks.slice(0, visibleTracksLimit).map((track, idx) => {
const isCurrent = currentTrack && currentTrack.id === track.id && currentTrack.source === track.source;
return (
<div
key={`${track.source}-${track.id}-${idx}`}
onClick={() => {
if (isResolvingTrack) return;
playPlaylistTrack(track);
}}
className={`group relative flex items-center gap-3.5 rounded-xl px-4 py-2.5 text-left transition-colors duration-150 border ${
isResolvingTrack ? "pointer-events-none opacity-60" : "cursor-pointer"
} ${
isCurrent
? "bg-(--accent-color)/12 text-(--fg-color) font-medium border-(--accent-color)/30 shadow-xs"
: "bg-(--fg-color)/4 hover:bg-(--fg-color)/8 border-(--border-line-color)"
}`}
>
<span className="w-5 text-center text-xs font-mono text-(--fg-color)/40 group-hover:text-(--fg-color)/70 shrink-0">
{isCurrent ? (
<MusicIcon size={14} weight="fill" className="text-(--accent-color) mx-auto" />
) : (
String(idx + 1).padStart(2, "0")
)}
</span>
<div className="relative size-10 shrink-0 rounded-xl overflow-hidden bg-(--fg-color)/10 border border-(--border-line-color) shadow-xs">
<TrackCover coverUrl={track.cover} title={track.title} />
</div>
<div className="min-w-0 grow">
<p className={`truncate text-sm ${isCurrent ? "text-(--fg-color) font-semibold" : "text-(--fg-color)/90"}`}>
{track.title}
</p>
<p className="truncate text-xs text-(--fg-color)/55 mt-0.5">
{track.artist} {track.album ? `• ${track.album}` : ""}
</p>
</div>
{isCurrent && isPlaying && (
<WaveformIcon size={16} className="shrink-0 text-(--accent-color) animate-pulse" />
)}
{/* 按钮组:包含单曲专有的“我喜欢”(收藏)、追加到队列按钮,以及从歌单移除按钮 */}
<div className="flex items-center gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
{onToggleFavorite && isFavorite && (
<button
type="button"
onClick={() => onToggleFavorite(track)}
className={`opacity-0 group-hover:opacity-100 p-2 rounded-xl transition-all shrink-0 cursor-pointer border border-transparent ${
isFavorite(track)
? "text-rose-500 bg-rose-500/10 border-rose-500/20"
: "bg-(--fg-color)/6 text-(--fg-color)/55 hover:text-rose-500 hover:bg-rose-500/10"
}`}
title={isFavorite(track) ? "取消收藏" : "加入收藏(我喜欢)"}
>
<HeartIcon size={13} weight={isFavorite(track) ? "fill" : "regular"} />
</button>
)}
<button
type="button"
onClick={() => onAddTrackToQueue?.(track)}
className="opacity-0 group-hover:opacity-100 p-2 rounded-xl bg-(--fg-color)/6 text-(--fg-color)/55 hover:text-(--accent-color) hover:bg-(--accent-color)/10 transition-all cursor-pointer border border-transparent hover:border-(--accent-color)/20"
title="追加该曲到播放队列"
>
<PlusIcon size={13} weight="bold" />
</button>
<button
type="button"
onClick={() => removeTrackFromPlaylist(folder.id, track.id, track.source)}
className="opacity-0 group-hover:opacity-100 p-2 rounded-xl bg-(--fg-color)/6 text-(--fg-color)/55 hover:text-red-500 hover:bg-red-500/10 transition-all cursor-pointer border border-transparent hover:border-red-500/20"
title="从歌单中移除"
>
<TrashIcon size={13} />
</button>
</div>
</div>
);
})}
{/* 分页加载更多 */}
{folder.tracks.length > visibleTracksLimit && (
<div className="pt-2 text-center shrink-0">
<button
type="button"
onClick={() => handleLoadMoreTracks(folder.tracks.length)}
className="px-5 py-2 rounded-xl border border-(--border-line-color) hover:border-(--accent-color)/30 bg-(--fg-color)/4 hover:bg-(--fg-color)/8 text-xs text-(--fg-color)/70 hover:text-(--fg-color) transition-all cursor-pointer inline-flex items-center gap-1 font-semibold"
>
<span>展开更多歌曲 (共 {folder.tracks.length} 首,已显示 {visibleTracksLimit} 首)</span>
</button>
</div>
)}
</div>
)}
</div>
</div>
);
}
// 渲染一级页面(歌单列表页)
return (
<div className="grow min-h-0 flex flex-col space-y-4 overflow-y-auto pr-1 overscroll-contain animate-in fade-in duration-200">
{/* 顶部:新建歌单区域 */}
<form onSubmit={handleCreatePlaylist} className="flex gap-2 shrink-0">
<input
type="text"
value={newPlaylistName}
onChange={(e) => setNewPlaylistName(e.target.value)}
placeholder="新建我的歌单文件夹..."
className="grow px-4 py-2.5 rounded-2xl bg-(--fg-color)/6 border border-(--border-line-color) text-xs text-(--fg-color) placeholder-(--fg-color)/40 focus:outline-hidden focus:border-(--accent-color) transition-all"
/>
<button
type="submit"
disabled={!newPlaylistName.trim()}
className="px-5 py-2.5 rounded-2xl bg-(--accent-color) hover:bg-(--accent-color)/90 text-white text-xs font-semibold shadow-md transition-all active:scale-95 disabled:opacity-50 flex items-center gap-1 cursor-pointer shrink-0"
>
<PlusIcon size={14} weight="bold" />
<span>新建</span>
</button>
</form>
{/* 歌单文件夹展示 */}
{playlists.length === 0 ? (
<div className="grow flex flex-col items-center justify-center py-12 text-center text-(--fg-color)/40 space-y-3">
<FolderIcon size={40} className="stroke-1 opacity-70" />
<div className="text-xs">
<p className="font-semibold text-(--fg-color)/70">尚无歌单文件夹</p>
<p className="mt-1 text-[11px] text-(--fg-color)/45 leading-relaxed">
您可以通过上方新建歌单,或者从【歌单导入】<br />解析网易云歌单,导入的歌曲会自动生成文件夹。
</p>
</div>
</div>
) : (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pb-4">
{playlists.map((folder) => {
const hasCover = Boolean(folder.cover);
return (
<div
key={folder.id}
onClick={() => handleFolderClick(folder.id)}
className="group relative flex items-center justify-between gap-3 p-4 rounded-2xl bg-(--fg-color)/4 hover:bg-(--fg-color)/8 border border-(--border-line-color) hover:border-(--accent-color)/30 transition-all duration-300 cursor-pointer shadow-xs hover:shadow-md"
>
<div className="flex items-center gap-3.5 min-w-0 grow">
{/* 文件夹小封面:海报图 */}
<div className="relative size-12 shrink-0 rounded-xl overflow-hidden bg-gradient-to-br from-neutral-800 to-neutral-900 border border-(--border-line-color) shadow-sm flex items-center justify-center text-white">
{hasCover ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={folder.cover}
alt={`${folder.name} 封面`}
className="size-full object-cover"
/>
) : (
<div className="flex flex-col items-center justify-center opacity-70">
<FolderIcon size={20} weight="fill" className="text-neutral-400" />
</div>
)}
</div>
<div className="min-w-0">
<p className="font-semibold text-sm text-(--fg-color) truncate group-hover:text-(--accent-color) transition-colors">
{folder.name}
</p>
<p className="text-[11px] text-(--fg-color)/50 mt-1">
{folder.tracks.length} 首曲目
</p>
</div>
</div>
{/* 悬浮/快捷操作区 */}
<div className="flex items-center gap-1 shrink-0" onClick={(e) => e.stopPropagation()}>
<button
type="button"
onClick={() => addPlaylistToQueue(folder.id, false)}
className="opacity-0 group-hover:opacity-100 p-1.5 rounded-lg bg-(--accent-color)/15 hover:bg-(--accent-color) text-(--accent-color) hover:text-white transition-all cursor-pointer"
title="播放全部"
disabled={folder.tracks.length === 0}
>
<PlayIcon size={12} weight="fill" />
</button>
<button
type="button"
onClick={() => handleRename(folder.id, folder.name)}
className="opacity-0 group-hover:opacity-100 p-1.5 rounded-lg hover:bg-(--fg-color)/10 text-(--fg-color)/60 hover:text-(--fg-color) transition-all cursor-pointer"
title="重命名"
>
<EditIcon size={12} />
</button>
<button
type="button"
onClick={() => removePlaylist(folder.id)}
className="opacity-0 group-hover:opacity-100 p-1.5 rounded-lg hover:bg-red-500/10 text-(--fg-color)/50 hover:text-red-500 transition-all cursor-pointer"
title="删除"
>
<TrashIcon size={12} />
</button>
</div>
</div>
);
})}
</div>
)}
{/* 自定义高颜值重命名对话弹窗:拒绝丑陋的原生 alert/prompt */}
{renameTargetId !== null && (
<div
className="fixed inset-0 bg-black/40 backdrop-blur-xs flex items-center justify-center z-50 animate-in fade-in duration-200"
onMouseDown={(e) => {
pointerDownTargetRef.current = e.target;
}}
onMouseUp={(e) => {
// 只有当 mousedown 的起点是遮罩层本身,且 mouseup 释放的终点也是遮罩层本身时,才进行关闭
// 这能 100% 杜绝鼠标在输入框内按住并向外拖拽全选文字时发生误触关闭的 Bug!
if (pointerDownTargetRef.current === e.currentTarget && e.target === e.currentTarget) {
setRenameTargetId(null);
}
}}
>
<div
className="bg-white dark:bg-[#161720] border border-zinc-200/80 dark:border-zinc-800/80 rounded-3xl p-5 w-80 max-w-[90%] shadow-[0_20px_50px_rgba(0,0,0,0.15)] flex flex-col gap-4 animate-in zoom-in-95 duration-200"
onClick={(e) => e.stopPropagation()}
>
<div className="space-y-1">
<h4 className="text-sm font-semibold text-(--fg-color)">重命名歌单文件夹</h4>
<p className="text-[10px] text-(--fg-color)/45">请输入该文件夹的新名称:</p>
</div>
<input
type="text"
autoFocus
value={renameInput}
onChange={(e) => setRenameInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
const name = renameInput.trim();
if (name) {
renamePlaylist(renameTargetId, name);
setRenameTargetId(null);
}
} else if (e.key === "Escape") {
setRenameTargetId(null);
}
}}
className="w-full px-3.5 py-2.5 rounded-xl bg-(--fg-color)/4 border border-(--border-line-color) text-xs text-(--fg-color) focus:outline-hidden focus:border-(--accent-color)/60 transition-colors"
placeholder="歌单名称..."
/>
<div className="flex items-center justify-end gap-2 text-xs pt-1">
<button
type="button"
onClick={() => setRenameTargetId(null)}
className="px-4 py-2 rounded-xl hover:bg-(--fg-color)/6 text-(--fg-color)/60 transition-colors cursor-pointer"
>
取消
</button>
<button
type="button"
onClick={() => {
const name = renameInput.trim();
if (name) {
renamePlaylist(renameTargetId, name);
setRenameTargetId(null);
}
}}
disabled={!renameInput.trim()}
className="px-4 py-2 rounded-xl bg-(--accent-color) hover:bg-(--accent-color)/90 disabled:opacity-50 text-white font-semibold transition-colors cursor-pointer shadow-sm"
>
保存
</button>
</div>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,243 @@
"use client";
import React, { useRef, useState, useEffect } from "react";
import { musicIcons } from "@/icon/music";
import type { ApiSearchResult, MusicSource, TrackDetail } from "@/interface/music";
const {
caretDown: CaretDownIcon,
heart: HeartIcon,
loading: LoadingIcon,
play: PlayIcon,
radio: RadioIcon,
search: SearchIcon,
} = musicIcons;
const SOURCE_OPTIONS: Array<{ label: string; value: MusicSource; color: string; badge: string }> = [
{ label: "网易云音乐", value: "netease", color: "bg-red-500/15 text-red-500 border-red-500/25", badge: "网易云" },
{ label: "酷我音乐", value: "kuwo", color: "bg-amber-500/15 text-amber-500 border-amber-500/25", badge: "酷我" },
{ label: "Bilibili", value: "bilibili", color: "bg-pink-500/15 text-pink-500 border-pink-500/25", badge: "Bilibili" },
{ label: "JOOX 音乐", value: "joox", color: "bg-teal-500/15 text-teal-500 border-teal-500/25", badge: "JOOX" },
];
interface DrawerSearchTabProps {
selectedSource: MusicSource;
onSourceChange: (source: MusicSource) => void;
searchQuery: string;
onSearchQueryChange: (query: string) => void;
onExecuteSearch: () => void;
isSearching: boolean;
searchResults: ApiSearchResult[];
searchMessage: string;
onResolveAndPlay: (result: ApiSearchResult) => void;
isResolvingTrack: boolean;
onToggleFavorite?: (track: TrackDetail) => void;
isFavorite?: (track: TrackDetail) => boolean;
}
export default function DrawerSearchTab({
selectedSource,
onSourceChange,
searchQuery,
onSearchQueryChange,
onExecuteSearch,
isSearching,
searchResults,
searchMessage,
onResolveAndPlay,
isResolvingTrack,
onToggleFavorite,
isFavorite,
}: DrawerSearchTabProps) {
const [isSelectDropdownOpen, setIsSelectDropdownOpen] = useState(false);
const [resolvingId, setResolvingId] = useState<string | null>(null);
const dropdownRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!isResolvingTrack) {
setResolvingId(null);
}
}, [isResolvingTrack]);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
setIsSelectDropdownOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
const activeSourceObj = SOURCE_OPTIONS.find((s) => s.value === selectedSource) || SOURCE_OPTIONS[0];
return (
<div className="flex flex-col h-full grow min-h-0 space-y-4">
<div className="flex items-center gap-2 bg-(--fg-color)/6 p-2 rounded-2xl border border-(--border-line-color) shrink-0">
<div ref={dropdownRef} className="relative shrink-0">
<button
type="button"
onClick={() => setIsSelectDropdownOpen((open) => !open)}
className="flex items-center gap-2 bg-(--bg-dark-color) text-(--fg-color) text-xs px-3 py-2 rounded-xl border border-(--border-line-color) shadow-sm hover:border-(--accent-color)/50 transition-all cursor-pointer font-medium"
>
<span className={`px-1.5 py-0.5 rounded text-[10px] font-semibold border ${activeSourceObj.color}`}>
{activeSourceObj.badge}
</span>
<span>{activeSourceObj.label}</span>
<CaretDownIcon size={14} className={`text-(--fg-color)/50 transition-transform ${isSelectDropdownOpen ? "rotate-180" : ""}`} />
</button>
{isSelectDropdownOpen && (
<div className="absolute top-full left-0 mt-2 w-44 rounded-2xl bg-(--bg-dark-color) border border-(--border-line-color) shadow-2xl z-50 p-1.5 backdrop-blur-3xl animate-in fade-in zoom-in-95 duration-150">
{SOURCE_OPTIONS.map((opt) => (
<button
key={opt.value}
type="button"
onClick={() => {
onSourceChange(opt.value);
setIsSelectDropdownOpen(false);
}}
className={`w-full flex items-center justify-between px-3 py-2 rounded-xl text-xs transition-colors cursor-pointer ${
selectedSource === opt.value
? "bg-(--accent-color)/15 text-(--accent-color) font-semibold"
: "text-(--fg-color)/70 hover:bg-(--fg-color)/8 hover:text-(--fg-color)"
}`}
>
<span>{opt.label}</span>
<span className={`px-1.5 py-0.5 rounded text-[9px] font-semibold border ${opt.color}`}>
{opt.badge}
</span>
</button>
))}
</div>
)}
</div>
<div className="relative grow flex items-center">
<input
type="text"
value={searchQuery}
onChange={(e) => onSearchQueryChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") onExecuteSearch();
}}
placeholder={`在 ${activeSourceObj.label} 检索在线歌曲/歌手/专辑...`}
className="w-full bg-transparent px-3 py-1.5 text-xs text-(--fg-color) placeholder-(--fg-color)/40 focus:outline-hidden"
/>
</div>
<button
type="button"
onClick={onExecuteSearch}
disabled={isSearching || !searchQuery.trim()}
className="px-4 py-2 rounded-xl bg-(--accent-color) text-white text-xs font-semibold shadow-md transition-all hover:scale-105 active:scale-95 disabled:opacity-50 cursor-pointer shrink-0 flex items-center gap-1.5"
>
{isSearching ? (
<LoadingIcon size={15} className="animate-spin" />
) : (
<>
<SearchIcon size={14} weight="bold" />
<span>搜索</span>
</>
)}
</button>
</div>
<div className="grow min-h-0 overflow-y-auto space-y-2.5 pr-1 overscroll-contain">
{searchMessage && (
<p className="py-8 text-center text-xs text-(--fg-color)/60">{searchMessage}</p>
)}
{!searchMessage && searchResults.length === 0 && (
<div className="flex h-52 flex-col items-center justify-center gap-3 text-center text-(--fg-color)/40">
<RadioIcon size={36} className="opacity-40" />
<p className="text-xs max-w-56 leading-relaxed">选择平台并输入名称,直接把喜欢的音乐添加到播放队列</p>
</div>
)}
{searchResults.map((result) => {
const isThisTrackResolving = isResolvingTrack && resolvingId === String(result.id);
const searchTrackItem: TrackDetail = {
id: String(result.id),
title: result.name,
artist: Array.isArray(result.artist) ? result.artist.join(" / ") : result.artist || "未知歌手",
album: result.album || "",
src: "",
source: result.source,
picId: result.pic_id,
lyricId: result.lyric_id,
};
return (
<div
key={`${result.source}-${result.id}`}
onClick={(e) => {
e.stopPropagation();
if (isResolvingTrack) return;
setResolvingId(String(result.id));
onResolveAndPlay(result);
}}
className={`group relative z-10 flex items-center justify-between rounded-2xl px-4 py-3 border transition-all ${
isThisTrackResolving
? "bg-(--accent-color)/15 border-(--accent-color)/50 shadow-md pointer-events-none cursor-wait"
: isResolvingTrack
? "pointer-events-none opacity-50 bg-(--fg-color)/4 border-(--border-line-color)"
: "bg-(--fg-color)/4 hover:bg-(--fg-color)/10 border-(--border-line-color) hover:border-(--accent-color)/40 cursor-pointer"
}`}
>
<div className="min-w-0 grow pr-3">
<div className="flex items-center gap-2">
<p className="truncate text-sm font-semibold text-(--fg-color)/90 group-hover:text-(--fg-color)">
{result.name}
</p>
</div>
<p className="truncate text-xs text-(--fg-color)/60 mt-0.5">
{Array.isArray(result.artist) ? result.artist.join(" / ") : result.artist} {result.album ? `• ${result.album}` : ""}
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
{onToggleFavorite && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onToggleFavorite(searchTrackItem);
}}
className={`p-2 rounded-xl transition-all cursor-pointer border border-transparent ${
isFavorite?.(searchTrackItem)
? "text-rose-500 bg-rose-500/10 border-rose-500/20"
: "opacity-0 group-hover:opacity-100 bg-(--fg-color)/6 text-(--fg-color)/50 hover:text-rose-500 hover:bg-rose-500/10"
}`}
title={isFavorite?.(searchTrackItem) ? "取消收藏" : "加入收藏"}
>
<HeartIcon size={15} weight={isFavorite?.(searchTrackItem) ? "fill" : "regular"} />
</button>
)}
<button
type="button"
disabled={isResolvingTrack}
className={`grid size-9 place-items-center rounded-xl transition-all shrink-0 shadow-sm ${
isThisTrackResolving
? "bg-(--accent-color) text-white"
: "bg-(--fg-color)/10 text-(--fg-color)/80 group-hover:bg-(--accent-color) group-hover:text-white group-hover:scale-105 active:scale-95"
}`}
aria-label="播放这首歌"
>
{isThisTrackResolving ? (
<LoadingIcon size={16} className="animate-spin text-white" />
) : (
<PlayIcon size={15} weight="fill" className="translate-x-0.5" />
)}
</button>
</div>
</div>
);
})}
</div>
</div>
);
}
@@ -0,0 +1,451 @@
"use client";
import React, { useRef, useState, useEffect, useCallback } from "react";
import { musicIcons } from "@/icon/music";
import type { PlaybackMode, TrackDetail } from "@/interface/music";
import RollingLyrics from "../RollingLyrics";
import PlayerProgressBar from "./PlayerProgressBar";
const {
loading: LoadingIcon,
next: NextIcon,
pause: PauseIcon,
play: PlayIcon,
playlist: PlaylistIcon,
previous: PreviousIcon,
repeat: RepeatIcon,
repeatOne: RepeatOneIcon,
shuffle: ShuffleIcon,
volume: VolumeIcon,
volumeMuted: VolumeMutedIcon,
lyrics: LyricsIcon,
heart: HeartIcon,
music: MusicIcon,
} = musicIcons;
interface PlayerCapsuleBarProps {
currentTrack: TrackDetail;
playlistLength: number;
isPlaying: boolean;
isResolvingTrack: boolean;
playMode: PlaybackMode;
currentTime: number;
duration: number;
volume: number;
isMuted: boolean;
brokenCovers: Set<string>;
playerMessage: string;
isFavorite: boolean;
onTogglePlay: () => void;
onPlayNext: () => void;
onPlayPrev: () => void;
onCycleMode: () => void;
onSeek: (time: number) => void;
onVolumeChange: (vol: number) => void;
onToggleMute: () => void;
onToggleFavorite: () => void;
onOpenDrawer: () => void;
onOpenExpandedModal: () => void;
onMarkBrokenCover: (id: string) => void;
formatTime: (seconds: number) => string;
}
const DefaultVinylCover = ({ isPlaying = false }: { isPlaying?: boolean }) => (
<div
className="size-full bg-radial from-[#22232a] to-[#0f1015] flex items-center justify-center relative shadow-inner select-none pointer-events-none animate-spin-slow"
style={{ animationPlayState: isPlaying ? "running" : "paused", willChange: "transform", transform: "translateZ(0)" }}
>
{/* 唱片的同心圆纹路 */}
<div className="absolute inset-1 rounded-full border border-white/5" />
<div className="absolute inset-2 rounded-full border border-white/5" />
<div className="absolute inset-3 rounded-full border border-white/5" />
{/* 红心胶心 */}
<div className="size-3.5 rounded-full bg-rose-500 flex items-center justify-center shadow-xs">
<MusicIcon size={8} className="text-white/80" />
</div>
</div>
);
export default function PlayerCapsuleBar({
currentTrack,
playlistLength,
isPlaying,
isResolvingTrack,
playMode,
currentTime,
duration,
volume,
isMuted,
brokenCovers,
playerMessage,
isFavorite,
onTogglePlay,
onPlayNext,
onPlayPrev,
onCycleMode,
onSeek,
onVolumeChange,
onToggleMute,
onToggleFavorite,
onOpenDrawer,
onOpenExpandedModal,
onMarkBrokenCover,
formatTime,
}: PlayerCapsuleBarProps) {
const volumeContainerRef = useRef<HTMLDivElement | null>(null);
const collapseTimerRef = useRef<NodeJS.Timeout | null>(null);
const [showVolumeSlider, setShowVolumeSlider] = useState(false);
const [isDraggingVolume, setIsDraggingVolume] = useState(false);
const [isCollapsed, setIsCollapsed] = useState(false);
const [localCoverFailed, setLocalCoverFailed] = useState(false);
useEffect(() => {
setLocalCoverFailed(false);
}, [currentTrack?.id]);
// 清除 5s 自动折叠倒计时
const clearCollapseTimer = useCallback(() => {
if (collapseTimerRef.current) {
clearTimeout(collapseTimerRef.current);
collapseTimerRef.current = null;
}
}, []);
// 启动 5s 自动折叠倒计时
const startCollapseTimer = useCallback(() => {
clearCollapseTimer();
collapseTimerRef.current = setTimeout(() => {
setIsCollapsed(true);
}, 5000);
}, [clearCollapseTimer]);
// 当鼠标悬浮到播放器:立刻唤醒展开
const handleMouseEnterPlayer = () => {
clearCollapseTimer();
if (isCollapsed) {
setIsCollapsed(false);
}
};
// 当鼠标离开播放器:启动 5 秒失焦折叠倒计时
const handleMouseLeavePlayer = () => {
if (!isDraggingVolume) {
startCollapseTimer();
}
};
useEffect(() => {
startCollapseTimer();
return () => clearCollapseTimer();
}, [startCollapseTimer, clearCollapseTimer]);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
if (volumeContainerRef.current && !volumeContainerRef.current.contains(e.target as Node)) {
if (!isDraggingVolume) {
setShowVolumeSlider(false);
}
}
};
if (showVolumeSlider) {
document.addEventListener("mousedown", handleClickOutside);
}
return () => document.removeEventListener("mousedown", handleClickOutside);
}, [showVolumeSlider, isDraggingVolume]);
const calculateVolumeFromEvent = (e: React.PointerEvent<HTMLDivElement>) => {
const rect = e.currentTarget.getBoundingClientRect();
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
return x / rect.width;
};
const handleVolumePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
setIsDraggingVolume(true);
e.currentTarget.setPointerCapture(e.pointerId);
const newVol = calculateVolumeFromEvent(e);
onVolumeChange(newVol);
};
const handleVolumePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
if (isDraggingVolume) {
const newVol = calculateVolumeFromEvent(e);
onVolumeChange(newVol);
}
};
const handleVolumePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
if (isDraggingVolume) {
setIsDraggingVolume(false);
e.currentTarget.releasePointerCapture(e.pointerId);
startCollapseTimer();
}
};
const ModeIcon = playMode === "repeat" ? RepeatOneIcon : playMode === "shuffle" ? ShuffleIcon : RepeatIcon;
const coverIsAvailable = Boolean(
playlistLength > 0 &&
currentTrack?.cover &&
!brokenCovers.has(currentTrack.id) &&
!localCoverFailed
);
const displayFallbackMessage = playerMessage || currentTrack.album || "等待一段声音开始";
return (
<div
onMouseEnter={handleMouseEnterPlayer}
onMouseLeave={handleMouseLeavePlayer}
data-player-style="floating-drawer-dock"
style={{
transform: isCollapsed
? "translate(-50%, calc(100% - 24px))"
: "translate(-50%, 0)",
}}
className={`fixed bottom-0 left-1/2 z-70 w-[calc(100%-2rem)] max-w-6xl backdrop-blur-2xl bg-(--bg-dark-color)/95 text-(--fg-color) border-t border-x border-(--border-line-color) shadow-[0_-12px_40px_rgba(0,0,0,0.3)] rounded-t-3xl px-5 pt-3 pb-3 transition-transform duration-500 cubic-bezier(0.16,1,0.3,1) select-none overflow-visible group/drawer ${
isCollapsed ? "cursor-pointer hover:border-(--accent-color)/60" : ""
}`}
onClick={() => {
if (isCollapsed) {
setIsCollapsed(false);
clearCollapseTimer();
}
}}
>
{/* 顶部微型的 Drawer 指示条 */}
<div className="w-full pb-2 flex flex-col items-center shrink-0 cursor-pointer">
<div className={`h-1 rounded-full transition-all duration-300 ${
isCollapsed ? "w-16 bg-(--accent-color) animate-pulse" : "w-10 bg-(--fg-color)/20 group-hover/drawer:bg-(--fg-color)/40"
}`} />
</div>
<PlayerProgressBar
currentTime={currentTime}
duration={duration}
onSeek={onSeek}
formatTime={formatTime}
hasTrack={playlistLength > 0}
/>
<div className="flex items-center justify-between gap-3 pt-1">
{/* 左侧:专辑封面与歌曲信息 */}
<div className="flex items-center gap-3.5 min-w-0 grow md:grow-0">
<button
type="button"
onClick={(e) => {
if (isCollapsed) return;
e.stopPropagation();
onOpenExpandedModal();
}}
className="relative size-10 sm:size-11 shrink-0 rounded-full overflow-hidden border border-(--border-line-color) shadow-sm group cursor-pointer transition-transform hover:scale-105 active:scale-95"
title="打开沉浸式歌词大屏"
>
{coverIsAvailable ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={currentTrack.cover}
alt={`${currentTrack.title} 封面`}
className="size-full object-cover animate-spin-slow"
style={{ animationPlayState: isPlaying ? "running" : "paused", willChange: "transform", transform: "translateZ(0)" }}
onError={() => {
onMarkBrokenCover(currentTrack.id);
setLocalCoverFailed(true);
}}
/>
) : (
<DefaultVinylCover isPlaying={isPlaying} />
)}
<div className="absolute inset-0 bg-black/30 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center text-white">
<LyricsIcon size={14} weight="bold" />
</div>
</button>
<div className="min-w-0 max-w-[260px] sm:max-w-md md:max-w-lg lg:max-w-xl">
<div className="flex items-center gap-2 truncate">
<p className="truncate text-xs sm:text-sm font-semibold text-(--fg-color) tracking-tight">
{playlistLength > 0 ? currentTrack.title : "暂无歌曲播放"}
</p>
{playlistLength > 0 && (
<span className="hidden sm:inline text-[10px] text-(--fg-color)/60 truncate">
• {currentTrack.artist}
</span>
)}
</div>
<div className="text-[11px] sm:text-xs text-(--fg-color)/70 mt-0.5 truncate">
{playlistLength > 0 ? (
<RollingLyrics
lyric={currentTrack.lyric}
translatedLyric={currentTrack.tlyric}
currentTime={currentTime}
fallback={displayFallbackMessage}
/>
) : (
<span className="text-[11px] text-(--fg-color)/40">开启您的音乐生活档案</span>
)}
</div>
</div>
</div>
{/* 中间:播放控制核心组 */}
<div className="flex items-center gap-1 sm:gap-2 shrink-0">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onToggleFavorite();
}}
className={`grid size-8 place-items-center rounded-full transition-all active:scale-90 cursor-pointer ${
isFavorite
? "text-rose-500 bg-rose-500/10 hover:bg-rose-500/20"
: "text-(--fg-color)/60 hover:text-rose-500 hover:bg-(--fg-color)/10"
}`}
title={isFavorite ? "取消收藏" : "加入收藏"}
>
<HeartIcon size={16} weight={isFavorite ? "fill" : "regular"} />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onCycleMode();
}}
className={`hidden sm:grid size-8 place-items-center rounded-full transition-colors hover:bg-(--fg-color)/10 ${
playMode === "sequence" ? "text-(--fg-color)/60" : "text-(--accent-color)"
}`}
title={playMode === "repeat" ? "单曲循环" : playMode === "shuffle" ? "随机播放" : "顺序播放"}
>
<ModeIcon size={16} weight="bold" />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onPlayPrev();
}}
className="grid size-8 sm:size-9 place-items-center rounded-full text-(--fg-color)/80 hover:text-(--fg-color) hover:bg-(--fg-color)/10 transition-all active:scale-90 cursor-pointer"
title="上一首"
>
<PreviousIcon size={18} weight="fill" />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onTogglePlay();
}}
disabled={isResolvingTrack}
className="grid size-9 sm:size-10 place-items-center rounded-full bg-(--accent-color) text-white shadow-sm transition-transform hover:scale-105 active:scale-95 disabled:opacity-50 cursor-pointer"
title={isPlaying ? "暂停" : "播放"}
>
{isResolvingTrack ? (
<LoadingIcon size={18} className="animate-spin" />
) : isPlaying ? (
<PauseIcon size={18} weight="fill" />
) : (
<PlayIcon size={18} weight="fill" className="translate-x-0.5" />
)}
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onPlayNext();
}}
className="grid size-8 sm:size-9 place-items-center rounded-full text-(--fg-color)/80 hover:text-(--fg-color) hover:bg-(--fg-color)/10 transition-all active:scale-90 cursor-pointer"
title="下一首"
>
<NextIcon size={18} weight="fill" />
</button>
<span className="hidden lg:inline-block ml-1 font-mono text-[10px] text-(--fg-color)/60 shrink-0">
{formatTime(currentTime)} / {formatTime(duration)}
</span>
</div>
{/* 右侧:音量控制 & 播放队列(采用绝对定位向左连体平滑展开,绝对不挤压左侧操控按钮) */}
<div className="flex items-center gap-1.5 sm:gap-2 shrink-0">
<div
ref={volumeContainerRef}
className="relative hidden md:block size-8 sm:size-9"
onMouseEnter={() => setShowVolumeSlider(true)}
onMouseLeave={() => {
if (!isDraggingVolume) setShowVolumeSlider(false);
}}
>
<div
className={`absolute right-0 top-0 h-full flex flex-row-reverse items-center transition-all duration-300 ease-out z-20 backdrop-blur-md rounded-full bg-(--fg-color)/5 hover:bg-(--fg-color)/10 border border-(--border-line-color)/40 ${
showVolumeSlider || isDraggingVolume
? "w-40 sm:w-44 px-2.5 sm:px-3 shadow-lg bg-(--fg-color)/8 border-(--border-line-color)/60 overflow-visible"
: "w-8 sm:w-9 px-0 justify-center overflow-hidden"
}`}
>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
if (isMuted) {
onToggleMute();
} else {
setShowVolumeSlider((prev) => !prev);
}
}}
onDoubleClick={(e) => {
e.stopPropagation();
onToggleMute();
}}
className="grid size-7 sm:size-8 place-items-center rounded-full text-(--fg-color)/70 hover:text-(--fg-color) transition-colors cursor-pointer shrink-0"
title={isMuted ? "取消静音" : "调整音量 (双击静音)"}
>
{isMuted || volume === 0 ? <VolumeMutedIcon size={15} /> : <VolumeIcon size={15} />}
</button>
<div
className={`flex items-center gap-2 grow min-w-0 transition-opacity duration-200 ${
showVolumeSlider || isDraggingVolume ? "opacity-100" : "opacity-0 pointer-events-none"
}`}
>
<span className="font-mono text-[9px] font-bold text-(--fg-color)/50 shrink-0 select-none">
{Math.round((isMuted ? 0 : volume) * 100)}%
</span>
<div
onPointerDown={handleVolumePointerDown}
onPointerMove={handleVolumePointerMove}
onPointerUp={handleVolumePointerUp}
className="grow h-3 flex items-center cursor-pointer group/voltrack"
title={`音量: ${Math.round((isMuted ? 0 : volume) * 100)}%`}
>
<div className="w-full h-1 bg-(--fg-color)/15 rounded-full group-hover/voltrack:h-1.5 transition-all relative">
<div
className="h-full bg-(--accent-color) rounded-full relative transition-all duration-75"
style={{ width: `${(isMuted ? 0 : volume) * 100}%` }}
>
<div className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 size-2.5 rounded-full bg-white border border-(--accent-color) shadow-sm group-hover/voltrack:scale-125 transition-transform z-30" />
</div>
</div>
</div>
</div>
</div>
</div>
<button
type="button"
onClick={(e) => {
if (isCollapsed) return;
e.stopPropagation();
onOpenDrawer();
}}
className="flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-(--fg-color)/8 hover:bg-(--fg-color)/15 text-xs text-(--fg-color) font-medium transition-all border border-(--border-line-color) cursor-pointer"
title="打开播放队列与搜索"
>
<PlaylistIcon size={15} weight="bold" />
<span className="hidden sm:inline text-[11px]">队列 ({playlistLength})</span>
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,107 @@
"use client";
import React, { useState } from "react";
interface PlayerProgressBarProps {
currentTime: number;
duration: number;
onSeek: (time: number) => void;
formatTime: (seconds: number) => string;
hasTrack?: boolean;
}
export default function PlayerProgressBar({
currentTime,
duration,
onSeek,
formatTime,
hasTrack = false,
}: PlayerProgressBarProps) {
const [isHovered, setIsHovered] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const [hoverTime, setHoverTime] = useState<number | null>(null);
const [hoverPositionRatio, setHoverPositionRatio] = useState(0);
const progressPercent = duration > 0 ? (currentTime / duration) * 100 : 0;
const calculateRatioFromEvent = (e: React.PointerEvent<HTMLDivElement>) => {
const rect = e.currentTarget.getBoundingClientRect();
const x = Math.max(0, Math.min(e.clientX - rect.left, rect.width));
return x / rect.width;
};
const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
setIsDragging(true);
e.currentTarget.setPointerCapture(e.pointerId);
const ratio = calculateRatioFromEvent(e);
setHoverPositionRatio(ratio);
if (duration > 0) {
onSeek(ratio * duration);
}
};
const handlePointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
const ratio = calculateRatioFromEvent(e);
setHoverPositionRatio(ratio);
if (duration > 0) {
setHoverTime(ratio * duration);
}
if (isDragging && duration > 0) {
onSeek(ratio * duration);
}
};
const handlePointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
if (isDragging) {
setIsDragging(false);
e.currentTarget.releasePointerCapture(e.pointerId);
}
};
return (
<div
onPointerDown={handlePointerDown}
onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => {
setIsHovered(false);
setHoverTime(null);
}}
className="absolute top-0 left-0 right-0 h-3.5 flex items-start cursor-pointer group z-20"
title="点击或拖动调整播放进度"
>
{/* 局部裁剪容器:高度与大圆角半径一致 (24px/h-6),利用 rounded-t-3xl 与 overflow-hidden 完美截断溢出圆弧的直角轨道 */}
<div className="absolute top-0 left-0 right-0 h-6 overflow-hidden rounded-t-3xl pointer-events-none w-full">
{/* 实际的进度条轨道 */}
<div className="w-full h-1 bg-(--fg-color)/15 transition-all duration-200 group-hover:h-2 relative">
<div
className="h-full bg-(--accent-color) transition-all duration-75"
style={{ width: `${progressPercent}%` }}
/>
</div>
</div>
{/* 进度条控制圆点:脱离 overflow-hidden 轨道层放置,以防边界剪裁 */}
{hasTrack && (
<div
className="absolute size-3.5 rounded-full bg-white border-2 border-(--accent-color) shadow-md animate-in zoom-in duration-150 z-30 pointer-events-none"
style={{
left: `calc(7px + ${progressPercent} * (100% - 14px) / 100)`,
top: isHovered ? "4px" : "2px",
transform: "translate(-50%, -50%)"
}}
/>
)}
{isHovered && hoverTime !== null && (
<div
className="absolute top-4 -translate-x-1/2 px-2 py-0.5 rounded-md bg-(--bg-dark-color) border border-(--border-line-color) text-[10px] font-mono text-(--fg-color) shadow-lg pointer-events-none z-30 animate-in fade-in duration-100"
style={{ left: `${hoverPositionRatio * 100}%` }}
>
{formatTime(hoverTime)}
</div>
)}
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
"use client";
import React from "react";
interface PlayerToastProps {
message: string | null;
onClose: () => void;
}
export default function PlayerToast({ message, onClose }: PlayerToastProps) {
if (!message) return null;
return (
<div className="fixed top-8 left-1/2 -translate-x-1/2 z-220 max-w-md px-5 py-3 rounded-2xl bg-(--bg-dark-color)/96 text-(--fg-color) border border-(--border-line-color) shadow-[0_12px_40px_rgba(0,0,0,0.35)] backdrop-blur-2xl flex items-center gap-3 animate-in fade-in slide-in-from-top-4 duration-300">
<span className="text-xs font-semibold px-2 py-0.5 rounded-full bg-(--accent-color)/15 text-(--accent-color) shrink-0">
提示
</span>
<p className="text-xs leading-relaxed text-(--fg-color) font-medium grow">{message}</p>
<button
type="button"
onClick={onClose}
className="text-xs text-(--fg-color)/40 hover:text-(--fg-color) shrink-0 ml-1 cursor-pointer"
aria-label="关闭提示"
>
✕
</button>
</div>
);
}
+701
View File
@@ -0,0 +1,701 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { ApiSearchResult, MusicSource, PlaybackMode, TrackDetail } from "@/interface/music";
import { resolveTrackDetails, searchMusic } from "@/api/music";
import { mockDefaultTracks } from "@/mock/music";
function formatTime(seconds: number) {
if (!Number.isFinite(seconds) || seconds < 0) return "00:00";
const minutes = Math.floor(seconds / 60);
const remaining = Math.floor(seconds % 60);
return `${String(minutes).padStart(2, "0")}:${String(remaining).padStart(2, "0")}`;
}
export function useAudioPlayer() {
const audioRef = useRef<HTMLAudioElement | null>(null);
const [playlist, setPlaylist] = useState<TrackDetail[]>([]);
const [currentIndex, setCurrentIndex] = useState(0);
const [isPlaying, setIsPlaying] = useState(false);
const [playMode, setPlayMode] = useState<PlaybackMode>("sequence");
const [currentTime, setCurrentTime] = useState(0);
const [duration, setDuration] = useState(0);
const [volume, setVolume] = useState(0.62);
const [isMuted, setIsMuted] = useState(false);
const [selectedSource, setSelectedSource] = useState<MusicSource>("netease");
const [isResolvingTrack, setIsResolvingTrack] = useState(false);
const [playerMessage, setPlayerMessage] = useState("");
const [brokenCovers, setBrokenCovers] = useState<Set<string>>(() => new Set());
const [toastMessage, setToastMessage] = useState<string | null>(null);
// 恢复进度相关 refs
const initialPositionRef = useRef<number | null>(null);
const hasRestoredPositionRef = useRef(false);
const failingTrackIdsRef = useRef<Set<string>>(new Set());
const enrichedTrackIdsRef = useRef<Set<string>>(new Set());
const resolvedTrackSrcIdsRef = useRef<Set<string>>(new Set());
const showToast = useCallback((msg: string) => {
setToastMessage(msg);
setTimeout(() => {
setToastMessage((prev) => (prev === msg ? null : prev));
}, 4000);
}, []);
const currentTrack = playlist[currentIndex] || mockDefaultTracks[0];
const currentTrackRef = useRef(currentTrack);
useEffect(() => {
currentTrackRef.current = currentTrack;
}, [currentTrack]);
// 换源重试错误处理
const handleTrackError = useCallback(async () => {
const track = currentTrackRef.current;
if (!track || failingTrackIdsRef.current.has(`${track.id}-${track.source}`)) {
setIsPlaying(false);
const errMsg = "全网暂无可用的音频播放路径";
setPlayerMessage(errMsg);
showToast(errMsg);
return;
}
failingTrackIdsRef.current.add(`${track.id}-${track.source}`);
setPlayerMessage(`音轨播放异常,正在自动换源重试...`);
const fallbackSources: MusicSource[] = (["netease", "kuwo", "bilibili"] as MusicSource[]).filter(
(s) => s !== track.source
);
let resolvedTrack: TrackDetail | null = null;
for (const src of fallbackSources) {
try {
const query = `${track.title} ${track.artist || ""}`.trim();
const searchRes = await searchMusic(query, src, 1);
if (searchRes.length > 0) {
resolvedTrack = await resolveTrackDetails(searchRes[0]);
if (resolvedTrack && resolvedTrack.src) {
break;
}
}
} catch {
continue;
}
}
if (resolvedTrack && resolvedTrack.src) {
const mergedTrack: TrackDetail = {
...track,
src: resolvedTrack.src,
source: resolvedTrack.source,
cover: track.cover || resolvedTrack.cover,
lyric: track.lyric || resolvedTrack.lyric,
};
setPlaylist((prevList) =>
prevList.map((t, idx) => (idx === currentIndex ? mergedTrack : t))
);
setPlayerMessage("");
showToast(`已为您自动切换至可用音源`);
setIsPlaying(true);
} else {
setIsPlaying(false);
const errMsg = "全网暂无可用的音频播放路径";
setPlayerMessage(errMsg);
showToast(errMsg);
}
}, [currentIndex, showToast]);
// 页面初始化:从 localStorage 恢复记录、进度与状态
useEffect(() => {
try {
const saved = localStorage.getItem("archive_player_state");
if (saved) {
const parsed = JSON.parse(saved);
if (Array.isArray(parsed.playlist) && parsed.playlist.length > 0) {
const hasInvalidCache = parsed.playlist.some(
(t: TrackDetail) =>
t.source === "joox" ||
t.id === "1u41XhDyuTRZ_BFM_EVpdA==" ||
t.id === "uPZirG1+JSxugKvPA7pyJQ=="
);
if (hasInvalidCache) {
setPlaylist(mockDefaultTracks);
setCurrentIndex(0);
} else {
setPlaylist(parsed.playlist);
}
}
if (typeof parsed.currentIndex === "number") {
setCurrentIndex(parsed.currentIndex);
}
if (parsed.selectedSource) {
setSelectedSource(parsed.selectedSource);
}
if (typeof parsed.volume === "number") {
setVolume(parsed.volume);
}
if (parsed.playMode) {
setPlayMode(parsed.playMode);
}
if (typeof parsed.currentTime === "number" && parsed.currentTime > 0) {
initialPositionRef.current = parsed.currentTime;
setCurrentTime(parsed.currentTime);
}
}
} catch {
// ignore storage error
}
}, []);
// 页面离开/刷新瞬间强行同步写入当前精确播放位置
useEffect(() => {
const saveCurrentStateImmediately = () => {
try {
const exactTime = audioRef.current?.currentTime || currentTime;
if (!hasRestoredPositionRef.current && initialPositionRef.current !== null && exactTime === 0) {
return;
}
localStorage.setItem(
"archive_player_state",
JSON.stringify({
playlist,
currentIndex,
selectedSource,
volume,
playMode,
currentTime: exactTime,
})
);
} catch {
// ignore storage error
}
};
const handleUnload = () => {
saveCurrentStateImmediately();
};
window.addEventListener("beforeunload", handleUnload);
window.addEventListener("pagehide", handleUnload);
return () => {
window.removeEventListener("beforeunload", handleUnload);
window.removeEventListener("pagehide", handleUnload);
};
}, [playlist, currentIndex, selectedSource, volume, playMode, currentTime]);
// 状态变更时防抖保存播放数据到 localStorage
useEffect(() => {
const timer = setTimeout(() => {
try {
const exactTime = audioRef.current?.currentTime || currentTime;
if (!hasRestoredPositionRef.current && initialPositionRef.current !== null && exactTime === 0) {
return;
}
localStorage.setItem(
"archive_player_state",
JSON.stringify({
playlist,
currentIndex,
selectedSource,
volume,
playMode,
currentTime: exactTime,
})
);
} catch {
// ignore storage error
}
}, 1000);
return () => clearTimeout(timer);
}, [playlist, currentIndex, selectedSource, volume, playMode, currentTime]);
// 自动按需补全当前播放曲目的歌词与海报封面 (通过 enrichedTrackIdsRef 防并发/无限次网络请求)
useEffect(() => {
if (!currentTrack || isResolvingTrack) return;
const trackId = `${currentTrack.source}-${currentTrack.id}`;
if (enrichedTrackIdsRef.current.has(trackId)) return;
const needCover = !currentTrack.cover || brokenCovers.has(currentTrack.id);
const needLyric = !currentTrack.lyric;
if (!needCover && !needLyric) {
// 已经齐全,标为已补全,无需后续无谓执行
enrichedTrackIdsRef.current.add(trackId);
return;
}
let isSubscribed = true;
// 标记为已启动补全流程,保证任何情况下都不会发起第二次关于该歌曲的补全请求
enrichedTrackIdsRef.current.add(trackId);
const enrichTrackDetails = async () => {
try {
const searchResult: ApiSearchResult = {
id: currentTrack.id,
name: currentTrack.title,
artist: currentTrack.artist,
album: currentTrack.album || "",
pic_id: currentTrack.picId || currentTrack.id,
lyric_id: currentTrack.lyricId || currentTrack.id,
source: currentTrack.source || "netease",
};
const resolved = await resolveTrackDetails(searchResult);
if (!isSubscribed) return;
if (resolved.cover || resolved.lyric) {
setPlaylist((prevList) =>
prevList.map((t, idx) => {
if (idx === currentIndex) {
return {
...t,
cover: t.cover || resolved.cover,
lyric: t.lyric || resolved.lyric,
tlyric: t.tlyric || resolved.tlyric,
};
}
return t;
})
);
}
} catch {
// ignore background enrichment error
}
};
void enrichTrackDetails();
return () => {
isSubscribed = false;
};
}, [currentTrack, currentIndex, isResolvingTrack, brokenCovers, setPlaylist]);
// 自动解析当前无 src 资源曲目的流媒体路径
useEffect(() => {
if (!currentTrack || isResolvingTrack) return;
if (currentTrack.src) return;
const trackId = `${currentTrack.source}-${currentTrack.id}`;
if (resolvedTrackSrcIdsRef.current.has(trackId)) return;
let isSubscribed = true;
setIsResolvingTrack(true);
setPlayerMessage(`正在解析播放路径 (${currentTrack.source})...`);
resolvedTrackSrcIdsRef.current.add(trackId);
const resolveCurrentTrackSrc = async () => {
const trySources: MusicSource[] = [
currentTrack.source,
...(["netease", "kuwo", "bilibili"] as MusicSource[]).filter((s) => s !== currentTrack.source),
];
let resolvedTrack: TrackDetail | null = null;
for (const src of trySources) {
try {
if (src === currentTrack.source) {
const searchResult: ApiSearchResult = {
id: currentTrack.id,
name: currentTrack.title,
artist: currentTrack.artist,
album: currentTrack.album || "",
pic_id: currentTrack.picId || currentTrack.id,
lyric_id: currentTrack.lyricId || currentTrack.id,
source: currentTrack.source,
};
resolvedTrack = await resolveTrackDetails(searchResult);
} else {
const searchRes = await searchMusic(currentTrack.title, src, 1);
if (searchRes.length > 0) {
resolvedTrack = await resolveTrackDetails(searchRes[0]);
}
}
if (resolvedTrack && resolvedTrack.src) {
break;
}
} catch {
continue;
}
}
if (!isSubscribed) return;
if (resolvedTrack && resolvedTrack.src) {
setPlaylist((prevList) =>
prevList.map((t, idx) => {
if (idx === currentIndex) {
return {
...t,
src: resolvedTrack!.src,
source: resolvedTrack!.source,
cover: t.cover || resolvedTrack!.cover,
lyric: t.lyric || resolvedTrack!.lyric,
tlyric: t.tlyric || resolvedTrack!.tlyric,
};
}
return t;
})
);
setPlayerMessage("");
setIsResolvingTrack(false);
} else {
showToast("全网暂无可用的播放路径,请尝试搜索其他曲目");
setIsResolvingTrack(false);
setPlayerMessage("");
setIsPlaying(false);
}
};
void resolveCurrentTrackSrc();
return () => {
isSubscribed = false;
setIsResolvingTrack(false);
setPlayerMessage("");
};
}, [currentTrack, currentIndex, isResolvingTrack, showToast, setIsPlaying]);
// 切换/重新点播当前歌曲时,自动清除该歌曲已尝试解析的 Ref 标记缓存,使其拥有重新解析和播放的机会
useEffect(() => {
if (currentTrack) {
const trackId = `${currentTrack.source}-${currentTrack.id}`;
resolvedTrackSrcIdsRef.current.delete(trackId);
}
}, [currentTrack]);
// 自动滚动裁剪/限流队列,确保播放队列长度始终恒定在 30 首,防止 DOM 卡顿
useEffect(() => {
if (playlist.length <= 30) return;
const excessCount = playlist.length - 30; // 剔除超出 30 长度的部分
// 优先从头部已播历史记录里进行滚动剔除,以保证接下来的待播曲目完整
if (currentIndex >= excessCount) {
setPlaylist((prev) => prev.slice(excessCount));
setCurrentIndex((prev) => prev - excessCount);
} else {
const headToRemove = currentIndex;
const tailToRemove = excessCount - headToRemove;
setPlaylist((prev) => {
const slicedHead = prev.slice(headToRemove);
return slicedHead.slice(0, slicedHead.length - tailToRemove);
});
setCurrentIndex(0);
}
}, [playlist.length, currentIndex]);
// 初始化 HTML5 Audio 实例
useEffect(() => {
const audio = new Audio();
audio.preload = "metadata";
audio.setAttribute("referrerpolicy", "no-referrer");
audioRef.current = audio;
const updateTime = () => {
if (audioRef.current) {
setCurrentTime(audioRef.current.currentTime || 0);
}
};
const updateDuration = () => setDuration(Number.isFinite(audio.duration) ? audio.duration : 0);
const handleError = () => {
void handleTrackError();
};
audio.addEventListener("timeupdate", updateTime);
audio.addEventListener("durationchange", updateDuration);
audio.addEventListener("loadedmetadata", updateDuration);
audio.addEventListener("error", handleError);
return () => {
audio.pause();
audio.removeEventListener("timeupdate", updateTime);
audio.removeEventListener("durationchange", updateDuration);
audio.removeEventListener("loadedmetadata", updateDuration);
audio.removeEventListener("error", handleError);
audio.removeAttribute("src");
audio.load();
audioRef.current = null;
};
}, [handleTrackError]);
// 音频源同步与延迟精确定位上次播放位置
useEffect(() => {
const audio = audioRef.current;
if (!audio || !currentTrack?.src) return;
const nextSource = new URL(currentTrack.src, window.location.origin).href;
if (audio.src !== nextSource) {
audio.src = nextSource;
audio.load();
if (!isResolvingTrack) {
setPlayerMessage("");
}
}
const applyRestoredPosition = () => {
if (!hasRestoredPositionRef.current && initialPositionRef.current !== null && initialPositionRef.current > 0) {
const targetTime = initialPositionRef.current;
hasRestoredPositionRef.current = true;
try {
audio.currentTime = targetTime;
setCurrentTime(targetTime);
} catch {
// ignore seek error
}
}
};
const handleReady = () => {
applyRestoredPosition();
};
audio.addEventListener("canplay", handleReady, { once: true });
audio.addEventListener("loadedmetadata", handleReady, { once: true });
if (audio.readyState >= 1) {
handleReady();
}
return () => {
audio.removeEventListener("canplay", handleReady);
audio.removeEventListener("loadedmetadata", handleReady);
};
}, [currentTrack, isResolvingTrack]);
// 播放与暂停状态精确控制:响应 isPlaying 状态的变化,确保点击暂停按钮能瞬间无条件响应
useEffect(() => {
const audio = audioRef.current;
if (!audio || !currentTrack?.src) return;
let isSubscribed = true;
if (isPlaying) {
const attemptPlay = () => {
if (!isSubscribed) return;
const promise = audio.play();
if (promise !== undefined) {
promise.catch((err: unknown) => {
if (!isSubscribed) return;
if (err instanceof Error) {
if (err.name === "AbortError") return;
if (err.name === "NotAllowedError") {
setIsPlaying(false);
const restorePos = initialPositionRef.current;
if (restorePos && restorePos > 0) {
showToast(`已恢复至上次进度 (${formatTime(restorePos)}),点击播放继续`);
} else {
showToast("浏览器阻止了自动播放,请手动点击播放按钮");
}
return;
}
}
setIsPlaying(false);
});
}
};
if (audio.readyState >= 1) {
attemptPlay();
} else {
const playWhenReady = () => {
attemptPlay();
};
audio.addEventListener("canplay", playWhenReady, { once: true });
return () => {
audio.removeEventListener("canplay", playWhenReady);
};
}
} else {
audio.pause();
}
return () => {
isSubscribed = false;
};
}, [isPlaying, currentTrack, showToast, setIsPlaying]);
// 音量控制
useEffect(() => {
const audio = audioRef.current;
if (!audio) return;
audio.volume = isMuted ? 0 : volume;
}, [isMuted, volume]);
const playNext = useCallback(() => {
if (playlist.length === 0) return;
if (playMode === "shuffle") {
setCurrentIndex(Math.floor(Math.random() * playlist.length));
} else {
setCurrentIndex((index) => (index + 1) % playlist.length);
}
setIsPlaying(true);
setPlayerMessage("");
}, [playMode, playlist.length]);
const playPrevious = useCallback(() => {
if (playlist.length === 0) return;
if ((audioRef.current?.currentTime || 0) > 4) {
if (audioRef.current) audioRef.current.currentTime = 0;
return;
}
setCurrentIndex((index) => (index - 1 + playlist.length) % playlist.length);
setIsPlaying(true);
setPlayerMessage("");
}, [playlist.length]);
const selectTrack = useCallback((index: number) => {
if (!playlist[index]) return;
setCurrentIndex(index);
setIsPlaying(true);
setPlayerMessage("");
}, [playlist]);
const cycleMode = useCallback(() => {
setPlayMode((mode) => (mode === "sequence" ? "repeat" : mode === "repeat" ? "shuffle" : "sequence"));
}, []);
const seek = useCallback((time: number) => {
const nextTime = Math.max(0, Math.min(time, duration || time));
setCurrentTime(nextTime);
if (audioRef.current) audioRef.current.currentTime = nextTime;
}, [duration]);
const removeTrack = useCallback(
(indexToRemove: number) => {
setPlaylist((tracks) => {
const newPlaylist = tracks.filter((_, i) => i !== indexToRemove);
if (newPlaylist.length === 0) {
setCurrentIndex(0);
setIsPlaying(false);
setPlayerMessage("");
return [];
}
if (indexToRemove < currentIndex) {
setCurrentIndex((idx) => idx - 1);
} else if (indexToRemove === currentIndex) {
setCurrentIndex((idx) => (idx >= newPlaylist.length ? 0 : idx));
}
return newPlaylist;
});
},
[currentIndex]
);
useEffect(() => {
const audio = audioRef.current;
if (!audio) return;
const handleEnded = () => {
if (playMode === "repeat") {
audio.currentTime = 0;
void audio.play();
return;
}
playNext();
};
audio.addEventListener("ended", handleEnded);
return () => audio.removeEventListener("ended", handleEnded);
}, [playMode, playNext]);
const resolveAndPlay = useCallback(
async (result: ApiSearchResult) => {
setIsResolvingTrack(true);
setPlayerMessage(`正在获取音轨 (${result.source})...`);
const trySources: MusicSource[] = [
result.source,
...(["netease", "kuwo", "bilibili", "joox"] as MusicSource[]).filter((s) => s !== result.source),
];
let resolvedTrack: TrackDetail | null = null;
for (const src of trySources) {
try {
if (src === result.source) {
resolvedTrack = await resolveTrackDetails(result);
} else {
setPlayerMessage(`原音轨暂不可用,正在尝试备用源 (${src})...`);
const searchRes = await searchMusic(result.name, src, 1);
if (searchRes.length > 0) {
resolvedTrack = await resolveTrackDetails(searchRes[0]);
}
}
if (resolvedTrack && resolvedTrack.src) {
break;
}
} catch {
continue;
}
}
if (!resolvedTrack || !resolvedTrack.src) {
showToast("全网暂无可用的播放路径,请尝试搜索其他曲目");
setIsResolvingTrack(false);
setPlayerMessage("");
return;
}
setPlaylist((tracks) => [resolvedTrack!, ...tracks.filter((t) => t.id !== resolvedTrack!.id)]);
setCurrentIndex(0);
setIsPlaying(true);
setIsResolvingTrack(false);
setPlayerMessage("");
},
[showToast]
);
const handleImportPlaylist = useCallback(
(importedTracks: TrackDetail[]) => {
setPlaylist((prevList) => {
const existingIds = new Set(prevList.map((t) => t.id));
const newTracks = importedTracks.filter((t) => !existingIds.has(t.id));
if (newTracks.length === 0) {
showToast("歌单中的曲目已在播放列表中");
return prevList;
}
showToast(`成功解析并导入 ${newTracks.length} 首歌单曲目!`);
return [...prevList, ...newTracks];
});
},
[showToast]
);
return {
playlist,
setPlaylist,
currentIndex,
setCurrentIndex,
currentTrack,
isPlaying,
setIsPlaying,
playMode,
setPlayMode,
currentTime,
setCurrentTime,
duration,
volume,
setVolume,
isMuted,
setIsMuted,
selectedSource,
setSelectedSource,
isResolvingTrack,
playerMessage,
brokenCovers,
setBrokenCovers,
toastMessage,
setToastMessage,
showToast,
selectTrack,
playNext,
playPrevious,
cycleMode,
seek,
removeTrack,
resolveAndPlay,
handleImportPlaylist,
};
}
+151
View File
@@ -0,0 +1,151 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import type { TrackDetail } from "@/interface/music";
interface UsePlayerFavoritesOptions {
showToast: (msg: string) => void;
setPlaylist: React.Dispatch<React.SetStateAction<TrackDetail[]>>;
setCurrentIndex: React.Dispatch<React.SetStateAction<number>>;
setIsPlaying: React.Dispatch<React.SetStateAction<boolean>>;
}
export function usePlayerFavorites({
showToast,
setPlaylist,
setCurrentIndex,
setIsPlaying,
}: UsePlayerFavoritesOptions) {
const [favorites, setFavorites] = useState<TrackDetail[]>([]);
// 页面初始化:从 localStorage 恢复收藏数据
useEffect(() => {
try {
const savedFavs = localStorage.getItem("archive_player_favorites");
if (savedFavs) {
const parsedFavs = JSON.parse(savedFavs);
if (Array.isArray(parsedFavs)) {
setFavorites(parsedFavs);
}
}
} catch {
// ignore storage error
}
}, []);
const isFavorite = useCallback(
(track: TrackDetail) => favorites.some((f) => f.id === track.id && f.source === track.source),
[favorites]
);
const toggleFavorite = useCallback(
(track: TrackDetail) => {
let isAdding = false;
setFavorites((prev) => {
const exists = prev.some((f) => f.id === track.id && f.source === track.source);
let nextFavs: TrackDetail[];
if (exists) {
nextFavs = prev.filter((f) => !(f.id === track.id && f.source === track.source));
showToast(`已将《${track.title}》移出收藏`);
} else {
isAdding = true;
nextFavs = [track, ...prev];
showToast(`已成功收藏《${track.title}》`);
}
try {
localStorage.setItem("archive_player_favorites", JSON.stringify(nextFavs));
} catch {
// ignore
}
return nextFavs;
});
if (isAdding && !track.cover) {
const enrichFavoriteTrack = async () => {
try {
const { resolveTrackDetails } = await import("@/api/music");
const searchResult = {
id: track.id,
name: track.title,
artist: track.artist,
album: track.album || "",
pic_id: track.picId || track.id,
lyric_id: track.lyricId || track.id,
source: track.source,
};
const resolved = await resolveTrackDetails(searchResult);
if (resolved && resolved.cover) {
setFavorites((prev) => {
const nextFavs = prev.map((f) => {
if (f.id === track.id && f.source === track.source) {
return {
...f,
cover: resolved.cover,
src: resolved.src || f.src,
lyric: f.lyric || resolved.lyric,
tlyric: f.tlyric || resolved.tlyric,
};
}
return f;
});
try {
localStorage.setItem("archive_player_favorites", JSON.stringify(nextFavs));
} catch {
// ignore
}
return nextFavs;
});
}
} catch {
// ignore
}
};
void enrichFavoriteTrack();
}
},
[showToast]
);
const playFavorites = useCallback(() => {
if (favorites.length === 0) return;
setPlaylist(favorites);
setCurrentIndex(0);
setIsPlaying(true);
showToast("已开始播放我的收藏歌曲");
}, [favorites, setPlaylist, setCurrentIndex, setIsPlaying, showToast]);
const clearFavorites = useCallback(() => {
setFavorites([]);
try {
localStorage.removeItem("archive_player_favorites");
} catch {
// ignore
}
showToast("已清空我的收藏");
}, [showToast]);
const playFavoriteTrack = useCallback(
(track: TrackDetail) => {
setPlaylist((prev) => {
const idx = prev.findIndex((t) => t.id === track.id && t.source === track.source);
if (idx >= 0) {
setCurrentIndex(idx);
return prev;
}
setCurrentIndex(0);
return [track, ...prev];
});
setIsPlaying(true);
},
[setCurrentIndex, setIsPlaying, setPlaylist]
);
return {
favorites,
isFavorite,
toggleFavorite,
playFavorites,
clearFavorites,
playFavoriteTrack,
};
}
+244
View File
@@ -0,0 +1,244 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import type { TrackDetail, MusicSource } from "@/interface/music";
import { getTrackPoster } from "@/lib/poster";
export interface PlaylistFolder {
id: string;
name: string;
cover?: string;
tracks: TrackDetail[];
createdAt: number;
}
interface UsePlayerPlaylistsOptions {
setPlaylist: React.Dispatch<React.SetStateAction<TrackDetail[]>>;
setCurrentIndex: React.Dispatch<React.SetStateAction<number>>;
setIsPlaying: React.Dispatch<React.SetStateAction<boolean>>;
showToast: (msg: string) => void;
}
export function usePlayerPlaylists({
setPlaylist,
setCurrentIndex,
setIsPlaying,
showToast,
}: UsePlayerPlaylistsOptions) {
const [playlists, setPlaylists] = useState<PlaylistFolder[]>([]);
// 页面初始化:从 localStorage 恢复已保存的“我的歌单”
useEffect(() => {
try {
const saved = localStorage.getItem("archive_player_playlists");
if (saved) {
const parsed = JSON.parse(saved);
if (Array.isArray(parsed)) {
setPlaylists(parsed);
}
}
} catch {
// 容错处理,忽略 storage 报错
}
}, []);
// 内部辅助:更新状态并同步持久化
const savePlaylists = (next: PlaylistFolder[]) => {
setPlaylists(next);
try {
localStorage.setItem("archive_player_playlists", JSON.stringify(next));
} catch {
// 忽略存储溢出或禁用错误
}
};
// 创建歌单
const createPlaylist = useCallback((name: string, tracks: TrackDetail[] = []) => {
const trimmedName = name.trim();
if (!trimmedName) return "";
const id = `folder_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
const newFolder: PlaylistFolder = {
id,
name: trimmedName,
tracks,
createdAt: Date.now(),
};
savePlaylists([newFolder, ...playlists]);
return id;
}, [playlists]);
// 重命名歌单
const renamePlaylist = useCallback((id: string, newName: string) => {
const trimmed = newName.trim();
if (!trimmed) return;
const next = playlists.map(pl => pl.id === id ? { ...pl, name: trimmed } : pl);
savePlaylists(next);
showToast(`歌单已重命名为《${trimmed}》`);
}, [playlists, showToast]);
// 删除歌单
const removePlaylist = useCallback((id: string) => {
const target = playlists.find(pl => pl.id === id);
if (!target) return;
const next = playlists.filter(pl => pl.id !== id);
savePlaylists(next);
showToast(`已删除歌单《${target.name}》`);
}, [playlists, showToast]);
// 将歌曲加入歌单 (单独点播时手动收藏或者从播放队列挪入)
const addTrackToPlaylist = useCallback((playlistId: string, track: TrackDetail) => {
let success = false;
const next = playlists.map(pl => {
if (pl.id === playlistId) {
const exists = pl.tracks.some(t => t.id === track.id && t.source === track.source);
if (exists) {
showToast(`《${track.title}》已在该歌单中`);
return pl;
}
success = true;
return { ...pl, tracks: [...pl.tracks, track] };
}
return pl;
});
if (success) {
savePlaylists(next);
const targetPl = playlists.find(p => p.id === playlistId);
if (targetPl) {
showToast(`已将《${track.title}》保存至歌单《${targetPl.name}》`);
}
}
}, [playlists, showToast]);
// 批量追加歌曲到某歌单(用于导入时直接追加到指定歌单,避免重复加入)
const addTracksToPlaylist = useCallback((playlistId: string, tracksToImport: TrackDetail[]) => {
let successCount = 0;
const next = playlists.map(pl => {
if (pl.id === playlistId) {
const existingKeys = new Set(pl.tracks.map(t => `${t.source}-${t.id}`));
const newTracks = tracksToImport.filter(t => !existingKeys.has(`${t.source}-${t.id}`));
if (newTracks.length === 0) {
showToast("导入的歌曲均已在目标歌单中");
return pl;
}
successCount = newTracks.length;
return { ...pl, tracks: [...pl.tracks, ...newTracks] };
}
return pl;
});
if (successCount > 0) {
savePlaylists(next);
const targetPl = playlists.find(p => p.id === playlistId);
showToast(`已成功将 ${successCount} 首歌曲导入歌单《${targetPl?.name || ""}》`);
}
}, [playlists, showToast]);
// 从特定歌单中移除一首歌
const removeTrackFromPlaylist = useCallback((playlistId: string, trackId: string, source: MusicSource) => {
const next = playlists.map(pl => {
if (pl.id === playlistId) {
return {
...pl,
tracks: pl.tracks.filter(t => !(t.id === trackId && t.source === source))
};
}
return pl;
});
savePlaylists(next);
showToast("已从歌单中移除该歌曲");
}, [playlists, showToast]);
// 核心逻辑:播放一首歌曲时,如果是属于某些歌单,则异步生成海报并自动以此海报做封面
const handleTrackPlayback = useCallback(async (track: TrackDetail) => {
// 1. 先异步生成/获取歌曲的海报 Base64 字符串
const posterUrl = await getTrackPoster(track);
if (!posterUrl) return;
// 2. 使用 setPlaylists 的函数式更新以解耦对外部 playlists 的依赖,彻底掐死 React 重新渲染的死循环
setPlaylists((prev) => {
// 检查当前是否有包含该歌曲的歌单,没有就不更新以避免无效重绘
const hasMatched = prev.some(pl =>
pl.tracks.some(t => t.id === track.id && t.source === track.source)
);
if (!hasMatched) return prev;
let isChanged = false;
const next = prev.map(pl => {
if (pl.tracks.some(t => t.id === track.id && t.source === track.source)) {
// 歌单封面固定逻辑:如果歌单已经拥有海报封面 (pl.cover 存在),则保持原封面,不再随播放频繁切换
if (pl.cover) return pl;
isChanged = true;
return { ...pl, cover: posterUrl };
}
return pl;
});
if (!isChanged) return prev;
// 同步到 localStorage
try {
localStorage.setItem("archive_player_playlists", JSON.stringify(next));
} catch {
// ignore
}
return next;
});
}, [setPlaylists]);
// 将歌单内的歌曲导入到播放队列
const addPlaylistToQueue = useCallback((playlistId: string, append = true) => {
const folder = playlists.find(pl => pl.id === playlistId);
if (!folder || folder.tracks.length === 0) {
showToast("该歌单中没有可播放的歌曲");
return;
}
if (append) {
// 追加模式:合并去重追加,防播放队列膨胀和卡顿
setPlaylist(prev => {
const existingIds = new Set(prev.map(t => `${t.source}-${t.id}`));
const newTracks = folder.tracks.filter(t => !existingIds.has(`${t.source}-${t.id}`));
if (newTracks.length === 0) {
showToast("歌单曲目已全部在播放列表中");
return prev;
}
showToast(`已成功将 ${newTracks.length} 首歌曲追加到播放队列`);
return [...prev, ...newTracks];
});
} else {
// 替换并播放模式
setPlaylist(folder.tracks);
setCurrentIndex(0);
setIsPlaying(true);
showToast(`已开始播放歌单《${folder.name}》`);
}
}, [playlists, setPlaylist, setCurrentIndex, setIsPlaying, showToast]);
// 播放歌单里单首曲目
const playPlaylistTrack = useCallback((track: TrackDetail) => {
setPlaylist((prev) => {
const idx = prev.findIndex((t) => t.id === track.id && t.source === track.source);
if (idx >= 0) {
setCurrentIndex(idx);
return prev;
}
setCurrentIndex(0);
return [track, ...prev];
});
setIsPlaying(true);
}, [setCurrentIndex, setIsPlaying, setPlaylist]);
return {
playlists,
createPlaylist,
renamePlaylist,
removePlaylist,
addTrackToPlaylist,
addTracksToPlaylist,
removeTrackFromPlaylist,
handleTrackPlayback,
addPlaylistToQueue,
playPlaylistTrack,
};
}
+35 -26
View File
@@ -1,36 +1,45 @@
import { useState, useEffect } from "react";
import { getPublicConfig } from "@/api/config";
"use client";
import { createContext, createElement, ReactNode, useContext, useMemo } from "react";
export interface SysConfig {
configKey: string;
configValue: string;
}
export function useSysConfig() {
const [configs, setConfigs] = useState<SysConfig[]>([]);
const [loading, setLoading] = useState(true);
interface SysConfigContextValue {
configs: SysConfig[];
loading: boolean;
isPageEnabled: (pageKey: string, defaultValue?: boolean) => boolean;
}
const defaultValue: SysConfigContextValue = {
configs: [],
loading: false,
isPageEnabled: (_pageKey, fallback = true) => fallback,
};
const SysConfigContext = createContext<SysConfigContextValue>(defaultValue);
useEffect(() => {
getPublicConfig()
.then((res) => res.data)
.then((data) => {
if (data.code === 200) {
setConfigs(data.data || []);
}
})
.catch((err) => {
console.warn("Failed to fetch public configs:", err);
})
.finally(() => {
setLoading(false);
});
}, []);
export function SysConfigProvider({
initialConfigs,
children,
}: {
initialConfigs: SysConfig[];
children: ReactNode;
}) {
const value = useMemo<SysConfigContextValue>(() => ({
configs: initialConfigs,
loading: false,
isPageEnabled: (pageKey: string, fallback = true) => {
const config = initialConfigs.find((item) => item.configKey === pageKey);
return config ? config.configValue === "true" : fallback;
},
}), [initialConfigs]);
const isPageEnabled = (pageKey: string, defaultValue = true) => {
const cfg = configs.find((c) => c.configKey === pageKey);
if (!cfg) return defaultValue;
return cfg.configValue === "true";
};
return createElement(SysConfigContext.Provider, { value }, children);
}
return { configs, loading, isPageEnabled };
export function useSysConfig() {
return useContext(SysConfigContext);
}
+55
View File
@@ -0,0 +1,55 @@
import {
CaretDown,
CaretUp,
CaretLeft,
MagnifyingGlass,
MusicNotes,
Pause,
Play,
Playlist,
Radio,
Repeat,
RepeatOnce,
Shuffle,
SkipBack,
SkipForward,
SpeakerHigh,
SpeakerSlash,
SpinnerGap,
Trash,
Waveform,
X,
Article,
Heart,
Folder,
PencilSimple,
Plus,
} from '@phosphor-icons/react';
export const musicIcons = {
caretDown: CaretDown,
caretUp: CaretUp,
caretLeft: CaretLeft,
close: X,
heart: Heart,
loading: SpinnerGap,
lyrics: Article,
music: MusicNotes,
next: SkipForward,
pause: Pause,
play: Play,
playlist: Playlist,
previous: SkipBack,
radio: Radio,
repeat: Repeat,
repeatOne: RepeatOnce,
search: MagnifyingGlass,
shuffle: Shuffle,
trash: Trash,
volume: SpeakerHigh,
volumeMuted: SpeakerSlash,
waveform: Waveform,
folder: Folder,
edit: PencilSimple,
plus: Plus,
} as const;
+59
View File
@@ -0,0 +1,59 @@
export type PlayerStyle = 'bottom-bar' | 'floating-capsule' | 'tape-dock';
export type PlaybackMode = 'sequence' | 'repeat' | 'shuffle';
export interface LyricLine {
time: number;
text: string;
translation?: string;
}
export type MusicApiErrorCode =
| 'INVALID_REQUEST'
| 'UPSTREAM_UNAVAILABLE'
| 'TRACK_UNAVAILABLE'
| 'STREAM_UNAVAILABLE';
export interface MusicApiErrorPayload {
code: MusicApiErrorCode;
message: string;
}
export type WaveformStatus = 'idle' | 'ready' | 'active' | 'fallback';
export interface RadioSysConfig {
playerStyle?: PlayerStyle;
showProgress?: boolean;
autoPlay?: boolean;
defaultVolume?: number;
bgmList?: TrackDetail[];
noiseList?: { name: string; src: string; icon?: string }[];
}
export type MusicSource = 'netease' | 'tencent' | 'kugou' | 'kuwo' | 'bilibili' | 'joox';
export interface ApiSearchResult {
id: string;
name: string;
artist: string | string[];
album: string;
pic_id: string;
url_id?: string;
lyric_id: string;
source: MusicSource;
}
export interface TrackDetail {
id: string;
title: string;
artist: string;
album: string;
src: string;
cover?: string;
picId?: string;
urlId?: string;
lyricId?: string;
lyric?: string;
tlyric?: string;
source: MusicSource;
}
+18
View File
@@ -0,0 +1,18 @@
import * as OpenCC from 'opencc-js';
const converterHK = OpenCC.Converter({ from: 'hk', to: 'cn' });
const converterTW = OpenCC.Converter({ from: 'tw', to: 'cn' });
/**
* 工业级 OpenCC 繁简转换器
* 全量覆盖香港繁体(HK)、台湾繁体(TW)到大陆简体(CN)的词汇与文字转换
*/
export function toSimplifiedChinese(text: string): string {
if (!text) return '';
try {
const resHK = converterHK(text);
return converterTW(resHK);
} catch {
return text;
}
}
+43
View File
@@ -0,0 +1,43 @@
interface ErrorLike {
code?: string;
message?: string;
name?: string;
status?: number;
response?: { status?: number };
cause?: unknown;
}
const globalLogState = globalThis as typeof globalThis & {
__blogFallbackLogKeys?: Set<string>;
};
const seenKeys = globalLogState.__blogFallbackLogKeys ?? new Set<string>();
globalLogState.__blogFallbackLogKeys = seenKeys;
function getErrorLike(error: unknown) {
return error && typeof error === "object" ? error as ErrorLike : {};
}
function isExpectedOfflineError(error: unknown) {
const candidate = getErrorLike(error);
const status = candidate.status ?? candidate.response?.status;
const message = `${candidate.name || ""} ${candidate.code || ""} ${candidate.message || ""}`.toLowerCase();
return (
status === 502 ||
status === 503 ||
status === 504 ||
message.includes("econnrefused") ||
message.includes("fetch failed") ||
message.includes("network error") ||
message.includes("timeout") ||
message.includes("aborted")
);
}
export function reportUnexpectedFallback(key: string, label: string, error: unknown) {
if (isExpectedOfflineError(error) || seenKeys.has(key)) return;
seenKeys.add(key);
const candidate = getErrorLike(error);
const summary = candidate.message || candidate.code || "unknown error";
console.warn(`${label}: ${summary}`);
}
+197
View File
@@ -0,0 +1,197 @@
import type { TrackDetail } from "@/interface/music";
// 内存海报缓存,避免对同一首歌曲重复绘制 Canvas 造成性能损耗
const posterCache = new Map<string, string>();
/**
* 异步获取或生成歌曲的海报 Base64 字符串
*/
export async function getTrackPoster(track: TrackDetail): Promise<string> {
const cacheKey = `${track.source}-${track.id}`;
if (posterCache.has(cacheKey)) {
return posterCache.get(cacheKey) || "";
}
const poster = await generateTrackPoster(track);
if (poster) {
posterCache.set(cacheKey, poster);
}
return poster;
}
/**
* 使用离屏 Canvas 异步绘制精致歌曲海报
* 优化:图片超时处理、跨域兜底、导出低分辨率/高压缩 jpeg 减小 LocalStorage 占用,规避卡顿
*/
function generateTrackPoster(track: TrackDetail): Promise<string> {
return new Promise((resolve) => {
// 延迟 200ms 执行,错开切歌/播放时的密集状态变化,确保主线程极度流畅
setTimeout(() => {
if (typeof window === "undefined" || typeof document === "undefined") {
resolve("");
return;
}
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
if (!ctx) {
resolve("");
return;
}
const width = 260;
const height = 260;
canvas.width = width;
canvas.height = height;
// 1. 绘制极具质感的深色微光渐变背景
const grad = ctx.createLinearGradient(0, 0, width, height);
grad.addColorStop(0, "#1f202e"); // 优雅紫灰
grad.addColorStop(0.5, "#151622"); // 暗夜深
grad.addColorStop(1, "#0d0e15"); // 极致深
ctx.fillStyle = grad;
ctx.fillRect(0, 0, width, height);
// 2. 绘制几圈高雅的同心波纹线,增加海报空气感/立体感
ctx.strokeStyle = "rgba(255, 255, 255, 0.025)";
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.arc(width / 2, height / 2 - 10, 70, 0, Math.PI * 2);
ctx.stroke();
ctx.beginPath();
ctx.arc(width / 2, height / 2 - 10, 95, 0, Math.PI * 2);
ctx.stroke();
const img = new Image();
// 允许 CORS 跨域请求
img.crossOrigin = "anonymous";
const drawTextAndResolve = () => {
// 3. 绘制文字信息
// 歌名
ctx.fillStyle = "#ffffff";
ctx.font = "bold 13px system-ui, -apple-system, sans-serif";
ctx.textAlign = "center";
let title = track.title || "未知曲目";
if (title.length > 16) title = title.substring(0, 14) + "...";
ctx.fillText(title, width / 2, height - 52);
// 歌手
ctx.fillStyle = "rgba(255, 255, 255, 0.6)";
ctx.font = "10px system-ui, -apple-system, sans-serif";
let artist = track.artist || "未知歌手";
if (artist.length > 20) artist = artist.substring(0, 18) + "...";
ctx.fillText(artist, width / 2, height - 36);
// 品牌底款
ctx.fillStyle = "rgba(255, 255, 255, 0.3)";
ctx.font = "normal 8px system-ui, -apple-system, sans-serif";
ctx.fillText("LIVE ARCHIVE • MUSIC", width / 2, height - 16);
// 4. 导出压缩 JPEG,进一步压缩 LocalStorage 占用 (单张大小降至 ~8KB)
try {
const dataUrl = canvas.toDataURL("image/jpeg", 0.7);
resolve(dataUrl);
} catch {
resolve("");
}
};
// 1.5s 极限超时保护,防图片请求卡死
const timeoutId = setTimeout(() => {
drawPlaceholderVinyl(ctx, width);
drawTextAndResolve();
}, 1500);
img.onload = () => {
clearTimeout(timeoutId);
try {
const imgSize = 110;
const imgX = (width - imgSize) / 2;
const imgY = 32;
const radius = 10;
// 绘制圆角剪裁区域
ctx.save();
ctx.beginPath();
ctx.moveTo(imgX + radius, imgY);
ctx.lineTo(imgX + imgSize - radius, imgY);
ctx.quadraticCurveTo(imgX + imgSize, imgY, imgX + imgSize, imgY + radius);
ctx.lineTo(imgX + imgSize, imgY + imgSize - radius);
ctx.quadraticCurveTo(imgX + imgSize, imgY + imgSize, imgX + imgSize - radius, imgY + imgSize);
ctx.lineTo(imgX + radius, imgY + imgSize);
ctx.quadraticCurveTo(imgX, imgY + imgSize, imgX, imgY + imgSize - radius);
ctx.lineTo(imgX, imgY + radius);
ctx.quadraticCurveTo(imgX, imgY, imgX + radius, imgY);
ctx.closePath();
ctx.clip();
// 渲染封面
ctx.drawImage(img, imgX, imgY, imgSize, imgSize);
ctx.restore();
// 加一圈微弱亮边框以凸显层次
ctx.strokeStyle = "rgba(255, 255, 255, 0.08)";
ctx.lineWidth = 1;
ctx.strokeRect(imgX, imgY, imgSize, imgSize);
drawTextAndResolve();
} catch {
// toDataURL 受污染报错降级
drawPlaceholderVinyl(ctx, width);
drawTextAndResolve();
}
};
img.onerror = () => {
clearTimeout(timeoutId);
drawPlaceholderVinyl(ctx, width);
drawTextAndResolve();
};
if (track.cover) {
img.src = track.cover;
} else {
clearTimeout(timeoutId);
drawPlaceholderVinyl(ctx, width);
drawTextAndResolve();
}
}, 200);
});
}
/**
* 绘制高质感的胶片唱片占位,当封面加载失败时兜底
*/
function drawPlaceholderVinyl(ctx: CanvasRenderingContext2D, width: number) {
const size = 110;
const cx = width / 2;
const cy = 32 + size / 2;
// 1. 唱片黑盘
ctx.fillStyle = "#16161a";
ctx.beginPath();
ctx.arc(cx, cy, size / 2, 0, Math.PI * 2);
ctx.fill();
// 2. 黑胶轨道纹路
ctx.strokeStyle = "rgba(255, 255, 255, 0.04)";
ctx.lineWidth = 1.5;
for (let r = 12; r < size / 2; r += 10) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2);
ctx.stroke();
}
// 3. 经典胶碟红心
ctx.fillStyle = "#f43f5e"; // 暖红心
ctx.beginPath();
ctx.arc(cx, cy, 14, 0, Math.PI * 2);
ctx.fill();
// 4. 黑洞中心孔
ctx.fillStyle = "#0c0d12";
ctx.beginPath();
ctx.arc(cx, cy, 3, 0, Math.PI * 2);
ctx.fill();
}
+23
View File
@@ -0,0 +1,23 @@
import { TrackDetail } from '@/interface/music';
export const mockDefaultTracks: TrackDetail[] = [
{
id: '1971054019',
title: '归期',
artist: '钱润玉',
album: '凡人修仙传 动画原声带',
src: '/api/music?types=stream&source=netease&id=1971054019&name=%E5%BD%92%E6%9C%9F&br=320000',
urlId: '1971054019',
lyricId: '1971054019',
source: 'netease',
cover: 'https://p1.music.126.net/zO8jK8sLhFhS2L2O2X1wQA==/109951167733479075.jpg',
lyric: `[00:00.00] 归期 - 钱润玉 (凡人修仙传)
[00:02.00] 词:王耀光 曲:王耀光
[00:15.00] 寒风吹过长夜 漫漫归途
[00:22.00] 剑影交错 斩不断红尘执念
[00:30.00] 踏遍千山万水 终寻归期
[00:38.00] 纵使岁月苍老 心如最初`
}
];