feat: 迁移架构&实现功能

- 持久化音量设置
- 搜索页支持自定义每页显示数量(持久化)
- vite-electron-plugin迁移electron-vite
This commit is contained in:
lqtmcstudio
2026-02-06 14:50:33 +08:00
parent 6cda900c8d
commit d6e1d11a52
37 changed files with 867 additions and 1732 deletions

16
src/renderer/index.html Normal file
View File

@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Vue + TS</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="src/main.ts"></script>
</body>
</html>

View File

@@ -26,5 +26,5 @@ onMounted(async () => {
</script>
<style>
@import "./styles/main.css";
@import "styles/main.css";
</style>

View File

@@ -234,6 +234,7 @@ const drawSpectrum = () => {
// Adjust canvas size
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
@@ -241,7 +242,7 @@ const drawSpectrum = () => {
const width = rect.width;
const height = rect.height;
ctx.clearRect(0, 0, width, height);
const targetData = playerStore.spectrum;
@@ -251,8 +252,8 @@ const drawSpectrum = () => {
// Adjust speed (0.1 - 0.3) for desired smoothness
const lerpSpeed = 0.15;
for (let i = 0; i < 32; i++) {
const target = targetData[i] || 0;
currentData[i] = currentData[i] + (target - currentData[i]) * lerpSpeed;
const target = targetData[i] || 0;
currentData[i] = currentData[i] + (target - currentData[i]) * lerpSpeed;
}
// 2. Draw Smooth Wave
@@ -260,7 +261,7 @@ const drawSpectrum = () => {
ctx.moveTo(0, height);
const pointCount = currentData.length;
// Use a subset if desired, but 32 is fine.
// Use a subset if desired, but 32 is fine.
// We want the wave to be centered or span the width.
const step = width / (pointCount - 1);
@@ -272,14 +273,14 @@ const drawSpectrum = () => {
for (let i = 0; i < pointCount - 1; i++) {
const xCurr = i * step;
const yCurr = height - (currentData[i] * height * 0.5);
const xNext = (i + 1) * step;
const yNext = height - (currentData[i + 1] * height * 0.5);
// Control point for quadratic curve (midpoint)
const xMid = (xCurr + xNext) / 2;
const yMid = (yCurr + yNext) / 2;
ctx.quadraticCurveTo(xCurr, yCurr, xMid, yMid);
}
@@ -296,13 +297,13 @@ const drawSpectrum = () => {
const gradient = ctx.createLinearGradient(0, height - 200, 0, height);
gradient.addColorStop(0, 'rgba(255, 255, 255, 0.4)');
gradient.addColorStop(1, 'rgba(255, 255, 255, 0.05)');
ctx.fillStyle = gradient;
// Add blur effect
ctx.shadowBlur = 20;
ctx.shadowColor = 'rgba(255, 255, 255, 0.5)';
ctx.fill();
// Reset shadow for next frame (performance)

View File

@@ -179,7 +179,8 @@ const handleBarClick = (e: MouseEvent) => {
};
// Utils
const formatTime = (seconds: number) => {
const formatTime = (seconds2: number) => {
const seconds = Math.floor(seconds2 / 1000);
if (!seconds || isNaN(seconds)) return '00:00';
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60);

View File

@@ -27,7 +27,6 @@ const hasSongs = computed(() => playerStore.playlist.length > 0);
</script>
<style>
/* 关键修复:全局重置盒模型 */
/* 这确保 width: 100% + padding 不会撑破容器 */
*, *::before, *::after {
box-sizing: border-box;
@@ -67,13 +66,12 @@ body {
flex-direction: column;
position: relative;
overflow: hidden;
/* 关键修复:防止 flex 子项内容过宽撑开容器 */
min-width: 0;
}
.page-content {
flex: 1;
overflow-y: auto; /* 只允许内容区域滚动 */
overflow-y: auto;
padding: 0;
background-color: var(--color-bg-primary);
position: relative;

View File

@@ -4,7 +4,6 @@ import { createPinia } from 'pinia'
import { createRouter, createWebHashHistory } from 'vue-router'
import App from './App.vue'
import TDesign from 'tdesign-vue-next'
import 'tdesign-vue-next/es/style/index.css'
const pinia = createPinia()
@@ -42,7 +41,6 @@ const router = createRouter({
const app = createApp(App)
app.use(pinia)
app.use(router)
app.use(TDesign)
app.mount('#app')
// --- TEST: Auto Play Specific Song ---

View File

@@ -1,7 +1,8 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { ref, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import type { Song } from '../types/song';
import { parseLyric } from '../utils/lyricParser';
export enum PlayMode {
List = 'list',
@@ -24,9 +25,19 @@ export const usePlayerStore = defineStore('player', () => {
// State
const isPlaying = ref(false);
const currentSong = ref<Song | null>(null);
const volume = ref(50);
const duration = ref(0);
const currentTime = ref(0);
const savedVolume = localStorage.getItem('qz-player-volume');
const volume = ref(savedVolume ? Number(savedVolume) : 50); // 1~100
// Persistence & Sync
watch(volume, (newVol) => {
localStorage.setItem('qz-player-volume', newVol.toString());
});
// Sync initial volume to backend
if (window.electronAPI?.qzplayer) {
window.electronAPI.qzplayer.setVolume(volume.value).catch(console.error);
}
const duration = ref(0); //毫秒级
const currentTime = ref(0); //毫秒级
// Audio Visualization State
const loudness = ref(0);
@@ -45,8 +56,10 @@ export const usePlayerStore = defineStore('player', () => {
const MAX_RETRY_COUNT = 3;
const hasRetriedWithFreshUrl = ref(false);
// --- Helpers ---
// Lyrics State
const lyrics = ref<{ lines: any[] }>({ lines: [] });
// --- Helpers ---
const activateDummyAudio = async () => {
if (dummyAudio.paused) {
try {
@@ -77,8 +90,6 @@ export const usePlayerStore = defineStore('player', () => {
// --- Actions ---
const setPlaylist = async (list: any[], startIndex = 0) => {
playlist.value = list;
currentIndex.value = startIndex;
@@ -98,12 +109,13 @@ export const usePlayerStore = defineStore('player', () => {
await activateDummyAudio();
updateMediaSession(song);
fetchLyrics(song);
// 1. Get URL (Cache -> Network)
// Get URL (Cache -> Network)
let playUrl = song.url;
if (song.type === 'Remote' && song.source) {
// Use Local Proxy
const quality = 'jymaster';
const quality = 'hires';
playUrl = `http://localhost:5266/music?source=${song.source}&id=${song.id}&quality=${quality}`;
console.log('[Player] Using Proxy:', playUrl);
}
@@ -120,11 +132,33 @@ export const usePlayerStore = defineStore('player', () => {
} catch (e) {
// IPC call failed (rare), handle sync error
console.error("IPC Play request failed:", e);
handlePlayError();
handlePlayError().then();
}
} else {
console.warn("Song has no URL");
handlePlayError();
handlePlayError().then();
}
};
const fetchLyrics = async (song: Song) => {
lyrics.value = { lines: [] }; // Reset
if (!song || !song.id) return;
try {
// Check if plugin API exists
if (window.electronAPI?.plugin?.getLyric) {
const rawLyric = await window.electronAPI.plugin.getLyric(song.source || 'kw', song.id.toString());
if (rawLyric) {
const parsedLines = parseLyric(rawLyric);
if (parsedLines) {
lyrics.value = { lines: parsedLines };
}
console.log(lyrics)
}
} else {
MessagePlugin.warning("当前插件不支持歌词获取").then()
}
} catch (e) {
console.error('Failed to fetch lyrics:', e);
}
};
@@ -145,7 +179,7 @@ export const usePlayerStore = defineStore('player', () => {
navigator.mediaSession.setActionHandler('seekto', (details) => {
if (details.seekTime != null) {
seek(details.seekTime);
seek(details.seekTime).then();
}
});
};
@@ -182,7 +216,7 @@ export const usePlayerStore = defineStore('player', () => {
// Normal error handling
playErrorCount.value++;
hasRetriedWithFreshUrl.value = false; // Reset for next song
hasRetriedWithFreshUrl.value = false;
if (playlist.value.length === 0) {
isPlaying.value = false;
@@ -191,13 +225,13 @@ export const usePlayerStore = defineStore('player', () => {
return;
}
if (playErrorCount.value >= MAX_RETRY_COUNT) {
window.electronAPI.qzplayer.pause();
window.electronAPI.qzplayer.pause().then();
isPlaying.value = false;
MessagePlugin.error('连续多次播放失败,已停止播放');
MessagePlugin.error('连续多次播放失败,已停止播放').then();
playErrorCount.value = 0;
syncDummyAudioState(false);
} else {
MessagePlugin.warning(`播放失败,尝试播放下一首 (${playErrorCount.value}/${MAX_RETRY_COUNT})`);
MessagePlugin.warning(`播放失败,尝试播放下一首 (${playErrorCount.value}/${MAX_RETRY_COUNT})`).then();
setTimeout(() => next(false), 500);
}
};
@@ -209,11 +243,10 @@ export const usePlayerStore = defineStore('player', () => {
if (data.name === 'pause') {
const isPaused = data.data;
isPlaying.value = !isPaused;
// 核心qzplayer 暂停 -> 同步暂停 Dummy -> 浏览器更新 SMTC 状态
syncDummyAudioState(!isPaused);
}
if (data.name === 'time-pos') currentTime.value = data.data;
if (data.name === 'duration') duration.value = data.data;
if (data.name === 'time-pos') currentTime.value = data.data; //毫秒级
if (data.name === 'duration') duration.value = data.data; //毫秒级
if (data.name === 'loudness') loudness.value = data.data;
if (data.name === 'spectrum') spectrum.value = data.data;
}
@@ -223,7 +256,7 @@ export const usePlayerStore = defineStore('player', () => {
if (reason === 'eof') {
next(false);
} else if (reason === 'error') {
handlePlayError();
handlePlayError().then();
}
}
});
@@ -271,6 +304,8 @@ export const usePlayerStore = defineStore('player', () => {
setVolume,
seek,
toggleMode,
toggleFullScreen
toggleFullScreen,
lyrics,
fetchLyrics
};
});

View File

@@ -3,7 +3,6 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {

View File

@@ -16,6 +16,7 @@ export interface IElectronAPI {
plugin: {
call: (pluginId: string, method: string, args: any[]) => Promise<any>;
search: (pluginId: string, query: string, page: number, limit: number) => Promise<any>;
getLyric: (pluginId: string, id: string) => Promise<any>;
};
// Cache Control
getCacheInfo: () => Promise<{ path: string; size: string; persistCache: boolean }>;

View File

@@ -2,10 +2,27 @@
<div class="view-container search-view">
<div class="content-wrapper">
<div class="search-header">
<h1 class="search-title">搜索: "{{ query }}"</h1>
<span class="result-count">找到 {{ total }} 个结果</span>
<div class="header-left">
<h1 class="search-title">搜索: "{{ query }}"</h1>
<span class="result-count">找到 {{ total }} 个结果</span>
</div>
<button class="icon-btn" @click="showSettings = !showSettings" :class="{ active: showSettings }" title="搜索设置">
<Icon icon="lucide:settings-2" />
</button>
</div>
<transition name="slide-fade">
<div class="settings-panel" v-if="showSettings">
<div class="setting-item">
<span class="setting-label">每页显示: {{ limit }} </span>
<div class="slider-container">
<input type="range" min="10" max="100" step="10" v-model.number="limit" class="setting-slider">
<div class="slider-track" :style="{ width: ((limit - 10) / 90) * 100 + '%' }"></div>
</div>
</div>
</div>
</transition>
<div class="song-list-container" v-if="!loading && songs.length > 0">
<div class="list-header">
<div class="col-index">#</div>
@@ -71,19 +88,21 @@
<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useRoute } from 'vue-router';
import { Icon } from '@iconify/vue';
import { usePlayerStore } from '../stores/player';
import { transformSearchSong } from '../utils/songUtils';
import type { Song } from '../types/song';
const route = useRoute();
const router = useRouter();
const playerStore = usePlayerStore();
const query = computed(() => route.query.q as string || '');
const currentPage = ref(1);
const limit = ref(30);
const showSettings = ref(false);
const savedLimit = localStorage.getItem('qz-search-limit');
const limit = ref(savedLimit ? Number(savedLimit) : 30);
const total = ref(0);
const loading = ref(false);
const songs = ref<Song[]>([]);
@@ -110,7 +129,7 @@ const visiblePages = computed(() => {
start = Math.max(1, start - ((current + delta) - total));
}
const pages = [];
const pages: number[] = [];
for (let i = start; i <= end; i++) {
pages.push(i);
}
@@ -191,6 +210,12 @@ watch(query, () => {
currentPage.value = 1;
fetchData();
}, { immediate: true });
watch(limit, (newLimit) => {
localStorage.setItem('qz-search-limit', newLimit.toString());
currentPage.value = 1;
fetchData();
});
</script>
@@ -210,6 +235,12 @@ watch(query, () => {
.search-header {
margin-bottom: 24px;
display: flex;
justify-content: space-between;
align-items: center;
}
.header-left {
text-align: left;
}
@@ -239,6 +270,113 @@ watch(query, () => {
color: var(--color-text-muted);
}
.icon-btn {
background: transparent;
border: none;
color: var(--color-text-secondary);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
border-radius: 8px;
width: 36px;
height: 36px;
transition: all 0.2s;
}
.icon-btn:hover {
background: var(--color-bg-tertiary);
color: var(--color-text-primary);
}
.icon-btn.active {
background: var(--color-bg-tertiary);
color: var(--color-accent);
}
/* Settings Panel */
.settings-panel {
background: var(--color-bg-secondary);
border-radius: var(--radius-lg);
padding: 16px 20px;
margin-bottom: 20px;
border: 1px solid var(--color-border);
}
.setting-item {
display: flex;
align-items: center;
gap: 16px;
}
.setting-label {
font-size: 14px;
color: var(--color-text-secondary);
min-width: 100px;
}
.slider-container {
position: relative;
width: 200px;
height: 4px;
background: var(--color-bg-tertiary);
border-radius: 2px;
display: flex;
align-items: center;
}
.setting-slider {
appearance: none;
position: absolute;
width: 100%;
height: 100%;
background: transparent;
top: 0;
left: 0;
margin: 0;
z-index: 2;
cursor: pointer;
}
.setting-slider::-webkit-slider-thumb {
-webkit-appearance: none;
width: 12px;
height: 12px;
border-radius: 50%;
background: var(--color-accent);
cursor: pointer;
box-shadow: 0 0 4px rgba(0,0,0,0.2);
}
.slider-track {
position: absolute;
top: 0;
left: 0;
height: 100%;
background: var(--color-accent);
border-radius: 2px;
pointer-events: none;
z-index: 1;
}
.slide-fade-enter-active,
.slide-fade-leave-active {
transition: all 0.3s ease;
max-height: 100px;
overflow: hidden;
opacity: 1;
}
.slide-fade-enter-from,
.slide-fade-leave-to {
max-height: 0;
opacity: 0;
margin-bottom: 0;
padding-top: 0;
padding-bottom: 0;
border-width: 0;
}
/* List Grid Layout */
.list-header, .song-item {
display: grid;