refactor: 更新 eslint 和 prettier 配置 格式化代码

This commit is contained in:
alger
2025-07-23 23:54:35 +08:00
parent d1f5c8af84
commit c08c2cbf19
134 changed files with 3887 additions and 3301 deletions

View File

@@ -1,4 +0,0 @@
node_modules
dist
out
.gitignore

View File

@@ -1,137 +0,0 @@
/* eslint-env node */
require('@rushstack/eslint-patch/modern-module-resolution');
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'@vue/typescript/recommended',
'plugin:vue/vue3-recommended',
'plugin:vue-scoped-css/base',
'@electron-toolkit',
'@electron-toolkit/eslint-config-ts/eslint-recommended',
'plugin:prettier/recommended'
],
env: {
browser: true,
node: true,
jest: true,
es6: true
},
globals: {
defineProps: 'readonly',
defineEmits: 'readonly'
},
plugins: ['vue', '@typescript-eslint', 'simple-import-sort'],
parserOptions: {
parser: '@typescript-eslint/parser',
sourceType: 'module',
allowImportExportEverywhere: true,
ecmaFeatures: {
jsx: true
}
},
settings: {
'import/extensions': ['.js', '.jsx', '.ts', '.tsx']
},
rules: {
'vue/require-default-prop': 'off',
'vue/multi-word-component-names': 'off',
'no-underscore-dangle': 'off',
'no-nested-ternary': 'off',
'no-console': 'off',
'no-await-in-loop': 'off',
'no-continue': 'off',
'no-restricted-syntax': 'off',
'no-return-assign': 'off',
'no-unused-expressions': 'off',
'no-return-await': 'off',
'no-plusplus': 'off',
'no-param-reassign': 'off',
'no-shadow': 'off',
'guard-for-in': 'off',
'import/extensions': 'off',
'import/no-unresolved': 'off',
'import/no-extraneous-dependencies': 'off',
'import/prefer-default-export': 'off',
'import/first': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'vue/first-attribute-linebreak': 0,
'@typescript-eslint/no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_'
}
],
'no-unused-vars': [
'error',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_'
}
],
'no-use-before-define': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/ban-types': 'off',
'class-methods-use-this': 'off',
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error'
},
overrides: [
{
files: ['*.vue'],
rules: {
'vue/component-name-in-template-casing': [2, 'kebab-case'],
'vue/require-default-prop': 0,
'vue/multi-word-component-names': 0,
'vue/no-reserved-props': 0,
'vue/no-v-html': 0,
'vue-scoped-css/enforce-style-type': [
'error',
{
allows: ['scoped']
}
],
'@typescript-eslint/explicit-function-return-type': 'off',
// 需要行尾分号
'prettier/prettier': ['error', { endOfLine: 'auto' }]
}
},
{
files: ['*.ts', '*.tsx'],
rules: {
'max-classes-per-file': 'off',
'no-await-in-loop': 'off',
'dot-notation': 'off',
'constructor-super': 'off',
'getter-return': 'off',
'no-const-assign': 'off',
'no-dupe-args': 'off',
'no-dupe-class-members': 'off',
'no-dupe-keys': 'off',
'no-func-assign': 'off',
'no-import-assign': 'off',
'no-new-symbol': 'off',
'no-obj-calls': 'off',
'no-redeclare': 'off',
'no-setter-return': 'off',
'no-this-before-super': 'off',
'no-undef': 'off',
'no-unreachable': 'off',
'no-unsafe-negation': 'off',
'no-var': 'error',
'prefer-const': 'error',
'prefer-rest-params': 'error',
'prefer-spread': 'error',
'valid-typeof': 'off',
'consistent-return': 'off',
'no-promise-executor-return': 'off',
'prefer-promise-reject-errors': 'off',
'@typescript-eslint/explicit-function-return-type': 'off'
}
}
]
};

View File

@@ -1,6 +1,6 @@
name: 反馈 Bug
description: 通过 github 模板进行 Bug 反馈。
title: "描述问题的标题"
title: '描述问题的标题'
body:
- type: markdown
attributes:

View File

@@ -1,6 +1,6 @@
name: 反馈新功能
description: 通过 github 模板进行新功能反馈。
title: "描述问题的标题"
title: '描述问题的标题'
body:
- type: markdown
attributes:

View File

@@ -1,4 +1,5 @@
## IssueShoot
- 预估时长: {{ .duration }}
- 期望完成时间: {{ .deadline }}
- 开发难度: {{ .level }}

View File

@@ -36,7 +36,7 @@ jobs:
host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USERNAME }}
key: ${{ secrets.DEPLOY_KEY }}
source: "out/renderer/*"
source: 'out/renderer/*'
target: ${{ secrets.DEPLOY_PATH }}
strip_components: 2

View File

@@ -1,5 +0,0 @@
singleQuote: true
semi: true
printWidth: 100
trailingComma: none
endOfLine: auto

View File

@@ -1,29 +1,32 @@
# 更新日志
## v4.8.2
### 🎨 优化
- 重新设计pc端歌词页面Mini播放栏
- 添加清除歌曲自定义解析功能
### 🐛 Bug 修复
- 修复歌曲单独解析失败问题
- 修复歌词页面加入歌单抽屉被遮挡问题
## v4.8.1
### 🐛 Bug 修复
- 修复无法快捷键调整问题
### 🎨 优化
- 优化音乐资源解析
- 去除无用代码,优化加载速度
## v4.8.0
### ✨ 新功能
- 增强移动端播放页面效果,添加播放模式选择,添加横屏模式,添加播放列表功能 ([81b61e4](https://github.com/algerkong/AlgerMusicPlayer/commit/81b61e4))([0d89e15](https://github.com/algerkong/AlgerMusicPlayer/commit/0d89e15))([9345805](https://github.com/algerkong/AlgerMusicPlayer/commit/9345805))
- 优化移动端界面动画效果,播放栏,返回效果等一系列功能
- 添加下载管理页面, 引入文件类型检测库以支持多种音频格式,支持自定义文件名格式和下载路径配置 ([3ac3159](https://github.com/algerkong/AlgerMusicPlayer/commit/3ac3159)),([b203077](https://github.com/algerkong/AlgerMusicPlayer/commit/b203077))
@@ -34,7 +37,8 @@
- 添加歌词时间矫正功能,支持增加和减少矫正时间 ([c975344](https://github.com/algerkong/AlgerMusicPlayer/commit/c975344))
### 🐛 Bug 修复
- 修复音频初始化音量问题,完善翻译 ([#320](https://github.com/algerkong/AlgerMusicPlayer/pull/320)) 感谢[Qumo](https://github.com/Hellodwadawd12312312)的pr
- 修复音频初始化音量问题,完善翻译 ([#320](https://github.com/algerkong/AlgerMusicPlayer/pull/320)) 感谢[Qumo](https://github.com/Hellodwadawd12312312)的pr
- 重构每日推荐数据加载逻辑,提取为独立函数并优化用户状态判断 ([5e704a1](https://github.com/algerkong/AlgerMusicPlayer/commit/5e704a1))
- 修复刷新后第一次播放出现的无法播放问题 ([6f1909a](https://github.com/algerkong/AlgerMusicPlayer/commit/6f1909a))
- 修复更多设置弹窗被歌词窗口遮挡问题,并优化为互斥弹窗,优化样式 ([62e5166](https://github.com/algerkong/AlgerMusicPlayer/commit/62e5166))
@@ -42,8 +46,8 @@
- 修复音频服务相关问题 ([090103b](https://github.com/algerkong/AlgerMusicPlayer/commit/090103b)),([5ee60d7](https://github.com/algerkong/AlgerMusicPlayer/commit/5ee60d7))
- 修复播放栏无法控制隐藏问题 ([d227ac8](https://github.com/algerkong/AlgerMusicPlayer/commit/d227ac8))
### 🎨 优化
- 优化歌曲列表组件布局([fabcf28](https://github.com/algerkong/AlgerMusicPlayer/commit/fabcf28))
- 重构播放控制逻辑,添加播放进度恢复功能并清理无用代码 ([b9c38d2](https://github.com/algerkong/AlgerMusicPlayer/commit/b9c38d2))
- 优化提示组件,支持位置和图标显示选项 ([155bdf2](https://github.com/algerkong/AlgerMusicPlayer/commit/155bdf2))
@@ -53,7 +57,9 @@
- 代码优化
## 赞赏支持☕️
[赞赏列表](http://donate.alger.fun/)
<table>
<tr>
<th style="text-align:center">微信赞赏</th>

38
DEV.md
View File

@@ -105,18 +105,18 @@ AlgerMusicPlayer/
渲染进程是基于 Vue 3 的前端应用,负责 UI 渲染和用户交互。
- **components/**: 包含各种 UI 组件
  - **common/**: 通用组件
  - **home/**: 首页相关组件
  - **lyric/**: 歌词显示组件
  - **settings/**: 设置界面组件
  - **MusicList.vue**: 音乐列表组件
  - **MvPlayer.vue**: MV 播放器
  - **EQControl.vue**: 均衡器控制
  - **...**: 其他组件
  - **common/**: 通用组件
  - **home/**: 首页相关组件
  - **lyric/**: 歌词显示组件
  - **settings/**: 设置界面组件
  - **MusicList.vue**: 音乐列表组件
  - **MvPlayer.vue**: MV 播放器
  - **EQControl.vue**: 均衡器控制
  - **...**: 其他组件
- **store/**: Pinia 状态管理
  - **modules/**: 各功能模块的状态管理
  - **index.ts**: 状态管理入口
  - **modules/**: 各功能模块的状态管理
  - **index.ts**: 状态管理入口
- **views/**: 页面视图组件
@@ -142,25 +142,28 @@ AlgerMusicPlayer/
- 避免使用枚举,使用 const 对象代替
- 使用 tailwind 实现响应式设计
### 如何启动?
安装依赖最好使用node18+
```
npm install
```
#### 桌面端开发
启动桌面端开发:
```
npm run dev
```
#### 网页端开发
如果只启动网页端开发,需要自己部署服务 netease-cloud-music-api
如果只启动网页端开发,需要自己部署服务 netease-cloud-music-api
需要复制一份 `.env.development.local``src/renderer`
```
# .env.development.local
@@ -171,6 +174,7 @@ VITE_API_MUSIC = ***
```
启动web端开发
```
npm run dev:web
```
@@ -178,15 +182,17 @@ npm run dev:web
### 打包
打包桌面端:
```
npm run build:win
```
打包后的文件在 /dist 下
打包网页端:
```
npm run build
```
打包后的文件在 /out/renderer 下

View File

@@ -1,4 +1,3 @@
<h2 align="center">🎵 Alger Music Player</h2>
<div align="center">
<div align="center">
@@ -23,10 +22,10 @@
<a href="https://hellogithub.com/repository/607b849c598d48e08fe38789d156ebdc" target="_blank"><img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=607b849c598d48e08fe38789d156ebdc&claim_uid=ObuMXUfeHBmk9TI&theme=neutral" alt="FeaturedHelloGitHub" width="160" height="32" /></a>
</div>
[项目下安装以及常用问题文档](https://www.yuque.com/alger-pfg5q/ip4f1a/bmgmfmghnhgwghkm?singleDoc#)
主要功能如下
- 🎵 音乐推荐
- 🔐 网易云账号登录与同步
- 📝 功能
@@ -41,7 +40,6 @@
- 迷你模式
- 状态栏控制
- 多语言支持
- 🎼 音乐功能
- 支持歌单、MV、专辑等完整音乐服务
- 音乐资源解析(基于 @unblockneteasemusic/server
@@ -56,12 +54,15 @@
- 全平台适配Desktop & Web & Mobile Web & Android<测试> & ios<后续>
## 项目简介
一个第三方音乐播放器、本地服务、桌面歌词、音乐下载、最高音质
一个第三方音乐播放器、本地服务、桌面歌词、音乐下载、最高音质
## 预览地址
[http://music.alger.fun/](http://music.alger.fun/)
## 软件截图
![首页白](./docs/image.png)
![首页黑](./docs/image3.png)
![歌词](./docs/image6.png)
@@ -70,31 +71,31 @@
![音乐远程控制](./docs/image5.png)
## 项目启动
```bash
npm install
npm run dev
```
## 开发文档
点击这里[开发文档](./DEV.md)
## 赞赏☕️
[赞赏列表](http://donate.alger.fun/)
| 微信赞赏 | 支付宝赞赏 |
| 微信赞赏 | 支付宝赞赏 |
| :--------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------: |
| <img src="https://github.com/algerkong/algerkong/blob/main/wechat.jpg?raw=true" alt="WeChat QRcode" width=200> <br><small>喝点咖啡继续干</small> | <img src="https://github.com/algerkong/algerkong/blob/main/alipay.jpg?raw=true" alt="Wechat QRcode" width=200> <br><small>来包辣条吧~</small> |
## 项目统计
[![Stargazers over time](https://starchart.cc/algerkong/AlgerMusicPlayer.svg?variant=adaptive)](https://starchart.cc/algerkong/AlgerMusicPlayer)
![Alt](https://repobeats.axiom.co/api/embed/c4d01b3632e241c90cdec9508dfde86a7f54c9f5.svg "Repobeats analytics image")
![Alt](https://repobeats.axiom.co/api/embed/c4d01b3632e241c90cdec9508dfde86a7f54c9f5.svg 'Repobeats analytics image')
## 欢迎提Issues
## 声明
本软件仅用于学习交流,禁止用于商业用途,否则后果自负。
希望大家还是要多多支持官方正版,此软件仅用作开发教学。

View File

@@ -39,7 +39,7 @@ export default defineConfig({
],
publicDir: resolve('resources'),
server: {
host: '0.0.0.0',
host: '0.0.0.0'
}
}
});

249
eslint.config.mjs Normal file
View File

@@ -0,0 +1,249 @@
import js from '@eslint/js';
import typescript from '@typescript-eslint/eslint-plugin';
import typescriptParser from '@typescript-eslint/parser';
import vue from 'eslint-plugin-vue';
import vueParser from 'vue-eslint-parser';
import prettier from 'eslint-plugin-prettier';
import simpleImportSort from 'eslint-plugin-simple-import-sort';
import vueScopedCss from 'eslint-plugin-vue-scoped-css';
import globals from 'globals';
export default [
// 忽略文件配置
{
ignores: ['node_modules/**', 'dist/**', 'out/**', '.gitignore']
},
// 基础 JavaScript 配置
js.configs.recommended,
// JavaScript 文件配置
{
files: ['**/*.js', '**/*.cjs', '**/*.mjs'],
languageOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
globals: {
...globals.node,
...globals.browser
}
},
rules: {
'no-console': 'off',
'no-undef': 'error'
}
},
// TypeScript 文件配置
{
files: ['**/*.ts', '**/*.tsx'],
languageOptions: {
parser: typescriptParser,
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
allowImportExportEverywhere: true,
ecmaFeatures: {
jsx: true
}
},
globals: {
...globals.node,
...globals.browser,
// Vue 3 特定全局变量
defineProps: 'readonly',
defineEmits: 'readonly',
// TypeScript 全局类型
NodeJS: 'readonly',
ScrollBehavior: 'readonly'
}
},
plugins: {
'@typescript-eslint': typescript,
'simple-import-sort': simpleImportSort
},
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-unused-vars': [
'warn',
{
argsIgnorePattern:
'^_|^e$|^event$|^error$|^data$|^callback$|^args$|^value$|^loading$|^width$|^height$|^showPlaylist$|^id$|^enabledSources$|^progress$|^status$|^success$|^filePath$|^locale$|^channel$|^listener$|^url$|^songId$|^delta$|^item$|^err$|^gradient$|^theme$',
varsIgnorePattern:
'^_|^e$|^event$|^error$|^data$|^callback$|^args$|^NONE$|^TIME$|^SONGS$|^PLAYLIST_END$|^c$|^l$|^Window$|^key$|^color$',
ignoreRestSiblings: true
}
],
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/ban-types': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error',
'no-console': 'off',
'no-unused-vars': [
'warn',
{
argsIgnorePattern:
'^_|^e$|^event$|^error$|^data$|^callback$|^args$|^value$|^loading$|^width$|^height$|^showPlaylist$|^id$|^enabledSources$|^progress$|^status$|^success$|^filePath$|^locale$|^channel$|^listener$|^url$|^songId$|^delta$|^item$|^err$|^gradient$|^theme$',
varsIgnorePattern:
'^_|^e$|^event$|^error$|^data$|^callback$|^args$|^NONE$|^TIME$|^SONGS$|^PLAYLIST_END$|^c$|^l$|^Window$|^key$|^color$',
ignoreRestSiblings: true
}
],
'no-use-before-define': 'off',
'max-classes-per-file': 'off',
'no-await-in-loop': 'off',
'dot-notation': 'off',
'constructor-super': 'off',
'getter-return': 'off',
'no-const-assign': 'off',
'no-dupe-args': 'off',
'no-dupe-class-members': 'off',
'no-dupe-keys': 'off',
'no-func-assign': 'off',
'no-import-assign': 'off',
'no-new-symbol': 'off',
'no-obj-calls': 'off',
'no-redeclare': 'off',
'no-setter-return': 'off',
'no-this-before-super': 'off',
'no-undef': 'off',
'no-unreachable': 'off',
'no-unsafe-negation': 'off',
'no-var': 'error',
'prefer-const': 'error',
'prefer-rest-params': 'error',
'prefer-spread': 'error',
'valid-typeof': 'off',
'consistent-return': 'off',
'no-promise-executor-return': 'off',
'prefer-promise-reject-errors': 'off'
}
},
// Vue 文件配置
{
files: ['**/*.vue'],
languageOptions: {
parser: vueParser,
parserOptions: {
parser: typescriptParser,
ecmaVersion: 'latest',
sourceType: 'module',
allowImportExportEverywhere: true
},
globals: {
...globals.browser,
// Vue 3 特定全局变量
defineProps: 'readonly',
defineEmits: 'readonly',
// Vue 3 Composition API (如果使用了 unplugin-auto-import)
ref: 'readonly',
reactive: 'readonly',
computed: 'readonly',
watch: 'readonly',
watchEffect: 'readonly',
onMounted: 'readonly',
onUnmounted: 'readonly',
onBeforeUnmount: 'readonly',
nextTick: 'readonly',
inject: 'readonly',
provide: 'readonly',
// Naive UI (如果使用了 unplugin-auto-import)
useDialog: 'readonly',
useMessage: 'readonly',
// TypeScript 全局类型
NodeJS: 'readonly',
ScrollBehavior: 'readonly'
}
},
plugins: {
vue,
'@typescript-eslint': typescript,
prettier,
'simple-import-sort': simpleImportSort,
'vue-scoped-css': vueScopedCss
},
rules: {
// Vue 3 推荐规则
'vue/no-unused-vars': 'error',
'vue/no-unused-components': 'error',
'vue/no-multiple-template-root': 'off',
'vue/no-v-model-argument': 'off',
'vue/require-default-prop': 'off',
'vue/multi-word-component-names': 'off',
'vue/component-name-in-template-casing': ['error', 'kebab-case'],
'vue/no-reserved-props': 'off',
'vue/no-v-html': 'off',
'vue/first-attribute-linebreak': 'off',
'vue-scoped-css/enforce-style-type': [
'error',
{
allows: ['scoped']
}
],
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'prettier/prettier': 'error',
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error'
}
},
// TypeScript 类型定义文件配置
{
files: ['**/*.d.ts'],
rules: {
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-interface': 'off'
}
},
// JavaScript 第三方库文件配置
{
files: ['**/assets/**/*.js', '**/vendor/**/*.js', '**/lib/**/*.js'],
rules: {
'no-unused-vars': 'off',
'no-redeclare': 'off',
'no-self-assign': 'off',
'no-undef': 'off'
}
},
// 通用规则
{
files: ['**/*.js', '**/*.ts', '**/*.vue'],
rules: {
'no-console': 'off',
'no-underscore-dangle': 'off',
'no-nested-ternary': 'off',
'no-await-in-loop': 'off',
'no-continue': 'off',
'no-restricted-syntax': 'off',
'no-return-assign': 'off',
'no-unused-expressions': 'off',
'no-return-await': 'off',
'no-plusplus': 'off',
'no-param-reassign': 'off',
'no-shadow': 'off',
'guard-for-in': 'off',
'class-methods-use-this': 'off',
'no-case-declarations': 'off',
'no-unused-vars': [
'warn',
{
argsIgnorePattern:
'^_|^e$|^event$|^error$|^data$|^callback$|^args$|^value$|^loading$|^width$|^height$|^showPlaylist$|^id$|^enabledSources$|^progress$|^status$|^success$|^filePath$|^locale$|^channel$|^listener$|^url$|^songId$|^delta$|^item$|^err$|^gradient$|^theme$',
varsIgnorePattern:
'^_|^e$|^event$|^error$|^data$|^callback$|^args$|^NONE$|^TIME$|^SONGS$|^PLAYLIST_END$|^c$|^l$|^Window$|^key$|^color$',
ignoreRestSiblings: true
}
]
}
}
];

View File

@@ -8,7 +8,7 @@
"scripts": {
"prepare": "husky",
"format": "prettier --write .",
"lint": "eslint . --ext .js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts,.vue --fix",
"lint": "eslint . --fix",
"typecheck:node": "tsc --noEmit -p tsconfig.node.json --composite false",
"typecheck:web": "vue-tsc --noEmit -p tsconfig.web.json --composite false",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
@@ -44,6 +44,7 @@
"@electron-toolkit/eslint-config": "^2.1.0",
"@electron-toolkit/eslint-config-ts": "^3.1.0",
"@electron-toolkit/tsconfig": "^1.0.1",
"@eslint/js": "^9.31.0",
"@rushstack/eslint-patch": "^1.10.3",
"@tailwindcss/postcss7-compat": "^2.2.4",
"@types/howler": "^2.2.12",
@@ -66,12 +67,13 @@
"electron-builder": "^25.1.8",
"electron-vite": "^3.1.0",
"eslint": "^9.0.0",
"eslint-config-prettier": "^10.1.2",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-simple-import-sort": "^12.0.0",
"eslint-plugin-vue": "^10.0.0",
"eslint-plugin-vue-scoped-css": "^2.9.0",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-import": "^2.32.0",
"eslint-plugin-prettier": "^5.5.3",
"eslint-plugin-simple-import-sort": "^12.1.1",
"eslint-plugin-vue": "^10.3.0",
"eslint-plugin-vue-scoped-css": "^2.11.0",
"globals": "^16.3.0",
"howler": "^2.2.4",
"lodash": "^4.17.21",
"marked": "^15.0.4",
@@ -79,7 +81,7 @@
"pinia": "^3.0.1",
"pinyin-match": "^1.2.6",
"postcss": "^8.5.3",
"prettier": "^3.3.2",
"prettier": "^3.6.2",
"remixicon": "^4.6.0",
"sass": "^1.86.0",
"tailwindcss": "^3.4.17",

10
prettier.config.js Normal file
View File

@@ -0,0 +1,10 @@
/**
* @type {import('prettier').Config}
*/
module.exports = {
singleQuote: true,
semi: true,
printWidth: 100,
trailingComma: 'none',
endOfLine: 'auto'
};

View File

@@ -1,486 +1,505 @@
<!DOCTYPE html>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>AlgerMusicPlayer 远程控制</title>
<style>
:root {
--primary-color: #007AFF;
--secondary-color: #5AC8FA;
--success-color: #4CD964;
--danger-color: #FF3B30;
--warning-color: #FF9500;
--light-gray: #F2F2F7;
--medium-gray: #E5E5EA;
--dark-gray: #8E8E93;
--text-color: #000000;
--text-secondary: #6C6C6C;
--background-color: #FFFFFF;
}
@media (prefers-color-scheme: dark) {
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
<title>AlgerMusicPlayer 远程控制</title>
<style>
:root {
--primary-color: #0A84FF;
--secondary-color: #64D2FF;
--success-color: #30D158;
--danger-color: #FF453A;
--warning-color: #FF9F0A;
--light-gray: #1C1C1E;
--medium-gray: #2C2C2E;
--dark-gray: #8E8E93;
--text-color: #FFFFFF;
--text-secondary: #AEAEB2;
--background-color: #000000;
--primary-color: #007aff;
--secondary-color: #5ac8fa;
--success-color: #4cd964;
--danger-color: #ff3b30;
--warning-color: #ff9500;
--light-gray: #f2f2f7;
--medium-gray: #e5e5ea;
--dark-gray: #8e8e93;
--text-color: #000000;
--text-secondary: #6c6c6c;
--background-color: #ffffff;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
@media (prefers-color-scheme: dark) {
:root {
--primary-color: #0a84ff;
--secondary-color: #64d2ff;
--success-color: #30d158;
--danger-color: #ff453a;
--warning-color: #ff9f0a;
--light-gray: #1c1c1e;
--medium-gray: #2c2c2e;
--dark-gray: #8e8e93;
--text-color: #ffffff;
--text-secondary: #aeaeb2;
--background-color: #000000;
}
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Helvetica Neue', Arial, sans-serif;
line-height: 1.6;
color: var(--text-color);
background-color: var(--light-gray);
display: flex;
flex-direction: column;
min-height: 100vh;
padding: 0;
margin: 0;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
.header {
position: sticky;
top: 0;
z-index: 100;
background-color: var(--background-color);
padding: 12px 16px;
text-align: center;
border-bottom: 1px solid var(--medium-gray);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
body {
font-family:
-apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Helvetica Neue', Arial, sans-serif;
line-height: 1.6;
color: var(--text-color);
background-color: var(--light-gray);
display: flex;
flex-direction: column;
min-height: 100vh;
padding: 0;
margin: 0;
}
.header h1 {
font-size: 18px;
font-weight: 600;
margin: 0;
}
.header {
position: sticky;
top: 0;
z-index: 100;
background-color: var(--background-color);
padding: 12px 16px;
text-align: center;
border-bottom: 1px solid var(--medium-gray);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
.container {
max-width: 540px;
margin: 0 auto;
padding: 16px;
width: 100%;
flex: 1;
}
.header h1 {
font-size: 18px;
font-weight: 600;
margin: 0;
}
.card {
background-color: var(--background-color);
border-radius: 12px;
padding: 16px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.container {
max-width: 540px;
margin: 0 auto;
padding: 16px;
width: 100%;
flex: 1;
}
.song-info {
display: flex;
align-items: center;
padding-bottom: 16px;
}
.card {
background-color: var(--background-color);
border-radius: 12px;
padding: 16px;
margin-bottom: 16px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.song-cover {
width: 72px;
height: 72px;
border-radius: 8px;
object-fit: cover;
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
background-color: var(--medium-gray);
}
.song-info {
display: flex;
align-items: center;
padding-bottom: 16px;
}
.song-details {
margin-left: 16px;
flex: 1;
}
.song-cover {
width: 72px;
height: 72px;
border-radius: 8px;
object-fit: cover;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
background-color: var(--medium-gray);
}
.song-details h2 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: var(--text-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.song-details {
margin-left: 16px;
flex: 1;
}
.song-details p {
margin: 4px 0 0;
font-size: 15px;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.song-details h2 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: var(--text-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.play-state {
font-size: 14px;
color: var(--primary-color);
margin-top: 4px;
display: flex;
align-items: center;
}
.song-details p {
margin: 4px 0 0;
font-size: 15px;
color: var(--text-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.play-state::before {
content: '';
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 6px;
}
.play-state {
font-size: 14px;
color: var(--primary-color);
margin-top: 4px;
display: flex;
align-items: center;
}
.playing .play-state::before {
background-color: var(--success-color);
}
.play-state::before {
content: '';
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 6px;
}
.paused .play-state::before {
background-color: var(--warning-color);
}
.playing .play-state::before {
background-color: var(--success-color);
}
.controls {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin-bottom: 16px;
}
.paused .play-state::before {
background-color: var(--warning-color);
}
.extra-controls {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 12px;
}
.controls {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin-bottom: 16px;
}
.btn {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: var(--background-color);
color: var(--primary-color);
border: 1px solid var(--medium-gray);
padding: 16px 0;
border-radius: 12px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
transition: all 0.2s ease;
user-select: none;
position: relative;
overflow: hidden;
}
.btn:active {
transform: scale(0.97);
opacity: 0.7;
}
.btn::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--primary-color);
opacity: 0;
transition: opacity 0.2s ease;
z-index: -1;
}
.btn:active::before {
opacity: 0.1;
}
.btn svg {
margin-bottom: 8px;
width: 24px;
height: 24px;
fill: var(--primary-color);
}
.btn-play svg {
width: 28px;
height: 28px;
margin-bottom: 6px;
}
.status-bar {
text-align: center;
padding: 8px 16px;
font-size: 14px;
color: var(--text-secondary);
background-color: var(--background-color);
border-top: 1px solid var(--medium-gray);
position: sticky;
bottom: 0;
}
.status-message {
display: inline-block;
transition: opacity 0.3s ease;
}
.status-message.fade {
opacity: 0;
}
.refresh-button {
color: var(--primary-color);
background: none;
border: none;
font-size: 14px;
cursor: pointer;
padding: 0;
margin-left: 8px;
}
@media (max-width: 350px) {
.controls, .extra-controls {
gap: 8px;
.extra-controls {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 12px;
}
.btn {
padding: 12px 0;
font-size: 12px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: var(--background-color);
color: var(--primary-color);
border: 1px solid var(--medium-gray);
padding: 16px 0;
border-radius: 12px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
transition: all 0.2s ease;
user-select: none;
position: relative;
overflow: hidden;
}
.btn:active {
transform: scale(0.97);
opacity: 0.7;
}
.btn::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: var(--primary-color);
opacity: 0;
transition: opacity 0.2s ease;
z-index: -1;
}
.btn:active::before {
opacity: 0.1;
}
.btn svg {
width: 20px;
height: 20px;
margin-bottom: 8px;
width: 24px;
height: 24px;
fill: var(--primary-color);
}
.btn-play svg {
width: 28px;
height: 28px;
margin-bottom: 6px;
}
}
</style>
</head>
<body>
<div class="header">
<h1>AlgerMusicPlayer 远程控制</h1>
</div>
<div class="container">
<div class="card" id="songInfoCard">
<div class="song-info">
<img id="songCover" class="song-cover" src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%238E8E93'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z'/%3E%3C/svg%3E" alt="封面">
<div class="song-details">
<h2 id="songTitle">未在播放</h2>
<p id="songArtist">--</p>
<div class="play-state" id="playState">未播放</div>
.status-bar {
text-align: center;
padding: 8px 16px;
font-size: 14px;
color: var(--text-secondary);
background-color: var(--background-color);
border-top: 1px solid var(--medium-gray);
position: sticky;
bottom: 0;
}
.status-message {
display: inline-block;
transition: opacity 0.3s ease;
}
.status-message.fade {
opacity: 0;
}
.refresh-button {
color: var(--primary-color);
background: none;
border: none;
font-size: 14px;
cursor: pointer;
padding: 0;
margin-left: 8px;
}
@media (max-width: 350px) {
.controls,
.extra-controls {
gap: 8px;
}
.btn {
padding: 12px 0;
font-size: 12px;
}
.btn svg {
width: 20px;
height: 20px;
margin-bottom: 6px;
}
}
</style>
</head>
<body>
<div class="header">
<h1>AlgerMusicPlayer 远程控制</h1>
</div>
<div class="container">
<div class="card" id="songInfoCard">
<div class="song-info">
<img
id="songCover"
class="song-cover"
src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%238E8E93'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z'/%3E%3C/svg%3E"
alt="封面"
/>
<div class="song-details">
<h2 id="songTitle">未在播放</h2>
<p id="songArtist">--</p>
<div class="play-state" id="playState">未播放</div>
</div>
</div>
</div>
<div class="card">
<div class="controls">
<button id="prevBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M6 6h2v12H6zm3.5 6l8.5 6V6z" />
</svg>
上一首
</button>
<button id="playBtn" class="btn btn-play">
<svg id="playIcon" viewBox="0 0 24 24" fill="currentColor">
<path d="M8 5v14l11-7z" />
</svg>
播放/暂停
</button>
<button id="nextBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z" />
</svg>
下一首
</button>
</div>
<div class="extra-controls">
<button id="volumeDownBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path
d="M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z"
/>
</svg>
音量-
</button>
<button id="volumeUpBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path
d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"
/>
</svg>
音量+
</button>
</div>
</div>
<div class="card">
<div class="extra-controls">
<button id="favoriteBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path
d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
/>
</svg>
收藏
</button>
<button id="refreshBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path
d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"
/>
</svg>
刷新
</button>
</div>
</div>
</div>
<div class="card">
<div class="controls">
<button id="prevBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M6 6h2v12H6zm3.5 6l8.5 6V6z"/>
</svg>
上一首
</button>
<button id="playBtn" class="btn btn-play">
<svg id="playIcon" viewBox="0 0 24 24" fill="currentColor">
<path d="M8 5v14l11-7z"/>
</svg>
播放/暂停
</button>
<button id="nextBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z"/>
</svg>
下一首
</button>
</div>
<div class="extra-controls">
<button id="volumeDownBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z"/>
</svg>
音量-
</button>
<button id="volumeUpBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/>
</svg>
音量+
</button>
</div>
<div class="status-bar">
<span id="status" class="status-message">准备就绪</span>
</div>
<div class="card">
<div class="extra-controls">
<button id="favoriteBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
</svg>
收藏
</button>
<button id="refreshBtn" class="btn">
<svg viewBox="0 0 24 24" fill="currentColor">
<path d="M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>
</svg>
刷新
</button>
</div>
</div>
</div>
<script>
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
// 获取DOM元素
const songInfoCard = document.getElementById('songInfoCard');
const songTitle = document.getElementById('songTitle');
const songArtist = document.getElementById('songArtist');
const songCover = document.getElementById('songCover');
const playState = document.getElementById('playState');
const playBtn = document.getElementById('playBtn');
const playIcon = document.getElementById('playIcon');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const favoriteBtn = document.getElementById('favoriteBtn');
const volumeUpBtn = document.getElementById('volumeUpBtn');
const volumeDownBtn = document.getElementById('volumeDownBtn');
const refreshBtn = document.getElementById('refreshBtn');
const status = document.getElementById('status');
<div class="status-bar">
<span id="status" class="status-message">准备就绪</span>
</div>
let isPlaying = false;
<script>
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', () => {
// 获取DOM元素
const songInfoCard = document.getElementById('songInfoCard');
const songTitle = document.getElementById('songTitle');
const songArtist = document.getElementById('songArtist');
const songCover = document.getElementById('songCover');
const playState = document.getElementById('playState');
const playBtn = document.getElementById('playBtn');
const playIcon = document.getElementById('playIcon');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const favoriteBtn = document.getElementById('favoriteBtn');
const volumeUpBtn = document.getElementById('volumeUpBtn');
const volumeDownBtn = document.getElementById('volumeDownBtn');
const refreshBtn = document.getElementById('refreshBtn');
const status = document.getElementById('status');
// 显示状态消息并淡出
function showStatus(message, autoClear = true) {
status.textContent = message;
status.classList.remove('fade');
let isPlaying = false;
// 显示状态消息并淡出
function showStatus(message, autoClear = true) {
status.textContent = message;
status.classList.remove('fade');
if (autoClear) {
setTimeout(() => {
status.classList.add('fade');
}, 2000);
}
}
// 更新播放/暂停图标
function updatePlayIcon() {
if (isPlaying) {
playIcon.innerHTML = '<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>';
} else {
playIcon.innerHTML = '<path d="M8 5v14l11-7z"/>';
}
}
// 更新状态的函数
async function updateStatus() {
try {
showStatus('获取播放状态...', false);
const response = await fetch('/api/status');
const data = await response.json();
// 更新播放状态
isPlaying = data.isPlaying;
updatePlayIcon();
// 更新UI
if (data.currentSong) {
songTitle.textContent = data.currentSong.name || '未知歌曲';
if (data.currentSong.ar && data.currentSong.ar.length) {
songArtist.textContent = data.currentSong.ar.map(a => a.name).join(', ');
} else if (data.currentSong.artists && data.currentSong.artists.length) {
songArtist.textContent = data.currentSong.artists.map(a => a.name).join(', ');
} else {
songArtist.textContent = '未知艺术家';
}
if (data.currentSong.picUrl) {
songCover.src = data.currentSong.picUrl;
}
} else {
songTitle.textContent = '未在播放';
songArtist.textContent = '--';
songCover.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%238E8E93'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z'/%3E%3C/svg%3E";
if (autoClear) {
setTimeout(() => {
status.classList.add('fade');
}, 2000);
}
// 更新播放状态
playState.textContent = isPlaying ? '正在播放' : '已暂停';
songInfoCard.className = isPlaying ? 'card playing' : 'card paused';
showStatus('已更新', true);
} catch (error) {
console.error('获取状态失败:', error);
showStatus('获取状态失败');
}
}
// 发送命令的函数
async function sendCommand(endpoint) {
try {
showStatus('发送命令中...', false);
const response = await fetch('/api/' + endpoint, { method: 'POST' });
const data = await response.json();
showStatus(data.message || '命令已发送');
// 稍等后更新状态
setTimeout(updateStatus, 500);
} catch (error) {
console.error('发送命令失败:', error);
showStatus('发送命令失败');
// 更新播放/暂停图标
function updatePlayIcon() {
if (isPlaying) {
playIcon.innerHTML = '<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>';
} else {
playIcon.innerHTML = '<path d="M8 5v14l11-7z"/>';
}
}
}
// 绑定按钮事件
playBtn.addEventListener('click', () => sendCommand('toggle-play'));
prevBtn.addEventListener('click', () => sendCommand('prev'));
nextBtn.addEventListener('click', () => sendCommand('next'));
favoriteBtn.addEventListener('click', () => sendCommand('toggle-favorite'));
volumeUpBtn.addEventListener('click', () => sendCommand('volume-up'));
volumeDownBtn.addEventListener('click', () => sendCommand('volume-down'));
refreshBtn.addEventListener('click', updateStatus);
// 更新状态的函数
async function updateStatus() {
try {
showStatus('获取播放状态...', false);
// 初始加载状态
updateStatus();
const response = await fetch('/api/status');
const data = await response.json();
// 每1秒更新一次状态
setInterval(updateStatus, 1000);
// 更新播放状态
isPlaying = data.isPlaying;
updatePlayIcon();
// 添加触摸反馈
const buttons = document.querySelectorAll('.btn');
buttons.forEach(btn => {
btn.addEventListener('touchstart', function() {
this.style.transform = 'scale(0.97)';
this.style.opacity = '0.7';
});
// 更新UI
if (data.currentSong) {
songTitle.textContent = data.currentSong.name || '未知歌曲';
btn.addEventListener('touchend', function() {
this.style.transform = 'scale(1)';
this.style.opacity = '1';
});
});
if (data.currentSong.ar && data.currentSong.ar.length) {
songArtist.textContent = data.currentSong.ar.map((a) => a.name).join(', ');
} else if (data.currentSong.artists && data.currentSong.artists.length) {
songArtist.textContent = data.currentSong.artists.map((a) => a.name).join(', ');
} else {
songArtist.textContent = '未知艺术家';
}
// 检测深色模式变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (data.currentSong.picUrl) {
songCover.src = data.currentSong.picUrl;
}
} else {
songTitle.textContent = '未在播放';
songArtist.textContent = '--';
songCover.src =
"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%238E8E93'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 14.5c-2.49 0-4.5-2.01-4.5-4.5S9.51 7.5 12 7.5s4.5 2.01 4.5 4.5-2.01 4.5-4.5 4.5zm0-5.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1z'/%3E%3C/svg%3E";
}
// 更新播放状态
playState.textContent = isPlaying ? '正在播放' : '已暂停';
songInfoCard.className = isPlaying ? 'card playing' : 'card paused';
showStatus('已更新', true);
} catch (error) {
console.error('获取状态失败:', error);
showStatus('获取状态失败');
}
}
// 发送命令的函数
async function sendCommand(endpoint) {
try {
showStatus('发送命令中...', false);
const response = await fetch('/api/' + endpoint, { method: 'POST' });
const data = await response.json();
showStatus(data.message || '命令已发送');
// 稍等后更新状态
setTimeout(updateStatus, 500);
} catch (error) {
console.error('发送命令失败:', error);
showStatus('发送命令失败');
}
}
// 绑定按钮事件
playBtn.addEventListener('click', () => sendCommand('toggle-play'));
prevBtn.addEventListener('click', () => sendCommand('prev'));
nextBtn.addEventListener('click', () => sendCommand('next'));
favoriteBtn.addEventListener('click', () => sendCommand('toggle-favorite'));
volumeUpBtn.addEventListener('click', () => sendCommand('volume-up'));
volumeDownBtn.addEventListener('click', () => sendCommand('volume-down'));
refreshBtn.addEventListener('click', updateStatus);
// 初始加载状态
updateStatus();
// 每1秒更新一次状态
setInterval(updateStatus, 1000);
// 添加触摸反馈
const buttons = document.querySelectorAll('.btn');
buttons.forEach((btn) => {
btn.addEventListener('touchstart', function () {
this.style.transform = 'scale(0.97)';
this.style.opacity = '0.7';
});
btn.addEventListener('touchend', function () {
this.style.transform = 'scale(1)';
this.style.opacity = '1';
});
});
// 检测深色模式变化
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
updateStatus();
});
});
});
</script>
</body>
</script>
</body>
</html>

View File

@@ -174,7 +174,8 @@ export default {
noTasks: 'No import tasks',
clearTasks: 'Clear Tasks',
clearTasksConfirmTitle: 'Confirm Clear',
clearTasksConfirmContent: 'Are you sure you want to clear all import task records? This action cannot be undone.',
clearTasksConfirmContent:
'Are you sure you want to clear all import task records? This action cannot be undone.',
confirm: 'Confirm',
cancel: 'Cancel',
clearTasksSuccess: 'Task list cleared',

View File

@@ -63,7 +63,7 @@ export default {
favorite: 'Favorite {name}',
unFavorite: 'Unfavorite {name}',
playbackSpeed: 'Playback Speed',
advancedControls: 'Advanced Controls',
advancedControls: 'Advanced Controls'
},
eq: {
title: 'Equalizer',
@@ -117,6 +117,7 @@ export default {
cleared: 'Playlist cleared',
empty: 'Playlist is empty',
clearConfirmTitle: 'Clear Playlist',
clearConfirmContent: 'This will clear all songs in the playlist and stop the current playback. Continue?'
clearConfirmContent:
'This will clear all songs in the playlist and stop the current playback. Continue?'
}
};

View File

@@ -66,11 +66,13 @@ export default {
configureMusicSources: 'Configure Sources',
selectedMusicSources: 'Selected sources:',
noMusicSources: 'No sources selected',
gdmusicInfo: 'GD Music Station intelligently resolves music from multiple platforms automatically',
gdmusicInfo:
'GD Music Station intelligently resolves music from multiple platforms automatically',
autoPlay: 'Auto Play',
autoPlayDesc: 'Auto resume playback when reopening the app',
showStatusBar: "Show Status Bar",
showStatusBarContent: "You can display the music control function in your mac status bar (effective after a restart)"
showStatusBar: 'Show Status Bar',
showStatusBarContent:
'You can display the music control function in your mac status bar (effective after a restart)'
},
application: {
closeAction: 'Close Action',
@@ -232,9 +234,9 @@ export default {
'spotify-green': 'Spotify Green',
'apple-blue': 'Apple Blue',
'youtube-red': 'YouTube Red',
'orange': 'Vibrant Orange',
'purple': 'Mystic Purple',
'pink': 'Cherry Pink'
orange: 'Vibrant Orange',
purple: 'Mystic Purple',
pink: 'Cherry Pink'
},
tooltips: {
openColorPicker: 'Open Color Picker',
@@ -280,6 +282,6 @@ export default {
addIp: 'Add IP',
emptyListHint: 'Empty list means allow all IPs',
saveSuccess: 'Remote control settings saved',
accessInfo: 'Remote control access address:',
accessInfo: 'Remote control access address:'
}
};

View File

@@ -8,7 +8,7 @@ export default {
unfavorite: 'Unlike',
removeFromPlaylist: 'Remove from Playlist',
dislike: 'Dislike',
undislike: 'Undislike',
undislike: 'Undislike'
},
message: {
downloading: 'Downloading, please wait...',
@@ -18,7 +18,7 @@ export default {
getUrlFailed: 'Failed to get music download URL, please check if logged in'
},
dialog: {
dislike:{
dislike: {
title: 'Dislike',
content: 'Are you sure you want to dislike this song?',
positiveText: 'Dislike',

View File

@@ -20,14 +20,14 @@ export default {
noFollowings: 'No Followings',
loadMore: 'Load More',
noSignature: 'This guy is lazy, nothing left',
userFollowsTitle: '\'s Followings',
userFollowsTitle: "'s Followings",
myFollowsTitle: 'My Followings'
},
follower: {
title: 'Follower List',
noFollowers: 'No Followers',
loadMore: 'Load More',
userFollowersTitle: '\'s Followers',
userFollowersTitle: "'s Followers",
myFollowersTitle: 'My Followers'
},
detail: {
@@ -38,7 +38,7 @@ export default {
artist: 'Artist',
noSignature: 'This guy is lazy, nothing left',
invalidUserId: 'Invalid User ID',
noRecordPermission: '{name} doesn\'t let you see your listening history'
noRecordPermission: "{name} doesn't let you see your listening history"
},
message: {
loadFailed: 'Failed to load user page',

View File

@@ -64,7 +64,7 @@ export default {
unFavorite: '已取消收藏{name}',
miniPlayBar: '迷你播放栏',
playbackSpeed: '播放速度',
advancedControls: '更多设置s',
advancedControls: '更多设置s'
},
eq: {
title: '均衡器',

View File

@@ -70,7 +70,7 @@ export default {
autoPlay: '自动播放',
autoPlayDesc: '重新打开应用时是否自动继续播放',
showStatusBar: '是否显示状态栏控制功能',
showStatusBarContent: '可以在您的mac状态栏显示音乐控制功能(重启后生效)',
showStatusBarContent: '可以在您的mac状态栏显示音乐控制功能(重启后生效)'
},
application: {
closeAction: '关闭行为',
@@ -232,9 +232,9 @@ export default {
'spotify-green': 'Spotify 绿',
'apple-blue': '苹果蓝',
'youtube-red': 'YouTube 红',
'orange': '活力橙',
'purple': '神秘紫',
'pink': '樱花粉'
orange: '活力橙',
purple: '神秘紫',
pink: '樱花粉'
},
tooltips: {
openColorPicker: '打开色板',
@@ -280,6 +280,6 @@ export default {
addIp: '添加IP',
emptyListHint: '空列表表示允许所有IP访问',
saveSuccess: '远程控制设置已保存',
accessInfo: '远程控制访问地址:',
accessInfo: '远程控制访问地址:'
}
};

View File

@@ -8,7 +8,7 @@ export default {
unfavorite: '取消喜欢',
removeFromPlaylist: '从歌单中删除',
dislike: '不喜欢',
undislike: '取消不喜欢',
undislike: '取消不喜欢'
},
message: {
downloading: '正在下载中,请稍候...',

View File

@@ -64,7 +64,7 @@ export default {
unFavorite: '已取消收藏{name}',
miniPlayBar: '迷你播放列',
playbackSpeed: '播放速度',
advancedControls: '更多設定s',
advancedControls: '更多設定s'
},
eq: {
title: '等化器',

View File

@@ -70,7 +70,7 @@ export default {
autoPlay: '自動播放',
autoPlayDesc: '重新開啟應用程式時是否自動繼續播放',
showStatusBar: '是否顯示狀態列控制功能',
showStatusBarContent: '可以在您的mac狀態列顯示音樂控制功能(重啟後生效)',
showStatusBarContent: '可以在您的mac狀態列顯示音樂控制功能(重啟後生效)'
},
application: {
closeAction: '關閉行為',
@@ -212,9 +212,9 @@ export default {
'spotify-green': 'Spotify 綠',
'apple-blue': '蘋果藍',
'youtube-red': 'YouTube 紅',
'orange': '活力橙',
'purple': '神秘紫',
'pink': '櫻花粉'
orange: '活力橙',
purple: '神秘紫',
pink: '櫻花粉'
},
tooltips: {
openColorPicker: '開啟色板',

View File

@@ -8,7 +8,7 @@ export default {
unfavorite: '取消喜歡',
removeFromPlaylist: '從播放清單中刪除',
dislike: '不喜歡',
undislike: '取消不喜歡',
undislike: '取消不喜歡'
},
message: {
downloading: '正在下載中,請稍候...',

View File

@@ -13,15 +13,13 @@ import { initializeShortcuts, registerShortcuts } from './modules/shortcuts';
import { initializeTray, updateCurrentSong, updatePlayState, updateTrayMenu } from './modules/tray';
import { setupUpdateHandlers } from './modules/update';
import { createMainWindow, initializeWindowManager, setAppQuitting } from './modules/window';
import { startMusicApi } from './server';
import { initWindowSizeManager } from './modules/window-size';
import { startMusicApi } from './server';
// 导入所有图标
const iconPath = join(__dirname, '../../resources');
const icon = nativeImage.createFromPath(
process.platform === 'darwin'
? join(iconPath, 'icon.icns')
: join(iconPath, 'icon.png')
process.platform === 'darwin' ? join(iconPath, 'icon.icns') : join(iconPath, 'icon.png')
);
let mainWindow: Electron.BrowserWindow;

View File

@@ -122,7 +122,7 @@ const createWin = () => {
}
});
lyricWindow.on('blur', () => lyricWindow && lyricWindow.setMaximizable(false))
lyricWindow.on('blur', () => lyricWindow && lyricWindow.setMaximizable(false));
return lyricWindow;
};

View File

@@ -1,14 +1,14 @@
import axios from 'axios';
import { app, dialog, ipcMain, Notification, protocol, shell } from 'electron';
import Store from 'electron-store';
import { fileTypeFromFile } from 'file-type';
import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
import * as NodeID3 from 'node-id3';
import * as path from 'path';
import * as os from 'os';
import * as mm from 'music-metadata';
import { fileTypeFromFile } from 'file-type';
import * as NodeID3 from 'node-id3';
import * as os from 'os';
import * as path from 'path';
import { getStore } from './config';
@@ -42,7 +42,7 @@ export function initializeFileManager() {
// 注册本地文件协议
protocol.registerFileProtocol('local', (request, callback) => {
try {
let url = request.url;
const url = request.url;
// local://C:/Users/xxx.mp3
let filePath = decodeURIComponent(url.replace('local:///', ''));
@@ -189,7 +189,8 @@ export function initializeFileManager() {
const validEntriesPromises = await Promise.all(
entriesArray.map(async ([path, info]) => {
try {
const exists = await fs.promises.access(path)
const exists = await fs.promises
.access(path)
.then(() => true)
.catch(() => false);
return exists ? info : null;
@@ -202,7 +203,7 @@ export function initializeFileManager() {
// 过滤有效的歌曲并排序
const validSongs = validEntriesPromises
.filter(song => song !== null)
.filter((song) => song !== null)
.sort((a, b) => (b.downloadTime || 0) - (a.downloadTime || 0));
// 更新存储,移除不存在的文件记录
@@ -478,23 +479,25 @@ async function downloadMusic(
// 音频格式映射表
const formatMap = {
'mp3': ['MPEG', 'MP3', 'mp3'],
'aac': ['AAC'],
'flac': ['FLAC'],
'ogg': ['Ogg', 'Vorbis'],
'wav': ['WAV', 'PCM'],
'm4a': ['M4A', 'MP4']
mp3: ['MPEG', 'MP3', 'mp3'],
aac: ['AAC'],
flac: ['FLAC'],
ogg: ['Ogg', 'Vorbis'],
wav: ['WAV', 'PCM'],
m4a: ['M4A', 'MP4']
};
// 查找匹配的格式
const format = Object.entries(formatMap).find(([_, keywords]) =>
keywords.some(keyword => container.includes(keyword) || codec.includes(keyword))
keywords.some((keyword) => container.includes(keyword) || codec.includes(keyword))
);
// 设置文件扩展名如果没找到则默认为mp3
fileExtension = format ? `.${format[0]}` : '.mp3';
console.log(`music-metadata检测结果: 容器:${container}, 编码:${codec}, 扩展名: ${fileExtension}`);
console.log(
`music-metadata检测结果: 容器:${container}, 编码:${codec}, 扩展名: ${fileExtension}`
);
} else {
// 两种方法都失败使用传入的type或默认mp3
fileExtension = type ? `.${type}` : '.mp3';

View File

@@ -1,10 +1,11 @@
import cors from 'cors';
import { ipcMain } from 'electron';
import express from 'express';
import cors from 'cors';
import os from 'os';
import { getStore } from './config';
import path from 'path';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { getStore } from './config';
// 定义远程控制相关接口
export interface RemoteControlConfig {
@@ -114,7 +115,7 @@ function startServer(config: RemoteControlConfig) {
app.use((req, res, next) => {
const clientIp = req.ip || req.socket.remoteAddress || '';
const cleanIp = clientIp.replace(/^::ffff:/, ''); // 移除IPv6前缀
console.log('config',config)
console.log('config', config);
if (config.allowedIps.length === 0 || config.allowedIps.includes(cleanIp)) {
next();
} else {

View File

@@ -329,7 +329,7 @@ export function updateTrayMenu(mainWindow: BrowserWindow) {
// 初始化状态栏Tray
function initializeStatusBarTray(mainWindow: BrowserWindow) {
const store = getStore()
const store = getStore();
if (process.platform !== 'darwin' || !store.get('set.showTopAction')) return;
const iconSize = getProperIconSize();

View File

@@ -31,8 +31,6 @@ export interface WindowState {
isMaximized: boolean;
}
/**
* 窗口大小管理器
* 负责保存、恢复和维护窗口大小状态
@@ -102,7 +100,10 @@ class WindowSizeManager {
// 根据工作区大小设置合理的最小尺寸
MIN_WIDTH = Math.min(Math.round(DEFAULT_MAIN_WIDTH * 0.5), Math.round(workAreaWidth * 0.3));
MIN_HEIGHT = Math.min(Math.round(DEFAULT_MAIN_HEIGHT * 0.5), Math.round(workAreaHeight * 0.3));
MIN_HEIGHT = Math.min(
Math.round(DEFAULT_MAIN_HEIGHT * 0.5),
Math.round(workAreaHeight * 0.3)
);
console.log(`设置最小窗口尺寸: ${MIN_WIDTH}x${MIN_HEIGHT}`);
} catch (error) {
@@ -173,9 +174,13 @@ class WindowSizeManager {
const [currentWidth, currentHeight] = win.getSize();
if (Math.abs(currentWidth - this.savedState.width) > 2 ||
Math.abs(currentHeight - this.savedState.height) > 2) {
console.log(`强制调整窗口大小: 当前=${currentWidth}x${currentHeight}, 目标=${this.savedState.width}x${this.savedState.height}`);
if (
Math.abs(currentWidth - this.savedState.width) > 2 ||
Math.abs(currentHeight - this.savedState.height) > 2
) {
console.log(
`强制调整窗口大小: 当前=${currentWidth}x${currentHeight}, 目标=${this.savedState.width}x${this.savedState.height}`
);
// 临时禁用minimum size限制
const [minWidth, minHeight] = win.getMinimumSize();
@@ -192,8 +197,10 @@ class WindowSizeManager {
console.log(`调整后窗口大小: ${newWidth}x${newHeight}`);
// 如果调整后的大小仍然与目标不一致,尝试再次调整
if (Math.abs(newWidth - this.savedState.width) > 1 ||
Math.abs(newHeight - this.savedState.height) > 1) {
if (
Math.abs(newWidth - this.savedState.width) > 1 ||
Math.abs(newHeight - this.savedState.height) > 1
) {
console.log(`窗口大小调整后仍不一致,将再次尝试调整`);
setTimeout(() => {
if (!win.isDestroyed() && !win.isMaximized() && !win.isMinimized()) {
@@ -296,7 +303,9 @@ class WindowSizeManager {
}
}
console.log(`窗口创建选项: 大小=${options.width}x${options.height}, 位置=(${options.x}, ${options.y})`);
console.log(
`窗口创建选项: 大小=${options.width}x${options.height}, 位置=(${options.x}, ${options.y})`
);
return options;
}
@@ -319,8 +328,12 @@ class WindowSizeManager {
win.maximize();
}
// 如果位置无效,则居中显示
else if (!app.isReady() || savedState.x === undefined || savedState.y === undefined ||
!this.isPositionVisible(savedState.x, savedState.y)) {
else if (
!app.isReady() ||
savedState.x === undefined ||
savedState.y === undefined ||
!this.isPositionVisible(savedState.x, savedState.y)
) {
console.log('保存的位置无效,窗口居中显示');
win.center();
}
@@ -331,13 +344,15 @@ class WindowSizeManager {
*/
saveWindowState(win: BrowserWindow): WindowState {
// 如果窗口已销毁,则返回之前的状态或默认状态
console.log('win.isDestroyed()',win.isDestroyed())
console.log('win.isDestroyed()', win.isDestroyed());
if (win.isDestroyed()) {
return this.savedState || {
width: DEFAULT_MAIN_WIDTH,
height: DEFAULT_MAIN_HEIGHT,
isMaximized: false
};
return (
this.savedState || {
width: DEFAULT_MAIN_WIDTH,
height: DEFAULT_MAIN_HEIGHT,
isMaximized: false
}
);
}
// 检查是否是mini模式窗口根据窗口大小判断
@@ -352,9 +367,10 @@ class WindowSizeManager {
// 由于 Electron 的限制,最大化状态下 getBounds() 可能不准确
// 所以我们尽量保留之前保存的非最大化时的大小
const currentBounds = win.getBounds();
const previousSize = this.savedState && !this.savedState.isMaximized
? { width: this.savedState.width, height: this.savedState.height }
: { width: currentBounds.width, height: currentBounds.height };
const previousSize =
this.savedState && !this.savedState.isMaximized
? { width: this.savedState.width, height: this.savedState.height }
: { width: currentBounds.width, height: currentBounds.height };
state = {
width: previousSize.width,
@@ -363,19 +379,18 @@ class WindowSizeManager {
y: currentBounds.y,
isMaximized: true
};
console.log('state IsMaximized',state)
}
else if (win.isMinimized()) {
console.log('state IsMaximized', state);
} else if (win.isMinimized()) {
// 最小化状态下不保存窗口大小,因为可能不准确
console.log('state IsMinimized',this.savedState)
return this.savedState || {
width: DEFAULT_MAIN_WIDTH,
height: DEFAULT_MAIN_HEIGHT,
isMaximized: false
};
}
else {
console.log('state IsMinimized', this.savedState);
return (
this.savedState || {
width: DEFAULT_MAIN_WIDTH,
height: DEFAULT_MAIN_HEIGHT,
isMaximized: false
}
);
} else {
// 正常状态下保存当前大小和位置
const [width, height] = win.getSize();
const [x, y] = win.getPosition();
@@ -387,7 +402,7 @@ class WindowSizeManager {
y,
isMaximized: false
};
console.log('state IsNormal',state)
console.log('state IsNormal', state);
}
// 如果是mini模式不保存到持久化存储只返回状态用于内存中的恢复
@@ -402,7 +417,7 @@ class WindowSizeManager {
// 更新内部状态
this.savedState = state;
console.log('state',state)
console.log('state', state);
return state;
}
@@ -432,8 +447,6 @@ class WindowSizeManager {
return validatedState;
}
/**
* 检查位置是否在可见屏幕范围内
*/
@@ -447,12 +460,7 @@ class WindowSizeManager {
for (const display of displays) {
const { x: screenX, y: screenY, width, height } = display.workArea;
if (
x >= screenX &&
x < screenX + width &&
y >= screenY &&
y < screenY + height
) {
if (x >= screenX && x < screenX + width && y >= screenY && y < screenY + height) {
return true;
}
}
@@ -523,9 +531,11 @@ class WindowSizeManager {
if (app.isReady()) {
try {
console.log(`应用页面缩放因子: ${zoomFactor}, 系统缩放比: ${screen.getPrimaryDisplay().scaleFactor}`);
console.log(
`应用页面缩放因子: ${zoomFactor}, 系统缩放比: ${screen.getPrimaryDisplay().scaleFactor}`
);
} catch (error) {
console.log(`应用页面缩放因子: ${zoomFactor}`);
console.error('获取系统缩放比失败:', error);
}
} else {
console.log(`应用页面缩放因子: ${zoomFactor}`);
@@ -552,7 +562,7 @@ class WindowSizeManager {
try {
ipcMain.removeHandler(channel);
} catch (error) {
// 忽略错误,处理程序可能不存在
console.warn(`移除IPC处理程序 ${channel} 时出错:`, error);
}
};
@@ -712,4 +722,3 @@ export const initWindowSizeHandlers = (mainWindow: BrowserWindow | null): void =
export const calculateMinimumWindowSize = (): { minWidth: number; minHeight: number } => {
return { minWidth: MIN_WIDTH, minHeight: MIN_HEIGHT };
};

View File

@@ -1,18 +1,28 @@
import { is } from '@electron-toolkit/utils';
import { app, BrowserWindow, nativeImage, globalShortcut, ipcMain, screen, session, shell } from 'electron';
import {
app,
BrowserWindow,
globalShortcut,
ipcMain,
nativeImage,
screen,
session,
shell
} from 'electron';
import Store from 'electron-store';
import { join } from 'path';
import {
DEFAULT_MAIN_WIDTH,
DEFAULT_MAIN_HEIGHT,
DEFAULT_MINI_WIDTH,
DEFAULT_MINI_HEIGHT,
applyContentZoom,
saveWindowState,
applyInitialState,
initWindowSizeHandlers,
DEFAULT_MAIN_HEIGHT,
DEFAULT_MAIN_WIDTH,
DEFAULT_MINI_HEIGHT,
DEFAULT_MINI_WIDTH,
getWindowOptions,
getWindowState,
initWindowSizeHandlers,
saveWindowState,
WindowState
} from './window-size';
@@ -68,34 +78,32 @@ function setThumbarButtons(window: BrowserWindow) {
window.setThumbarButtons([
{
tooltip: 'prev',
icon: nativeImage
.createFromPath(join(app.getAppPath(), 'resources/icons', 'prev.png')),
icon: nativeImage.createFromPath(join(app.getAppPath(), 'resources/icons', 'prev.png')),
click() {
window.webContents.send('global-shortcut', 'prevPlay');
},
}
},
{
tooltip: isPlaying ? 'pause' : 'play',
icon: nativeImage
.createFromPath(join(app.getAppPath(), 'resources/icons', isPlaying ? 'pause.png' : 'play.png')),
icon: nativeImage.createFromPath(
join(app.getAppPath(), 'resources/icons', isPlaying ? 'pause.png' : 'play.png')
),
click() {
window.webContents.send('global-shortcut', 'togglePlay');
},
}
},
{
tooltip: 'next',
icon: nativeImage
.createFromPath(join(app.getAppPath(), 'resources/icons', 'next.png')),
icon: nativeImage.createFromPath(join(app.getAppPath(), 'resources/icons', 'next.png')),
click() {
window.webContents.send('global-shortcut', 'nextPlay');
},
}
}
]);
}
/**
* 初始化窗口管理相关的IPC监听
*/
@@ -159,7 +167,11 @@ export function initializeWindowManager() {
win.setMaximumSize(DEFAULT_MINI_WIDTH, DEFAULT_MINI_HEIGHT);
win.setSize(DEFAULT_MINI_WIDTH, DEFAULT_MINI_HEIGHT, false); // 禁用动画
// 将迷你窗口放在工作区的右上角,留出一些边距
win.setPosition(screenX + screenWidth - DEFAULT_MINI_WIDTH - 20, display.workArea.y + 20, false);
win.setPosition(
screenX + screenWidth - DEFAULT_MINI_WIDTH - 20,
display.workArea.y + 20,
false
);
win.setAlwaysOnTop(true);
win.setSkipTaskbar(false);
win.setResizable(false);
@@ -186,7 +198,10 @@ export function initializeWindowManager() {
console.log('从迷你模式恢复,使用保存的状态:', JSON.stringify(preMiniModeState));
// 设置适当的最小尺寸
win.setMinimumSize(Math.max(DEFAULT_MAIN_WIDTH * 0.5, 600), Math.max(DEFAULT_MAIN_HEIGHT * 0.5, 400));
win.setMinimumSize(
Math.max(DEFAULT_MAIN_WIDTH * 0.5, 600),
Math.max(DEFAULT_MAIN_HEIGHT * 0.5, 400)
);
// 恢复窗口状态
win.setAlwaysOnTop(false);
@@ -223,9 +238,13 @@ export function initializeWindowManager() {
if (!win.isDestroyed() && !win.isMaximized() && !win.isMinimized()) {
// 再次验证窗口大小
const [width, height] = win.getSize();
if (Math.abs(width - preMiniModeState.width) > 2 ||
Math.abs(height - preMiniModeState.height) > 2) {
console.log(`恢复后窗口大小不一致,再次调整: 当前=${width}x${height}, 目标=${preMiniModeState.width}x${preMiniModeState.height}`);
if (
Math.abs(width - preMiniModeState.width) > 2 ||
Math.abs(height - preMiniModeState.height) > 2
) {
console.log(
`恢复后窗口大小不一致,再次调整: 当前=${width}x${height}, 目标=${preMiniModeState.width}x${preMiniModeState.height}`
);
win.setSize(preMiniModeState.width, preMiniModeState.height, false);
}
}
@@ -234,7 +253,6 @@ export function initializeWindowManager() {
}
});
ipcMain.on('update-play-state', (_, playing: boolean) => {
isPlaying = playing;
if (mainWindowInstance) {
@@ -279,14 +297,16 @@ export function createMainWindow(icon: Electron.NativeImage): BrowserWindow {
webSecurity: false
};
console.log(`创建窗口,使用选项: ${JSON.stringify({
width: options.width,
height: options.height,
x: options.x,
y: options.y,
minWidth: options.minWidth,
minHeight: options.minHeight
})}`);
console.log(
`创建窗口,使用选项: ${JSON.stringify({
width: options.width,
height: options.height,
x: options.x,
y: options.y,
minWidth: options.minWidth,
minHeight: options.minHeight
})}`
);
// 创建窗口
const mainWindow = new BrowserWindow(options);
@@ -340,9 +360,13 @@ export function createMainWindow(icon: Electron.NativeImage): BrowserWindow {
if (!mainWindow.isDestroyed() && !mainWindow.isMaximized()) {
const [currentWidth, currentHeight] = mainWindow.getSize();
if (savedState && !savedState.isMaximized) {
if (Math.abs(currentWidth - savedState.width) > 2 ||
Math.abs(currentHeight - savedState.height) > 2) {
console.log(`窗口大小不匹配,再次调整: 当前=${currentWidth}x${currentHeight}, 目标=${savedState.width}x${savedState.height}`);
if (
Math.abs(currentWidth - savedState.width) > 2 ||
Math.abs(currentHeight - savedState.height) > 2
) {
console.log(
`窗口大小不匹配,再次调整: 当前=${currentWidth}x${currentHeight}, 目标=${savedState.width}x${savedState.height}`
);
mainWindow.setSize(savedState.width, savedState.height, false);
}
}
@@ -371,7 +395,6 @@ export function createMainWindow(icon: Electron.NativeImage): BrowserWindow {
initWindowSizeHandlers(mainWindow);
// 保存主窗口引用
mainWindowInstance = mainWindow;

View File

@@ -5,7 +5,7 @@ import server from 'netease-cloud-music-api-alger/server';
import os from 'os';
import path from 'path';
import { unblockMusic, type Platform } from './unblockMusic';
import { type Platform, unblockMusic } from './unblockMusic';
const store = new Store();
if (!fs.existsSync(path.resolve(os.tmpdir(), 'anonymous_token'))) {

View File

@@ -58,7 +58,7 @@ function ensureDataStructure(data: any): any {
// 确保artists中的每个元素都有name属性
if (data.artists.length > 0) {
data.artists = data.artists.map(artist => {
data.artists = data.artists.map((artist) => {
return artist ? { name: artist.name || '' } : { name: '' };
});
}
@@ -89,10 +89,9 @@ const unblockMusic = async (
retryCount = 1,
enabledPlatforms?: Platform[]
): Promise<UnblockResult> => {
// 过滤 enabledPlatforms确保只包含 ALL_PLATFORMS 中存在的平台
const filteredPlatforms = enabledPlatforms
? enabledPlatforms.filter(platform => ALL_PLATFORMS.includes(platform))
? enabledPlatforms.filter((platform) => ALL_PLATFORMS.includes(platform))
: ALL_PLATFORMS;
// 处理歌曲数据,确保数据结构完整

View File

@@ -16,7 +16,8 @@ const api = {
openLyric: () => ipcRenderer.send('open-lyric'),
sendLyric: (data) => ipcRenderer.send('send-lyric', data),
sendSong: (data) => ipcRenderer.send('update-current-song', data),
unblockMusic: (id, data, enabledSources) => ipcRenderer.invoke('unblock-music', id, data, enabledSources),
unblockMusic: (id, data, enabledSources) =>
ipcRenderer.invoke('unblock-music', id, data, enabledSources),
// 歌词窗口关闭事件
onLyricWindowClosed: (callback: () => void) => {
ipcRenderer.on('lyric-window-closed', () => callback());

View File

@@ -19,17 +19,16 @@ import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import TrafficWarningDrawer from '@/components/TrafficWarningDrawer.vue';
import homeRouter from '@/router/home';
import { useMenuStore } from '@/store/modules/menu';
import { usePlayerStore } from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings';
import { isElectron, isLyricWindow } from '@/utils';
import { initAudioListeners } from './hooks/MusicHook';
import { initAudioListeners, initMusicHook } from './hooks/MusicHook';
import { audioService } from './services/audioService';
import { isMobile } from './utils';
import { useAppShortcuts } from './utils/appShortcuts';
import { audioService } from './services/audioService';
const { locale } = useI18n();
const settingsStore = useSettingsStore();
@@ -114,6 +113,9 @@ onMounted(async () => {
}
// 先初始化播放状态
await playerStore.initializePlayState();
// 初始化 MusicHook注入 playerStore
initMusicHook(playerStore);
// 如果有正在播放的音乐,则初始化音频监听器
if (playerStore.playMusic && playerStore.playMusic.id) {
// 使用 nextTick 确保 DOM 更新后再初始化

View File

@@ -153,11 +153,8 @@ export const getBilibiliAudioUrl = async (bvid: string, cid: number): Promise<st
}
};
// 根据音乐名称搜索并直接返回音频URL
export const searchAndGetBilibiliAudioUrl = async (
keyword: string
): Promise<string> => {
export const searchAndGetBilibiliAudioUrl = async (keyword: string): Promise<string> => {
try {
// 搜索B站视频取第一页第一个结果
const res = await searchBilibili({ keyword, page: 1, pagesize: 1 });
@@ -180,4 +177,4 @@ export const searchAndGetBilibiliAudioUrl = async (
console.error('根据名称搜索B站音频URL失败:', error);
throw error;
}
}
};

View File

@@ -1,4 +1,5 @@
import axios from 'axios';
import type { MusicSourceType } from '@/type/music';
/**
@@ -19,8 +20,8 @@ export interface ParsedMusicResult {
params: {
id: number;
type: string;
}
}
};
};
}
/**
@@ -59,9 +60,9 @@ export const parseFromGDMusic = async (
// 处理不同的艺术家字段结构
if (data.artists && Array.isArray(data.artists)) {
artistNames = data.artists.map(artist => artist.name).join(' ');
artistNames = data.artists.map((artist) => artist.name).join(' ');
} else if (data.ar && Array.isArray(data.ar)) {
artistNames = data.ar.map(artist => artist.name).join(' ');
artistNames = data.ar.map((artist) => artist.name).join(' ');
} else if (data.artist) {
artistNames = typeof data.artist === 'string' ? data.artist : '';
}
@@ -74,8 +75,7 @@ export const parseFromGDMusic = async (
}
// 所有可用的音乐源 netease、joox、tidal
const allSources = ['joox', 'tidal', 'netease'
] as MusicSourceType[];
const allSources = ['joox', 'tidal', 'netease'] as MusicSourceType[];
console.log('GD音乐台开始搜索:', searchQuery);

View File

@@ -1,13 +1,15 @@
import { cloneDeep } from 'lodash';
import { musicDB } from '@/hooks/MusicHook';
import { useSettingsStore, useUserStore } from '@/store';
import type { ILyric } from '@/type/lyric';
import type { SongResult } from '@/type/music';
import { isElectron } from '@/utils';
import request from '@/utils/request';
import requestMusic from '@/utils/request_music';
import { cloneDeep } from 'lodash';
import { parseFromGDMusic } from './gdmusic';
import type { SongResult } from '@/type/music';
import { searchAndGetBilibiliAudioUrl } from './bilibili';
import { parseFromGDMusic } from './gdmusic';
const { addData, getData, deleteData } = musicDB;
@@ -89,7 +91,8 @@ export const getMusicLrc = async (id: number) => {
*/
const getBilibiliAudio = async (data: SongResult) => {
const songName = data?.name || '';
const artistName = Array.isArray(data?.ar) && data.ar.length > 0 && data.ar[0]?.name ? data.ar[0].name : '';
const artistName =
Array.isArray(data?.ar) && data.ar.length > 0 && data.ar[0]?.name ? data.ar[0].name : '';
const albumName = data?.al && typeof data.al === 'object' && data.al?.name ? data.al.name : '';
const searchQuery = [songName, artistName, albumName].filter(Boolean).join(' ').trim();
@@ -131,7 +134,7 @@ const getGDMusicAudio = async (id: number, data: SongResult) => {
* @returns 解析结果
*/
const getUnblockMusicAudio = (id: number, data: SongResult, sources: any[]) => {
const filteredSources = sources.filter(source => source !== 'gdmusic');
const filteredSources = sources.filter((source) => source !== 'gdmusic');
console.log(`使用unblockMusic解析音源:`, filteredSources);
return window.api.unblockMusic(id, cloneDeep(data), cloneDeep(filteredSources));
};
@@ -187,7 +190,7 @@ export const getParsingMusicUrl = async (id: number, data: SongResult) => {
// GD解析失败继续下一步
console.log('GD音乐台解析失败尝试使用其他音源');
}
console.log('musicSources',musicSources)
console.log('musicSources', musicSources);
// 2.3 使用unblockMusic解析其他音源
if (isElectron && musicSources.length > 0) {
return getUnblockMusicAudio(id, data, musicSources);

View File

@@ -14,7 +14,6 @@ export function getUserPlaylist(uid: number, limit: number = 30, offset: number
// 播放历史
// /user/record?uid=32953014&type=1
export function getUserRecord(uid: number, type: number = 0) {
return request.get('/user/record', {
params: { uid, type },
noRetry: true

View File

@@ -10,7 +10,7 @@ body {
border-radius: 0.5rem !important;
overflow: hidden !important;
}
.n-popover:has(.transparent-popover ) {
.n-popover:has(.transparent-popover) {
background-color: transparent !important;
padding: 0 !important;
}

File diff suppressed because one or more lines are too long

View File

@@ -1,7 +1,8 @@
<template>
<div class="eq-control">
<div class="eq-header">
<h3>{{ t('player.eq.title') }}
<h3>
{{ t('player.eq.title') }}
<n-tag type="warning" size="small" round v-if="!isElectron">
桌面版可用网页端不支持
</n-tag>

View File

@@ -27,18 +27,10 @@
<div class="warning-message">
<h3>获取完整体验</h3>
<p class="platform-support">
<span>
<i class="ri-window-line mr-1"></i>Windows 10+
</span>
<span>
<i class="ri-apple-line mr-1"></i>macOS
</span>
<span>
<i class="ri-ubuntu-line mr-1"></i>Linux
</span>
<span>
<i class="ri-android-line mr-1"></i>Android
</span>
<span> <i class="ri-window-line mr-1"></i>Windows 10+ </span>
<span> <i class="ri-apple-line mr-1"></i>macOS </span>
<span> <i class="ri-ubuntu-line mr-1"></i>Linux </span>
<span> <i class="ri-android-line mr-1"></i>Android </span>
</p>
<p class="description">
下载桌面应用以获得最佳音乐体验包含完整功能与更高音质
@@ -47,7 +39,11 @@
</div>
<div class="action-links">
<a href="https://mp.weixin.qq.com/s/9pr1XQB36gShM_-TG2LBdg" target="_blank" class="doc-link">
<a
href="https://mp.weixin.qq.com/s/9pr1XQB36gShM_-TG2LBdg"
target="_blank"
class="doc-link"
>
<i class="ri-file-text-line mr-1"></i> 查看使用文档
</a>
<a href="http://donate.alger.fun/download" target="_blank" class="download-link">
@@ -81,7 +77,9 @@
<div class="drawer-actions">
<n-button secondary class="action-button" @click="markAsDonated">已支持</n-button>
<n-button type="primary" class="action-button primary" @click="remindLater">稍后提醒</n-button>
<n-button type="primary" class="action-button primary" @click="remindLater"
>稍后提醒</n-button
>
</div>
</div>
</div>
@@ -90,7 +88,8 @@
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onMounted, ref } from 'vue';
import { isMobile } from '@/utils';
// 控制抽屉显示状态
@@ -396,12 +395,12 @@ onMounted(() => {
.drawer-actions {
flex-wrap: wrap;
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 10px;
background-color: #fff;
z-index: 999999999;
bottom: 0;
left: 0;
right: 0;
padding: 10px;
background-color: #fff;
z-index: 999999999;
.action-button {
flex: 1 0 auto;

View File

@@ -4,31 +4,21 @@
<div class="description">
<p>{{ t('donation.description') }}</p>
<p>{{ t('donation.message') }}</p>
<n-button type="primary" @click="toDonateList">
<template #icon>
<i class="ri-cup-line"></i>
</template>
{{ t('donation.toDonateList') }}
</n-button>
<n-button type="primary" @click="toDonateList">
<template #icon>
<i class="ri-cup-line"></i>
</template>
{{ t('donation.toDonateList') }}
</n-button>
</div>
<div class="qrcode-grid">
<div class="qrcode-item">
<n-image
:src="alipay"
:alt="t('common.alipay')"
class="qrcode-image"
preview-disabled
/>
<n-image :src="alipay" :alt="t('common.alipay')" class="qrcode-image" preview-disabled />
<span class="qrcode-label">{{ t('common.alipay') }}</span>
</div>
<div class="qrcode-item">
<n-image
:src="wechat"
:alt="t('common.wechat')"
class="qrcode-image"
preview-disabled
/>
<n-image :src="wechat" :alt="t('common.wechat')" class="qrcode-image" preview-disabled />
<span class="qrcode-label">{{ t('common.wechat') }}</span>
</div>
</div>
@@ -53,12 +43,7 @@
>
<div class="card-content">
<div class="donor-avatar">
<n-avatar
:src="donor.avatar"
:fallback-src="defaultAvatar"
round
class="avatar-img"
/>
<n-avatar :src="donor.avatar" :fallback-src="defaultAvatar" round class="avatar-img" />
</div>
<div class="donor-info">
<div class="donor-meta">

View File

@@ -59,9 +59,9 @@ onMounted(() => {
// 监听下载完成
window.electron.ipcRenderer.on('music-download-complete', async (_, data) => {
if (data.success) {
downloadList.value = downloadList.value.filter(item => item.filename !== data.filename);
downloadList.value = downloadList.value.filter((item) => item.filename !== data.filename);
} else {
const existingItem = downloadList.value.find(item => item.filename === data.filename);
const existingItem = downloadList.value.find((item) => item.filename === data.filename);
if (existingItem) {
Object.assign(existingItem, {
status: 'error',
@@ -69,7 +69,7 @@ onMounted(() => {
progress: 0
});
setTimeout(() => {
downloadList.value = downloadList.value.filter(item => item.filename !== data.filename);
downloadList.value = downloadList.value.filter((item) => item.filename !== data.filename);
}, 3000);
}
}

View File

@@ -1,4 +1,5 @@
import { Router } from 'vue-router';
import { useMusicStore } from '@/store/modules/music';
/**

View File

@@ -31,13 +31,14 @@
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
import { getAlbum, getListDetail } from '@/api/list';
import MvPlayer from '@/components/MvPlayer.vue';
import { useMusicStore } from '@/store/modules/music';
import { usePlayerStore } from '@/store/modules/player';
import { IMvItem } from '@/type/mv';
import { getImgUrl } from '@/utils';
import { useRouter } from 'vue-router';
import { useMusicStore } from '@/store/modules/music';
const props = withDefaults(
defineProps<{
@@ -90,12 +91,7 @@ const handleClick = async () => {
};
// 保存数据到store
musicStore.setCurrentMusicList(
songList.value,
props.item.name,
listInfo.value,
false
);
musicStore.setCurrentMusicList(songList.value, props.item.name, listInfo.value, false);
// 使用路由跳转
router.push({
@@ -109,12 +105,7 @@ const handleClick = async () => {
listInfo.value = res.data.playlist;
// 保存数据到store
musicStore.setCurrentMusicList(
songList.value,
props.item.name,
listInfo.value,
false
);
musicStore.setCurrentMusicList(songList.value, props.item.name, listInfo.value, false);
// 使用路由跳转
router.push({

View File

@@ -16,12 +16,13 @@
<script lang="ts" setup>
import { computed } from 'vue';
import type { SongResult } from '@/type/music';
import StandardSongItem from './songItemCom/StandardSongItem.vue';
import MiniSongItem from './songItemCom/MiniSongItem.vue';
import ListSongItem from './songItemCom/ListSongItem.vue';
import CompactSongItem from './songItemCom/CompactSongItem.vue';
import ListSongItem from './songItemCom/ListSongItem.vue';
import MiniSongItem from './songItemCom/MiniSongItem.vue';
import StandardSongItem from './songItemCom/StandardSongItem.vue';
const props = withDefaults(
defineProps<{

View File

@@ -421,7 +421,7 @@ const handleUpdate = async () => {
}
</style>
<style lang="scss">
<style lang="scss" scoped>
/* 对话框内容样式 */
.update-dialog-content {
display: flex;

View File

@@ -33,10 +33,11 @@
</template>
<script lang="ts" setup>
import SongItemDropdown from './SongItemDropdown.vue';
import { useSongItem } from '@/hooks/useSongItem';
import { isElectron } from '@/utils';
import type { SongResult } from '@/type/music';
import { isElectron } from '@/utils';
import SongItemDropdown from './SongItemDropdown.vue';
const props = defineProps<{
item: SongResult;

View File

@@ -14,7 +14,11 @@
>
<!-- 索引插槽 -->
<template #index>
<div v-if="index !== undefined" class="song-item-index" :class="{ 'text-green-500': isPlaying }">
<div
v-if="index !== undefined"
class="song-item-index"
:class="{ 'text-green-500': isPlaying }"
>
{{ index + 1 }}
</div>
</template>
@@ -31,7 +35,11 @@
<div class="song-item-content-compact">
<div class="song-item-content-compact-wrapper">
<div class="song-item-content-compact-title w-60 flex-shrink-0">
<n-ellipsis class="text-ellipsis" line-clamp="1" :class="{ 'text-green-500': isPlaying }">
<n-ellipsis
class="text-ellipsis"
line-clamp="1"
:class="{ 'text-green-500': isPlaying }"
>
{{ item.name }}
</n-ellipsis>
</div>
@@ -60,7 +68,11 @@
<!-- 操作插槽 -->
<template #operating>
<div class="song-item-operating-compact">
<div v-if="favorite" class="song-item-operating-like" :class="{ 'opacity-0': !isHovering && !isFavorite }">
<div
v-if="favorite"
class="song-item-operating-like"
:class="{ 'opacity-0': !isHovering && !isFavorite }"
>
<i
class="iconfont icon-likefill"
:class="{ 'like-active': isFavorite }"
@@ -69,13 +81,21 @@
</div>
<div
class="song-item-operating-play animate__animated"
:class="{ 'bg-green-600': isPlaying, 'animate__flipInY': playLoading, 'opacity-0': !isHovering && !isPlaying }"
:class="{
'bg-green-600': isPlaying,
animate__flipInY: playLoading,
'opacity-0': !isHovering && !isPlaying
}"
@click="onPlayMusic"
>
<i v-if="isPlaying && play" class="iconfont icon-stop"></i>
<i v-else class="iconfont icon-playfill"></i>
</div>
<div class="song-item-operating-menu" @click.stop="onMenuClick" :class="{ 'opacity-0': !isHovering && !isPlaying }">
<div
class="song-item-operating-menu"
@click.stop="onMenuClick"
:class="{ 'opacity-0': !isHovering && !isPlaying }"
>
<i class="iconfont ri-more-fill"></i>
</div>
</div>
@@ -86,10 +106,12 @@
<script lang="ts" setup>
import { NCheckbox, NEllipsis } from 'naive-ui';
import { computed, ref } from 'vue';
import { usePlayerStore } from '@/store';
import BaseSongItem from './BaseSongItem.vue';
import type { SongResult } from '@/type/music';
import BaseSongItem from './BaseSongItem.vue';
const playerStore = usePlayerStore();
const props = withDefaults(

View File

@@ -37,7 +37,11 @@
<template #content>
<div class="song-item-content">
<div class="song-item-content-wrapper">
<n-ellipsis class="song-item-content-title text-ellipsis" line-clamp="1" :class="{ 'text-green-500': isPlaying }">
<n-ellipsis
class="song-item-content-title text-ellipsis"
line-clamp="1"
:class="{ 'text-green-500': isPlaying }"
>
{{ item.name }}
</n-ellipsis>
<div class="song-item-content-divider">-</div>
@@ -67,7 +71,7 @@
</div>
<div
class="song-item-operating-play bg-gray-300 dark:bg-gray-800 animate__animated"
:class="{ 'bg-green-600': isPlaying, 'animate__flipInY': playLoading }"
:class="{ 'bg-green-600': isPlaying, animate__flipInY: playLoading }"
@click="onPlayMusic"
>
<i v-if="isPlaying && play" class="iconfont icon-stop"></i>
@@ -81,11 +85,13 @@
<script lang="ts" setup>
import { NCheckbox, NEllipsis, NImage } from 'naive-ui';
import { computed, ref } from 'vue';
import { usePlayerStore } from '@/store';
import BaseSongItem from './BaseSongItem.vue';
import type { SongResult } from '@/type/music';
import { getImgUrl } from '@/utils';
import BaseSongItem from './BaseSongItem.vue';
const playerStore = usePlayerStore();
const props = withDefaults(

View File

@@ -68,7 +68,7 @@
</div>
<div
class="song-item-operating-play bg-gray-300 dark:bg-gray-800 animate__animated"
:class="{ 'bg-green-600': isPlaying, 'animate__flipInY': playLoading }"
:class="{ 'bg-green-600': isPlaying, animate__flipInY: playLoading }"
@click="onPlayMusic"
>
<i v-if="isPlaying && play" class="iconfont icon-stop"></i>
@@ -82,11 +82,13 @@
<script lang="ts" setup>
import { NCheckbox, NEllipsis, NImage } from 'naive-ui';
import { computed, ref } from 'vue';
import { usePlayerStore } from '@/store';
import BaseSongItem from './BaseSongItem.vue';
import type { SongResult } from '@/type/music';
import { getImgUrl } from '@/utils';
import BaseSongItem from './BaseSongItem.vue';
const playerStore = usePlayerStore();
const props = withDefaults(

View File

@@ -15,7 +15,7 @@
<script lang="ts" setup>
import type { MenuOption } from 'naive-ui';
import { NEllipsis, NImage, NDropdown } from 'naive-ui';
import { NDropdown, NEllipsis, NImage } from 'naive-ui';
import { computed, h, inject } from 'vue';
import { useI18n } from 'vue-i18n';
@@ -104,7 +104,9 @@ const renderSongPreview = () => {
},
{
default: () => {
const artistNames = (props.item.ar || props.item.song?.artists)?.map((a) => a.name).join(' / ');
const artistNames = (props.item.ar || props.item.song?.artists)
?.map((a) => a.name)
.join(' / ');
return artistNames || '未知艺术家';
}
}
@@ -164,8 +166,11 @@ const dropdownOptions = computed<MenuOption[]>(() => {
{
label: props.isDislike ? t('songItem.menu.undislike') : t('songItem.menu.dislike'),
key: 'dislike',
icon: () => h('i', { class: `iconfont ${props.isDislike ? 'ri-dislike-fill text-green-500': 'ri-dislike-line'}` })
},
icon: () =>
h('i', {
class: `iconfont ${props.isDislike ? 'ri-dislike-fill text-green-500' : 'ri-dislike-line'}`
})
}
];
if (props.canRemove) {

View File

@@ -37,7 +37,12 @@
<template #content>
<div class="song-item-content">
<div class="song-item-content-title">
<n-ellipsis class="text-ellipsis" line-clamp="1" :class="{ 'text-green-500': isPlaying }">{{ item.name }}</n-ellipsis>
<n-ellipsis
class="text-ellipsis"
line-clamp="1"
:class="{ 'text-green-500': isPlaying }"
>{{ item.name }}</n-ellipsis
>
</div>
<div class="song-item-content-name">
<n-ellipsis class="text-ellipsis" line-clamp="1">
@@ -74,7 +79,7 @@
</n-tooltip>
<div
class="song-item-operating-play bg-gray-300 dark:bg-gray-800 animate__animated"
:class="{ 'bg-green-600': isPlaying, 'animate__flipInY': playLoading }"
:class="{ 'bg-green-600': isPlaying, animate__flipInY: playLoading }"
@click="onPlayMusic"
>
<i v-if="isPlaying && play" class="iconfont icon-stop"></i>
@@ -91,10 +96,11 @@ import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { usePlayerStore } from '@/store';
import BaseSongItem from './BaseSongItem.vue';
import type { SongResult } from '@/type/music';
import { getImgUrl } from '@/utils';
import BaseSongItem from './BaseSongItem.vue';
const { t } = useI18n();
const playerStore = usePlayerStore();

View File

@@ -32,9 +32,9 @@ import { useRouter } from 'vue-router';
import { getNewAlbum } from '@/api/home';
import { getAlbum } from '@/api/list';
import { getImgUrl, setAnimationClass, setAnimationDelay } from '@/utils';
import { navigateToMusicList } from '@/components/common/MusicListNavigator';
import type { IAlbumNew } from '@/type/album';
import { getImgUrl, setAnimationClass, setAnimationDelay } from '@/utils';
const { t } = useI18n();
const albumData = ref<IAlbumNew>();

View File

@@ -30,11 +30,7 @@
</div>
<div class="mt-2">
<p
v-for="item in getDisplayDaySongs.slice(0, 5)"
:key="item.id"
class="text-el"
>
<p v-for="item in getDisplayDaySongs.slice(0, 5)" :key="item.id" class="text-el">
{{ item.name }}
<br />
</p>
@@ -100,7 +96,9 @@
@click="handleArtistClick(item.id)"
>
<div
:style="setBackgroundImg(getImgUrl(item.picUrl || item.avatar || item.cover, '500y500'))"
:style="
setBackgroundImg(getImgUrl(item.picUrl || item.avatar || item.cover, '500y500'))
"
class="recommend-singer-item-bg"
></div>
<div class="recommend-singer-item-count p-2 text-base text-gray-200 z-10">
@@ -128,7 +126,7 @@
</template>
<script lang="ts" setup>
import { onMounted, ref, watchEffect, computed } from 'vue';
import { computed, onMounted, ref, watchEffect } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
@@ -136,6 +134,7 @@ import { getDayRecommend, getHotSinger } from '@/api/home';
import { getListDetail } from '@/api/list';
import { getMusicDetail } from '@/api/music';
import { getUserPlaylist } from '@/api/user';
import { navigateToMusicList } from '@/components/common/MusicListNavigator';
import { useArtist } from '@/hooks/useArtist';
import { usePlayerStore, useUserStore } from '@/store';
import { IDayRecommend } from '@/type/day_recommend';
@@ -150,7 +149,6 @@ import {
setAnimationDelay,
setBackgroundImg
} from '@/utils';
import { navigateToMusicList } from '@/components/common/MusicListNavigator';
const userStore = useUserStore();
const playerStore = usePlayerStore();
@@ -232,7 +230,6 @@ onMounted(async () => {
loadNonUserData();
});
// 提取每日推荐加载逻辑到单独的函数
const loadDayRecommendData = async () => {
try {
@@ -242,7 +239,9 @@ const loadDayRecommendData = async () => {
const dayRecommendSource = dayRecommend as unknown as IDayRecommend;
dayRecommendData.value = {
...dayRecommendSource,
dailySongs: dayRecommendSource.dailySongs.filter((song: any) => !playerStore.dislikeList.includes(song.id))
dailySongs: dayRecommendSource.dailySongs.filter(
(song: any) => !playerStore.dislikeList.includes(song.id)
)
};
} catch (error) {
console.error('获取每日推荐失败:', error);
@@ -260,7 +259,6 @@ const loadNonUserData = async () => {
// 获取热门歌手
const { data: singerData } = await getHotSinger({ offset: 0, limit: 5 });
hotSingerData.value = singerData;
} catch (error) {
console.error('加载热门歌手数据失败:', error);
}
@@ -285,11 +283,13 @@ const handleArtistClick = (id: number) => {
navigateToArtist(id);
};
const getDisplayDaySongs = computed(() => {
if(!dayRecommendData.value){
if (!dayRecommendData.value) {
return [];
}
return dayRecommendData.value.dailySongs.filter((song) => !playerStore.dislikeList.includes(song.id));
})
return dayRecommendData.value.dailySongs.filter(
(song) => !playerStore.dislikeList.includes(song.id)
);
});
const showDayRecommend = () => {
if (!dayRecommendData.value?.dailySongs) return;
@@ -306,7 +306,7 @@ const openPlaylist = (item: any) => {
playlistItem.value = item;
playlistLoading.value = true;
getListDetail(item.id).then(res => {
getListDetail(item.id).then((res) => {
playlistDetail.value = res.data;
playlistLoading.value = false;
@@ -416,7 +416,6 @@ watchEffect(() => {
}
});
const getPlaylistGridClass = (length: number) => {
switch (length) {
case 1:

View File

@@ -1,21 +1,19 @@
<script setup lang="ts">
import { defineProps, defineEmits } from 'vue';
import { defineEmits, defineProps } from 'vue';
import { useI18n } from 'vue-i18n';
const props = defineProps<{
correctionTime: number
correctionTime: number;
}>();
const emit = defineEmits<{
(e: 'adjust', delta: number): void
(e: 'adjust', delta: number): void;
}>();
const { t } = useI18n();
</script>
<template>
<div
class="lyric-correction"
>
<div class="lyric-correction">
<n-tooltip placement="right">
<template #trigger>
<div
@@ -28,7 +26,9 @@ const { t } = useI18n();
</template>
<span>{{ t('player.subtractCorrection', { num: 0.2 }) }}</span>
</n-tooltip>
<span class="text-xs py-0.5 px-1 rounded bg-white/70 dark:bg-neutral-800/70 shadow font-mono tracking-wider text-gray-700 dark:text-gray-200 bg-opacity-40 backdrop-blur-2xl">
<span
class="text-xs py-0.5 px-1 rounded bg-white/70 dark:bg-neutral-800/70 shadow font-mono tracking-wider text-gray-700 dark:text-gray-200 bg-opacity-40 backdrop-blur-2xl"
>
{{ props.correctionTime > 0 ? '+' : '' }}{{ props.correctionTime.toFixed(1) }}s
</span>
<n-tooltip placement="right">
@@ -55,7 +55,7 @@ const { t } = useI18n();
@apply w-7 h-7 flex items-center justify-center rounded-lg bg-white dark:bg-neutral-800 border border-white/20 dark:border-neutral-700/40 shadow-md backdrop-blur-2xl cursor-pointer transition-all duration-150 text-gray-700 dark:text-gray-200 hover:bg-green-500/80 hover:text-white hover:border-green-400/60 active:scale-95 bg-opacity-40 dark:hover:bg-green-500/80 dark:hover:text-white dark:hover:border-green-400/60 dark:hover:bg-opacity-40;
}
.mobile{
.mobile {
.lyric-correction {
@apply opacity-100;
}

View File

@@ -72,7 +72,7 @@
v-if="!config.hideMiniPlayBar"
class="mt-4"
:pure-mode-enabled="config.pureModeEnabled"
:isDark=" textColors.theme === 'dark'"
:isDark="textColors.theme === 'dark'"
/>
</div>
</div>
@@ -135,7 +135,7 @@
</div>
</div>
<!-- 歌词右下角矫正按钮组件 -->
<LyricCorrectionControl
<lyric-correction-control
v-if="!isMobile"
:correction-time="correctionTime"
@adjust="adjustCorrectionTime"
@@ -151,19 +151,19 @@ import { useDebounceFn } from '@vueuse/core';
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import LyricCorrectionControl from '@/components/lyric/LyricCorrectionControl.vue';
import LyricSettings from '@/components/lyric/LyricSettings.vue';
import SimplePlayBar from '@/components/player/SimplePlayBar.vue';
import LyricCorrectionControl from '@/components/lyric/LyricCorrectionControl.vue';
import {
adjustCorrectionTime,
artistList,
correctionTime,
lrcArray,
nowIndex,
playMusic,
setAudioTime,
textColors,
useLyricProgress,
correctionTime,
adjustCorrectionTime
useLyricProgress
} from '@/hooks/MusicHook';
import { useArtist } from '@/hooks/useArtist';
import { usePlayerStore } from '@/store/modules/player';

View File

@@ -7,8 +7,15 @@
:to="`#layout-main`"
:z-index="9998"
>
<div id="mobile-drawer-target" :class="[config.theme, `cover-style-${config.mobileCoverStyle}`, {'is-landscape': isLandscape}, {'is-dark': isDark}]">
<div
id="mobile-drawer-target"
:class="[
config.theme,
`cover-style-${config.mobileCoverStyle}`,
{ 'is-landscape': isLandscape },
{ 'is-dark': isDark }
]"
>
<!-- 顶部控制按钮 -->
<div v-if="playMusic?.playLoading" class="loading-overlay">
<i class="ri-loader-4-line loading-icon"></i>
@@ -23,11 +30,7 @@
<!-- 全屏歌词页面 - 竖屏模式下 -->
<transition name="fade">
<div
v-if="showFullLyrics && !isLandscape"
class="fullscreen-lyrics"
:class="config.theme"
>
<div v-if="showFullLyrics && !isLandscape" class="fullscreen-lyrics" :class="config.theme">
<div class="fullscreen-header">
<div class="song-title">{{ playMusic.name }}</div>
<div class="artist-name">
@@ -74,7 +77,7 @@
'record-style': config.mobileCoverStyle === 'record',
'square-style': config.mobileCoverStyle === 'square',
'full-style': config.mobileCoverStyle === 'full',
'paused': !play
paused: !play
}"
@click="cycleCoverStyle"
>
@@ -108,16 +111,12 @@
</span>
</p>
<div class="favorite-icon" @click="toggleFavorite">
<i class="ri-heart-3-fill" :class="{ 'favorite': isFavorite }"></i>
<i class="ri-heart-3-fill" :class="{ favorite: isFavorite }"></i>
</div>
</div>
<!-- 歌词区域 -->
<div
class="lyrics-container"
v-if="!config.hideLyrics"
@click="showFullLyricScreen"
>
<div class="lyrics-container" v-if="!config.hideLyrics" @click="showFullLyricScreen">
<div v-if="lrcArray.length > 0" class="lyrics-wrapper">
<div v-for="(line, idx) in visibleLyrics" :key="idx" class="lyric-line">
{{ line.text }}
@@ -141,7 +140,7 @@
'record-style': config.mobileCoverStyle === 'record',
'square-style': config.mobileCoverStyle === 'square',
'full-style': config.mobileCoverStyle === 'full',
'paused': !play
paused: !play
}"
@click="cycleCoverStyle"
>
@@ -162,9 +161,11 @@
<span class="current-time">{{ secondToMinute(nowTime) }}</span>
<span class="total-time">{{ secondToMinute(allTime) }}</span>
</div>
<div class="apple-style-progress"
<div
class="apple-style-progress"
@click="handleProgressBarClick"
@mousedown="handleMouseDown">
@mousedown="handleMouseDown"
>
<div class="progress-track">
<div
class="progress-fill"
@@ -172,7 +173,7 @@
></div>
<div
class="progress-thumb"
:class="{ 'active': isThumbDragging || isMouseDragging }"
:class="{ active: isThumbDragging || isMouseDragging }"
:style="{ left: `${(nowTime / Math.max(1, allTime)) * 100}%` }"
@touchstart="handleThumbTouchStart"
@touchmove="handleThumbTouchMove"
@@ -202,7 +203,7 @@
</p>
</div>
<div class="favorite-icon landscape" @click="toggleFavorite">
<i class="ri-heart-3-fill" :class="{ 'favorite': isFavorite }"></i>
<i class="ri-heart-3-fill" :class="{ favorite: isFavorite }"></i>
</div>
</div>
@@ -248,16 +249,22 @@
</div>
<!-- 竖屏模式的控制区域 -->
<div v-if="!isLandscape" class="unified-controls" :class="{ 'fullscreen-mode': showFullLyrics }">
<div
v-if="!isLandscape"
class="unified-controls"
:class="{ 'fullscreen-mode': showFullLyrics }"
>
<!-- 进度条 (苹果风格) -->
<div class="progress-container">
<div class="time-info">
<span class="current-time">{{ secondToMinute(nowTime) }}</span>
<span class="total-time">{{ secondToMinute(allTime) }}</span>
</div>
<div class="apple-style-progress"
<div
class="apple-style-progress"
@click="handleProgressBarClick"
@mousedown="handleMouseDown">
@mousedown="handleMouseDown"
>
<div class="progress-track">
<div
class="progress-fill"
@@ -265,7 +272,7 @@
></div>
<div
class="progress-thumb"
:class="{ 'active': isThumbDragging || isMouseDragging }"
:class="{ active: isThumbDragging || isMouseDragging }"
:style="{ left: `${(nowTime / Math.max(1, allTime)) * 100}%` }"
@touchstart="handleThumbTouchStart"
@touchmove="handleThumbTouchMove"
@@ -304,9 +311,9 @@
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { useWindowSize } from '@vueuse/core';
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import {
allTime,
@@ -331,7 +338,7 @@ const playerStore = usePlayerStore();
// 播放控制相关
const play = computed(() => playerStore.isPlay);
const playIcon = computed(() => play.value ? 'ri-pause-fill' : 'ri-play-fill');
const playIcon = computed(() => (play.value ? 'ri-pause-fill' : 'ri-play-fill'));
const playMode = computed(() => playerStore.playMode);
const playModeIcon = computed(() => {
switch (playMode.value) {
@@ -440,7 +447,11 @@ const scrollToCurrentLyric = (immediate = false, customScrollerRef?: HTMLElement
const lineRect = activeEl.getBoundingClientRect();
// 优化滚动位置计算,确保当前歌词在视图中央
const scrollTop = scrollerRef.scrollTop + (lineRect.top - containerRect.top) - (containerRect.height / 2) + (lineRect.height / 2);
const scrollTop =
scrollerRef.scrollTop +
(lineRect.top - containerRect.top) -
containerRect.height / 2 +
lineRect.height / 2;
console.log(`滚动到歌词 #${nowIndex.value}, 位置: ${scrollTop}px`);
@@ -528,8 +539,11 @@ const handleTouchStart = (e: TouchEvent) => {
touchStartY.value = e.touches[0].clientY;
// 根据当前模式获取正确的滚动容器
const scrollerRef = showFullLyrics.value ? lyricsScrollerRef.value :
(isLandscape.value ? landscapeLyricsRef.value : lyricsScrollerRef.value);
const scrollerRef = showFullLyrics.value
? lyricsScrollerRef.value
: isLandscape.value
? landscapeLyricsRef.value
: lyricsScrollerRef.value;
lastScrollTop.value = scrollerRef?.scrollTop || 0;
isTouchScrolling.value = true;
@@ -620,7 +634,9 @@ const handleMouseDown = (e: MouseEvent) => {
isMouseDragging.value = true;
// 立即更新位置
const progressBar = (e.currentTarget as HTMLElement).closest('.apple-style-progress') as HTMLElement;
const progressBar = (e.currentTarget as HTMLElement).closest(
'.apple-style-progress'
) as HTMLElement;
if (progressBar) {
const rect = progressBar.getBoundingClientRect();
const offsetX = e.clientX - rect.left;
@@ -876,11 +892,11 @@ const prevSong = () => {
const togglePlayMode = () => {
playerStore.togglePlayMode();
showBottomToast([
t('player.playMode.sequence'),
t('player.playMode.loop'),
t('player.playMode.random')
][playMode.value]);
showBottomToast(
[t('player.playMode.sequence'), t('player.playMode.loop'), t('player.playMode.random')][
playMode.value
]
);
};
const closeMusicFull = () => {
@@ -1076,18 +1092,20 @@ const getLrcStyle = (index: number) => {
&::before {
content: '';
@apply absolute top-0 left-0 w-full h-full rounded-full z-10;
background: radial-gradient(circle at center,
transparent 38%,
rgba(0, 0, 0, 0.15) 38%,
rgba(0, 0, 0, 0.15) 39%,
rgba(255, 255, 255, 0.1) 39%,
rgba(255, 255, 255, 0.1) 39.5%,
rgba(0, 0, 0, 0.08) 39.5%,
rgba(0, 0, 0, 0.08) 40.5%,
rgba(0, 0, 0, 0.2) 40.5%,
rgba(0, 0, 0, 0.2) 41.5%,
rgba(0, 0, 0, 0.6) 41.5%,
rgba(0, 0, 0, 0.6) 100%);
background: radial-gradient(
circle at center,
transparent 38%,
rgba(0, 0, 0, 0.15) 38%,
rgba(0, 0, 0, 0.15) 39%,
rgba(255, 255, 255, 0.1) 39%,
rgba(255, 255, 255, 0.1) 39.5%,
rgba(0, 0, 0, 0.08) 39.5%,
rgba(0, 0, 0, 0.08) 40.5%,
rgba(0, 0, 0, 0.2) 40.5%,
rgba(0, 0, 0, 0.2) 41.5%,
rgba(0, 0, 0, 0.6) 41.5%,
rgba(0, 0, 0, 0.6) 100%
);
pointer-events: none;
animation: spin 20s linear infinite;
animation-play-state: running;
@@ -1103,7 +1121,8 @@ const getLrcStyle = (index: number) => {
}
&.paused {
&::before, &::after {
&::before,
&::after {
animation-play-state: paused;
}
}
@@ -1118,10 +1137,12 @@ const getLrcStyle = (index: number) => {
&::after {
content: '';
@apply absolute top-0 left-0 w-full h-full rounded-full z-[2];
background: linear-gradient(135deg,
rgba(255, 255, 255, 0.05) 0%,
rgba(255, 255, 255, 0) 50%,
rgba(0, 0, 0, 0.05) 100%);
background: linear-gradient(
135deg,
rgba(255, 255, 255, 0.05) 0%,
rgba(255, 255, 255, 0) 50%,
rgba(0, 0, 0, 0.05) 100%
);
pointer-events: none;
}
}
@@ -1141,7 +1162,8 @@ const getLrcStyle = (index: number) => {
.time-info {
@apply flex justify-between items-center mb-2;
.current-time, .total-time {
.current-time,
.total-time {
@apply text-sm;
color: var(--text-color-primary);
opacity: 0.8;
@@ -1267,7 +1289,13 @@ const getLrcStyle = (index: number) => {
@apply h-full w-full overflow-y-auto pt-24 pb-24;
scroll-behavior: smooth;
-webkit-overflow-scrolling: touch;
mask-image: linear-gradient(to bottom, transparent 5%, black 15%, black 85%, transparent 95%);
mask-image: linear-gradient(
to bottom,
transparent 5%,
black 15%,
black 85%,
transparent 95%
);
-webkit-mask-image: linear-gradient(
to bottom,
transparent 5%,
@@ -1343,7 +1371,7 @@ const getLrcStyle = (index: number) => {
@apply text-base mb-2;
}
.ri-heart-3-fill{
.ri-heart-3-fill {
@apply text-2xl;
}
}
@@ -1352,7 +1380,7 @@ const getLrcStyle = (index: number) => {
// 统一控制区域
.unified-controls {
@apply fixed bottom-0 left-0 right-0 px-6 pt-6 pb-6;
background: linear-gradient(to top, rgba(0,0,0,0.5) 0%, rgba(0,0,0,0) 100%);
background: linear-gradient(to top, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0) 100%);
height: 230px;
pointer-events: auto;
z-index: 10000 !important;
@@ -1587,7 +1615,7 @@ const getLrcStyle = (index: number) => {
.fullscreen-header {
@apply pt-8 pb-4 px-6 flex flex-col items-center fixed top-0 left-0 w-full z-10;
background: linear-gradient(to bottom, rgba(0,0,0,0.2) 0%, rgba(0,0,0,0) 100%);
background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0) 100%);
height: 100px;
pointer-events: auto;
@@ -1674,7 +1702,7 @@ const getLrcStyle = (index: number) => {
}
}
#mobile-drawer-target{
#mobile-drawer-target {
// 横屏模式下的歌词样式
&.is-landscape {
.landscape-lyrics-section {
@@ -1703,7 +1731,7 @@ const getLrcStyle = (index: number) => {
.unified-controls {
&.fullscreen-mode {
background: linear-gradient(to top, rgba(0,0,0,0.8) 0%, rgba(0,0,0,0) 100%);
background: linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0) 100%);
}
.back-button {
@@ -1771,7 +1799,11 @@ const getLrcStyle = (index: number) => {
left: 0;
right: 0;
height: 40%;
background: linear-gradient(transparent, var(--bg-color, rgba(25, 25, 25, 1)) 70%, var(--bg-color, rgba(25, 25, 25, 1)));
background: linear-gradient(
transparent,
var(--bg-color, rgba(25, 25, 25, 1)) 70%,
var(--bg-color, rgba(25, 25, 25, 1))
);
z-index: 1;
pointer-events: none;
}
@@ -1786,10 +1818,9 @@ const getLrcStyle = (index: number) => {
}
}
.is-dark{
.square-style{
.is-dark {
.square-style {
@apply shadow-2xl shadow-black/50;
}
}
</style>

View File

@@ -4,9 +4,10 @@
<script setup lang="ts">
import { computed } from 'vue';
import { isMobile } from '@/utils';
import MusicFull from '@/components/lyric/MusicFull.vue';
import MusicFullMobile from '@/components/lyric/MusicFullMobile.vue';
import { isMobile } from '@/utils';
// 根据当前设备类型选择需要显示的组件
const componentToUse = computed(() => {

View File

@@ -44,7 +44,11 @@
class="color-preview"
:style="{ backgroundColor: currentColor }"
@click="showColorPicker = !showColorPicker"
:title="showColorPicker ? t('settings.themeColor.tooltips.closeColorPicker') : t('settings.themeColor.tooltips.openColorPicker')"
:title="
showColorPicker
? t('settings.themeColor.tooltips.closeColorPicker')
: t('settings.themeColor.tooltips.openColorPicker')
"
>
<i class="ri-palette-line"></i>
</div>
@@ -86,16 +90,16 @@
</template>
<script setup lang="ts">
import { NColorPicker } from 'naive-ui';
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { NColorPicker } from 'naive-ui';
import {
getLyricThemeColors,
getPresetColorValue,
validateColor,
type LyricThemeColor,
optimizeColorForTheme,
type LyricThemeColor
validateColor
} from '@/utils/linearColor';
interface Props {
@@ -105,7 +109,7 @@ interface Props {
}
interface Emits {
(e: 'colorChange', color: string): void;
(e: 'colorChange', _color: string): void;
(e: 'close'): void;
}

View File

@@ -6,7 +6,7 @@
:z-index="9999999"
@select="handleSelect"
placement="top"
@update:show="(show) => showDropdown = show"
@update:show="(show) => (showDropdown = show)"
>
<n-tooltip trigger="hover" :z-index="9999999">
<template #trigger>
@@ -26,7 +26,12 @@
</n-dropdown>
<!-- EQ 均衡器弹窗 -->
<n-modal v-model:show="showEQModal" :mask-closable="true" :unstable-show-mask="false" :z-index="9999999">
<n-modal
v-model:show="showEQModal"
:mask-closable="true"
:unstable-show-mask="false"
:z-index="9999999"
>
<div class="eq-modal-content">
<div class="modal-close" @click="showEQModal = false">
<i class="ri-close-line"></i>
@@ -36,7 +41,12 @@
</n-modal>
<!-- 定时关闭弹窗 -->
<n-modal v-model:show="playerStore.showSleepTimer" :mask-closable="true" :unstable-show-mask="false" :z-index="9999999">
<n-modal
v-model:show="playerStore.showSleepTimer"
:mask-closable="true"
:unstable-show-mask="false"
:z-index="9999999"
>
<div class="timer-modal-content">
<div class="modal-close" @click="playerStore.showSleepTimer = false">
<i class="ri-close-line"></i>
@@ -46,7 +56,12 @@
</n-modal>
<!-- 播放速度设置弹窗 -->
<n-modal v-model:show="showSpeedModal" :mask-closable="true" :unstable-show-mask="false" :z-index="9999999">
<n-modal
v-model:show="showSpeedModal"
:mask-closable="true"
:unstable-show-mask="false"
:z-index="9999999"
>
<div class="speed-modal-content">
<div class="modal-close" @click="showSpeedModal = false">
<i class="ri-close-line"></i>
@@ -57,7 +72,7 @@
v-for="option in playbackRateOptions"
:key="option.key"
class="speed-option"
:class="{ 'active': playbackRate === option.key }"
:class="{ active: playbackRate === option.key }"
@click="selectSpeed(option.key)"
>
{{ option.label }}
@@ -68,12 +83,13 @@
</template>
<script lang="ts" setup>
import { ref, computed, h, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { DropdownOption } from 'naive-ui';
import { usePlayerStore } from '@/store/modules/player';
import { computed, h, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import EqControl from '@/components/EQControl.vue';
import SleepTimer from '@/components/player/SleepTimer.vue';
import { usePlayerStore } from '@/store/modules/player';
const { t } = useI18n();
const playerStore = usePlayerStore();
@@ -93,13 +109,16 @@ watch(showEQModal, (newValue) => {
}
});
watch(() => playerStore.showSleepTimer, (newValue) => {
if (newValue) {
// 如果睡眠定时器弹窗打开,关闭其他弹窗
showEQModal.value = false;
showSpeedModal.value = false;
watch(
() => playerStore.showSleepTimer,
(newValue) => {
if (newValue) {
// 如果睡眠定时器弹窗打开,关闭其他弹窗
showEQModal.value = false;
showSpeedModal.value = false;
}
}
});
);
watch(showSpeedModal, (newValue) => {
if (newValue) {
@@ -142,14 +161,17 @@ const dropdownOptions = computed<DropdownOption[]>(() => [
key: 'timer',
icon: () => h('i', { class: 'ri-timer-line' }),
// 如果有激活的定时器,添加标记
suffix: () => hasActiveSleepTimer.value ? h('span', { class: 'active-option-mark' }) : null
suffix: () => (hasActiveSleepTimer.value ? h('span', { class: 'active-option-mark' }) : null)
},
{
label: t('player.playBar.playbackSpeed') + `(${playbackRate.value}x)`,
key: 'speed',
icon: () => h('i', { class: 'ri-speed-line' }),
// 如果播放速度不是1.0,添加标记
suffix: () => playbackRate.value !== 1.0 ? h('span', { class: 'active-option-mark' }, `${playbackRate.value}x`) : null
suffix: () =>
playbackRate.value !== 1.0
? h('span', { class: 'active-option-mark' }, `${playbackRate.value}x`)
: null
}
]);
@@ -179,13 +201,12 @@ const selectSpeed = (speed: number) => {
playerStore.setPlaybackRate(speed);
showSpeedModal.value = false;
};
</script>
<style lang="scss" scoped>
.sleep-timer-countdown {
@apply fixed top-0 left-1/2 transform -translate-x-1/2 py-1 px-3 rounded-b-lg bg-green-500 text-white text-sm flex items-center;
box-shadow: 0 2px 10px rgba(0,0,0,0.15);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
z-index: 9998;
min-width: 80px;
text-align: center;
@@ -220,7 +241,8 @@ const selectSpeed = (speed: number) => {
.active-indicator {
@apply absolute -top-1 -right-1 flex;
.timer-badge, .speed-badge {
.timer-badge,
.speed-badge {
@apply flex items-center justify-center text-xs bg-green-500 text-white rounded-full;
height: 16px;
min-width: 16px;

View File

@@ -52,7 +52,13 @@
></i>
</div>
<n-popover v-if="component" trigger="hover" :z-index="99999999" placement="top" :show-arrow="false">
<n-popover
v-if="component"
trigger="hover"
:z-index="99999999"
placement="top"
:show-arrow="false"
>
<template #trigger>
<div class="function-button" @click="mute" @wheel.prevent="handleVolumeWheel">
<i class="iconfont" :class="getVolumeIcon"></i>
@@ -196,7 +202,7 @@ const handleVolumeWheel = (e: WheelEvent) => {
const isFavorite = computed(() => {
// 对于B站视频使用ID匹配函数
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) {
return playerStore.favoriteList.some(id => isBilibiliIdMatch(id, playMusic.value.id));
return playerStore.favoriteList.some((id) => isBilibiliIdMatch(id, playMusic.value.id));
}
// 非B站视频直接比较ID
@@ -642,7 +648,7 @@ const setMusicFull = () => {
}
}
:deep(.n-popover){
:deep(.n-popover) {
background-color: transparent !important;
}
</style>

View File

@@ -112,8 +112,8 @@
import { useThrottleFn } from '@vueuse/core';
import { computed, ref, watch } from 'vue';
import { allTime, artistList, nowTime, playMusic, sound, textColors } from '@/hooks/MusicHook';
import MusicFullWrapper from '@/components/lyric/MusicFullWrapper.vue';
import { allTime, artistList, nowTime, playMusic, sound, textColors } from '@/hooks/MusicHook';
import { usePlayerStore } from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings';
import { getImgUrl, secondToMinute, setAnimationClass } from '@/utils';

View File

@@ -60,9 +60,7 @@
<n-ellipsis class="text-ellipsis" line-clamp="1">
{{ playMusic.name }}
</n-ellipsis>
<span v-if="playbackRate !== 1.0" class="playback-rate-badge">
{{ playbackRate }}x
</span>
<span v-if="playbackRate !== 1.0" class="playback-rate-badge"> {{ playbackRate }}x </span>
</div>
<div class="music-content-name">
<n-ellipsis
@@ -143,7 +141,10 @@
<n-tooltip trigger="hover" :z-index="9999999">
<template #trigger>
<i class="iconfont icon-list text-2xl hover:text-green-500 transition-colors cursor-pointer" @click="openPlayListDrawer"></i>
<i
class="iconfont icon-list text-2xl hover:text-green-500 transition-colors cursor-pointer"
@click="openPlayListDrawer"
></i>
</template>
{{ t('player.playBar.playList') }}
</n-tooltip>
@@ -156,8 +157,12 @@
<script lang="ts" setup>
import { useThrottleFn } from '@vueuse/core';
import { useMessage } from 'naive-ui';
import { storeToRefs } from 'pinia';
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import MusicFullWrapper from '@/components/lyric/MusicFullWrapper.vue';
import AdvancedControlsPopover from '@/components/player/AdvancedControlsPopover.vue';
import ReparsePopover from '@/components/player/ReparsePopover.vue';
import {
allTime,
@@ -169,16 +174,10 @@ import {
textColors
} from '@/hooks/MusicHook';
import { useArtist } from '@/hooks/useArtist';
import MusicFullWrapper from '@/components/lyric/MusicFullWrapper.vue';
import { audioService } from '@/services/audioService';
import {
isBilibiliIdMatch,
usePlayerStore
} from '@/store/modules/player';
import { isBilibiliIdMatch, usePlayerStore } from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings';
import { getImgUrl, isElectron, isMobile, secondToMinute, setAnimationClass } from '@/utils';
import AdvancedControlsPopover from '@/components/player/AdvancedControlsPopover.vue';
import { storeToRefs } from 'pinia';
const playerStore = usePlayerStore();
const settingsStore = useSettingsStore();
@@ -313,7 +312,7 @@ const playModeText = computed(() => {
});
// 播放速度控制
const {playbackRate} = storeToRefs(playerStore);
const { playbackRate } = storeToRefs(playerStore);
// 切换播放模式
const togglePlayMode = () => {
playerStore.togglePlayMode();
@@ -333,7 +332,7 @@ const showSliderTooltip = ref(false);
// 播放暂停按钮事件
const playMusicEvent = async () => {
try {
const result = await playerStore.setPlay({ ...playMusic.value});
const result = await playerStore.setPlay({ ...playMusic.value });
if (result) {
playerStore.setPlayMusic(true);
}
@@ -348,7 +347,7 @@ const musicFullVisible = computed({
set: (value) => {
playerStore.setMusicFull(value);
}
})
});
// 设置musicFull
const setMusicFull = () => {
@@ -362,7 +361,7 @@ const setMusicFull = () => {
const isFavorite = computed(() => {
// 对于B站视频使用ID匹配函数
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) {
return playerStore.favoriteList.some(id => isBilibiliIdMatch(id, playMusic.value.id));
return playerStore.favoriteList.some((id) => isBilibiliIdMatch(id, playMusic.value.id));
}
// 非B站视频直接比较ID
@@ -728,7 +727,6 @@ const openPlayListDrawer = () => {
background: var(--hover-color-dark);
}
.playback-rate-badge {
@apply ml-2 px-1.5 h-4 flex items-center text-xs rounded bg-green-500 bg-opacity-15 text-green-600 dark:text-green-400;
font-weight: 500;

View File

@@ -8,8 +8,13 @@
class="playlist-panel"
:class="[
'animate__animated',
closing ? (isMobile ? 'animate__slideOutDown' : 'animate__slideOutRight') :
(isMobile ? 'animate__slideInUp' : 'animate__slideInRight')
closing
? isMobile
? 'animate__slideOutDown'
: 'animate__slideOutRight'
: isMobile
? 'animate__slideInUp'
: 'animate__slideInRight'
]"
>
<div class="playlist-panel-header">
@@ -21,7 +26,7 @@
<i class="iconfont ri-delete-bin-line"></i>
</div>
</template>
{{ t('player.playList.clearAll')}}
{{ t('player.playList.clearAll') }}
</n-tooltip>
<div class="close-btn" @click="closePanel">
<i class="iconfont ri-close-line"></i>
@@ -31,7 +36,7 @@
<div class="playlist-panel-content">
<div v-if="playList.length === 0" class="empty-playlist">
<i class="iconfont ri-music-2-line"></i>
<p>{{ t('player.playList.empty')}}</p>
<p>{{ t('player.playList.empty') }}</p>
</div>
<n-virtual-list v-else ref="playListRef" :item-size="62" item-resizable :items="playList">
<template #default="{ item }">
@@ -52,9 +57,10 @@
</template>
<script setup lang="ts">
import { computed, ref, watch, onMounted, onUnmounted, nextTick } from 'vue';
import { useDialog, useMessage } from 'naive-ui';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage, useDialog } from 'naive-ui';
import SongItem from '@/components/common/SongItem.vue';
import { usePlayerStore } from '@/store/modules/player';
import type { SongResult } from '@/type/music';
@@ -78,27 +84,31 @@ const show = computed({
});
// 监听外部可见性变化
watch(show, (newValue) => {
if (newValue) {
// 打开面板
internalVisible.value = true;
closing.value = false;
// 在下一个渲染周期后滚动到当前歌曲
nextTick(() => {
scrollToCurrentSong();
});
} else {
// 如果已经是关闭状态,不需要处理
if (!internalVisible.value) return;
watch(
show,
(newValue) => {
if (newValue) {
// 打开面板
internalVisible.value = true;
closing.value = false;
// 在下一个渲染周期后滚动到当前歌曲
nextTick(() => {
scrollToCurrentSong();
});
} else {
// 如果已经是关闭状态,不需要处理
if (!internalVisible.value) return;
// 开始关闭动画
closing.value = true;
// 等待动画完成后再隐藏组件
setTimeout(() => {
internalVisible.value = false;
}, 400); // 动画持续时间
}
}, { immediate: true });
// 开始关闭动画
closing.value = true;
// 等待动画完成后再隐藏组件
setTimeout(() => {
internalVisible.value = false;
}, 400); // 动画持续时间
}
},
{ immediate: true }
);
// 播放列表
const playList = computed(() => playerStore.playList as SongResult[]);
@@ -118,7 +128,7 @@ const handleClearPlaylist = () => {
return;
}
if(isMobile.value){
if (isMobile.value) {
closePanel();
}
@@ -160,7 +170,7 @@ const scrollToCurrentSong = () => {
const index = playerStore.playListIndex;
console.log('滚动到歌曲索引:', index);
playListRef.value.scrollTo({
top: (index > 3 ? (index - 3) : 0) * 62,
top: (index > 3 ? index - 3 : 0) * 62
});
}
}, 100);
@@ -287,7 +297,7 @@ const handleDeleteSong = (song: SongResult) => {
&-content {
height: calc(80vh - 60px);
@apply px-4;
.delete-btn{
.delete-btn {
@apply visible;
}
}

View File

@@ -40,10 +40,16 @@
<div class="flex-1 text-sm whitespace-nowrap overflow-hidden text-ellipsis">
{{ source.label }}
</div>
<div v-if="isReparsing && currentReparsingSource === source.value" class="w-5 h-5 flex items-center justify-center">
<div
v-if="isReparsing && currentReparsingSource === source.value"
class="w-5 h-5 flex items-center justify-center"
>
<i class="ri-loader-4-line animate-spin"></i>
</div>
<div v-else-if="isCurrentSource(source.value)" class="w-5 h-5 flex items-center justify-center">
<div
v-else-if="isCurrentSource(source.value)"
class="w-5 h-5 flex items-center justify-center"
>
<i class="ri-check-line"></i>
</div>
</div>
@@ -53,7 +59,10 @@
{{ t('player.reparse.bilibiliNotSupported') }}
</div>
<!-- 清除自定义音源 -->
<div class="text-red-500 text-sm flex items-center bg-light-200 dark:bg-dark-200 rounded-lg p-2 cursor-pointer" @click="clearCustomSource">
<div
class="text-red-500 text-sm flex items-center bg-light-200 dark:bg-dark-200 rounded-lg p-2 cursor-pointer"
@click="clearCustomSource"
>
<div class="flex items-center justify-center w-6 h-6 mr-3 text-lg">
<i class="ri-close-circle-line"></i>
</div>
@@ -66,13 +75,14 @@
</template>
<script lang="ts" setup>
import { useMessage } from 'naive-ui';
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from 'naive-ui';
import { playMusic } from '@/hooks/MusicHook';
import { audioService } from '@/services/audioService';
import { usePlayerStore } from '@/store/modules/player';
import type { Platform } from '@/types/music';
import { audioService } from '@/services/audioService';
const playerStore = usePlayerStore();
const { t } = useI18n();
@@ -104,13 +114,13 @@ const isCurrentSource = (source: Platform) => {
// 获取音源图标
const getSourceIcon = (source: Platform) => {
const iconMap: Record<Platform, string> = {
'migu': 'ri-music-2-fill',
'kugou': 'ri-music-fill',
'qq': 'ri-qq-fill',
'joox': 'ri-disc-fill',
'pyncmd': 'ri-netease-cloud-music-fill',
'bilibili': 'ri-bilibili-fill',
'gdmusic': 'ri-google-fill'
migu: 'ri-music-2-fill',
kugou: 'ri-music-fill',
qq: 'ri-qq-fill',
joox: 'ri-disc-fill',
pyncmd: 'ri-netease-cloud-music-fill',
bilibili: 'ri-bilibili-fill',
gdmusic: 'ri-google-fill'
};
return iconMap[source] || 'ri-music-2-fill';
@@ -125,6 +135,7 @@ const initSelectedSources = () => {
try {
selectedSourcesValue.value = JSON.parse(savedSource);
} catch (e) {
console.error('解析保存的音源设置失败:', e);
selectedSourcesValue.value = [];
}
} else {
@@ -173,48 +184,55 @@ const directReparseMusic = async (source: Platform) => {
};
// 监听歌曲ID变化初始化音源设置
watch(() => playMusic.value.id, () => {
if (playMusic.value.id) {
initSelectedSources();
}
}, { immediate: true });
watch(
() => playMusic.value.id,
() => {
if (playMusic.value.id) {
initSelectedSources();
}
},
{ immediate: true }
);
// 监听歌曲变化,检查是否有自定义音源
watch(() => playMusic.value.id, async (newId) => {
if (newId) {
const songId = String(newId);
const savedSource = localStorage.getItem(`song_source_${songId}`);
watch(
() => playMusic.value.id,
async (newId) => {
if (newId) {
const songId = String(newId);
const savedSource = localStorage.getItem(`song_source_${songId}`);
// 如果有保存的音源设置但当前不是使用自定义解析的播放,尝试应用
if (savedSource && playMusic.value.source !== 'bilibili') {
try {
const sources = JSON.parse(savedSource) as Platform[];
console.log(`检测到歌曲ID ${songId} 有自定义音源设置:`, sources);
// 如果有保存的音源设置但当前不是使用自定义解析的播放,尝试应用
if (savedSource && playMusic.value.source !== 'bilibili') {
try {
const sources = JSON.parse(savedSource) as Platform[];
console.log(`检测到歌曲ID ${songId} 有自定义音源设置:`, sources);
// 当URL加载失败或过期时自动应用自定义音源重新加载
audioService.on('url_expired', async (trackInfo) => {
if (trackInfo && trackInfo.id === playMusic.value.id) {
console.log('URL已过期自动应用自定义音源重新加载');
try {
isReparsing.value = true;
const success = await playerStore.reparseCurrentSong(sources[0]);
if (!success) {
// 当URL加载失败或过期时自动应用自定义音源重新加载
audioService.on('url_expired', async (trackInfo) => {
if (trackInfo && trackInfo.id === playMusic.value.id) {
console.log('URL已过期自动应用自定义音源重新加载');
try {
isReparsing.value = true;
const success = await playerStore.reparseCurrentSong(sources[0]);
if (!success) {
message.error(t('player.reparse.failed'));
}
} catch (e) {
console.error('自动重新解析失败:', e);
message.error(t('player.reparse.failed'));
} finally {
isReparsing.value = false;
}
} catch (e) {
console.error('自动重新解析失败:', e);
message.error(t('player.reparse.failed'));
} finally {
isReparsing.value = false;
}
}
});
} catch (e) {
console.error('解析保存的音源设置失败:', e);
});
} catch (e) {
console.error('解析保存的音源设置失败:', e);
}
}
}
}
});
);
</script>
<style lang="scss" scoped>
@@ -223,8 +241,12 @@ watch(() => playMusic.value.id, async (newId) => {
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.animate-spin {

View File

@@ -70,18 +70,22 @@
</template>
<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue';
import { secondToMinute } from '@/utils';
import { computed, onMounted, ref, watch } from 'vue';
import { allTime, nowTime, playMusic } from '@/hooks/MusicHook';
import { audioService } from '@/services/audioService';
import { usePlayerStore } from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings';
import { secondToMinute } from '@/utils';
const props = withDefaults(defineProps<{
isDark: boolean;
}>(), {
isDark: false
});
const props = withDefaults(
defineProps<{
isDark: boolean;
}>(),
{
isDark: false
}
);
const playerStore = usePlayerStore();
const settingsStore = useSettingsStore();
@@ -204,7 +208,8 @@ const applyThemeColor = (colorValue: string) => {
playBarElement.style.setProperty('--fill-color', colorValue);
// 亮度自适应处理
if (brightness > 200) { // 非常亮的颜色
if (brightness > 200) {
// 非常亮的颜色
// 深化主色以增加对比度
const darkenedColor = `rgb(${Math.max(0, r - 60)}, ${Math.max(0, g - 60)}, ${Math.max(0, b - 60)})`;
playBarElement.style.setProperty('--fill-color-alt', darkenedColor);
@@ -213,7 +218,8 @@ const applyThemeColor = (colorValue: string) => {
playBarElement.style.setProperty('--high-contrast-color', '#000000'); // 高对比度颜色
playBarElement.classList.add('light-theme-color');
playBarElement.classList.remove('dark-theme-color');
} else if (brightness < 50) { // 非常暗的颜色
} else if (brightness < 50) {
// 非常暗的颜色
// 提亮主色以增加可见性
const lightenedColor = `rgb(${Math.min(255, r + 60)}, ${Math.min(255, g + 60)}, ${Math.min(255, b + 60)})`;
playBarElement.style.setProperty('--fill-color-alt', lightenedColor);
@@ -250,11 +256,14 @@ const applyThemeColor = (colorValue: string) => {
};
// 监听主题色变化
watch(() => playerStore.playMusic.primaryColor, (newVal) => {
if (newVal) {
applyThemeColor(newVal);
watch(
() => playerStore.playMusic.primaryColor,
(newVal) => {
if (newVal) {
applyThemeColor(newVal);
}
}
});
);
onMounted(() => {
if (playerStore.playMusic?.primaryColor) {
@@ -304,11 +313,15 @@ onMounted(() => {
/* 极亮主题色适配 */
&.light-theme-color {
.progress-fill {
box-shadow: 0 0 8px var(--fill-color-transparent), inset 0 0 0 1px rgba(0, 0, 0, 0.1);
box-shadow:
0 0 8px var(--fill-color-transparent),
inset 0 0 0 1px rgba(0, 0, 0, 0.1);
}
.control-btn.play-btn {
box-shadow: 0 3px 8px var(--fill-color-transparent), 0 1px 2px rgba(0, 0, 0, 0.3);
box-shadow:
0 3px 8px var(--fill-color-transparent),
0 1px 2px rgba(0, 0, 0, 0.3);
color: var(--text-on-fill);
}
@@ -320,14 +333,18 @@ onMounted(() => {
/* 极暗主题色适配 */
&.dark-theme-color {
.progress-fill {
box-shadow: 0 0 10px var(--fill-color-transparent), inset 0 0 0 1px rgba(255, 255, 255, 0.2);
box-shadow:
0 0 10px var(--fill-color-transparent),
inset 0 0 0 1px rgba(255, 255, 255, 0.2);
}
.control-btn.play-btn {
box-shadow: 0 3px 12px var(--fill-color-transparent), 0 0 0 1px rgba(255, 255, 255, 0.2);
box-shadow:
0 3px 12px var(--fill-color-transparent),
0 0 0 1px rgba(255, 255, 255, 0.2);
.iconfont {
text-shadow: 0 1px 3px rgba(0,0,0,0.5);
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}
}
@@ -359,10 +376,11 @@ onMounted(() => {
}
&:hover {
.progress-track{
.progress-track {
background-color: var(--track-color-hover);
}
.progress-track, .progress-fill {
.progress-track,
.progress-fill {
@apply h-full;
}
@@ -394,7 +412,8 @@ onMounted(() => {
.controls-section {
@apply flex items-center justify-between mb-4;
.left-controls, .right-controls {
.left-controls,
.right-controls {
@apply flex items-center;
}
@@ -458,7 +477,9 @@ onMounted(() => {
.iconfont {
@apply cursor-pointer text-base;
transition: transform 0.2s ease, color 0.2s ease;
transition:
transform 0.2s ease,
color 0.2s ease;
&:hover {
transform: scale(1.1);
@@ -487,7 +508,9 @@ onMounted(() => {
.n-slider-handle {
@apply opacity-0 transition-opacity duration-200;
background: white;
box-shadow: 0 0 6px var(--fill-color-transparent), 0 0 0 1px var(--high-contrast-color);
box-shadow:
0 0 6px var(--fill-color-transparent),
0 0 0 1px var(--high-contrast-color);
border: 2px solid var(--fill-color);
}

View File

@@ -9,7 +9,9 @@
</template>
<template v-else-if="timerType === 'songs'">
<div class="timer-value">{{ remainingSongs }}</div>
<div class="timer-label">{{ t('player.sleepTimer.songsRemaining', { count: remainingSongs }) }}</div>
<div class="timer-label">
{{ t('player.sleepTimer.songsRemaining', { count: remainingSongs }) }}
</div>
</template>
<template v-else-if="timerType === 'end'">
<div class="timer-value">{{ t('player.sleepTimer.activeUntilEnd') }}</div>
@@ -108,9 +110,10 @@
</template>
<script lang="ts" setup>
import { computed, ref, onMounted, onUnmounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { usePlayerStore } from '@/store/modules/player';
const { t } = useI18n();
@@ -244,7 +247,9 @@ onUnmounted(() => {
.timer-status {
@apply flex flex-col items-center justify-center p-8 mb-5 w-full rounded-2xl dark:bg-gray-800 dark:bg-opacity-40 dark:shadow-gray-900/20;
background-color: rgba(255, 255, 255, 0.5);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(255, 255, 255, 0.1);
box-shadow:
0 1px 3px rgba(0, 0, 0, 0.05),
0 0 0 1px rgba(255, 255, 255, 0.1);
transition: all 0.3s ease;
// 定时值显示
@@ -292,15 +297,19 @@ onUnmounted(() => {
}
// 时间/歌曲选项容器
.time-options, .songs-options {
.time-options,
.songs-options {
@apply flex flex-wrap gap-2;
// 选项按钮共享样式
.time-option-btn, .songs-option-btn {
.time-option-btn,
.songs-option-btn {
@apply px-4 py-2 rounded-full text-gray-800 dark:text-gray-200 transition-all duration-200;
background-color: rgba(255, 255, 255, 0.5);
@apply dark:bg-gray-800 dark:bg-opacity-40 hover:bg-white dark:hover:bg-gray-700;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05), 0 0 0 1px rgba(255, 255, 255, 0.1);
box-shadow:
0 1px 2px rgba(0, 0, 0, 0.05),
0 0 0 1px rgba(255, 255, 255, 0.1);
@apply dark:shadow-gray-900/20;
&:hover {
@@ -313,16 +322,19 @@ onUnmounted(() => {
}
// 自定义输入区域
.custom-time, .custom-songs {
.custom-time,
.custom-songs {
@apply flex items-center space-x-2 mt-4 w-full;
// 输入框
.custom-time-input, .custom-songs-input {
.custom-time-input,
.custom-songs-input {
@apply flex-1;
}
// 设置按钮
.custom-time-btn, .custom-songs-btn {
.custom-time-btn,
.custom-songs-btn {
@apply py-2 px-4 rounded-full transition-all duration-200;
}
}

View File

@@ -9,8 +9,9 @@
</template>
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import { usePlayerStore } from '@/store/modules/player';
const { t } = useI18n();
@@ -28,14 +29,13 @@ const checkTimerExpired = () => {
playerStore.clearSleepTimer();
}
}
}
};
// 在组件挂载时检查定时器状态
onMounted(() => {
checkTimerExpired();
});
// 倒计时显示
const formattedRemainingTime = computed(() => {
// 依赖刷新触发器强制更新
@@ -110,10 +110,9 @@ onUnmounted(() => {
</script>
<style lang="scss" scoped>
.sleep-timer-countdown {
@apply fixed top-[28px] left-1/2 transform -translate-x-1/2 -translate-y-full py-1 px-3 rounded-b-lg bg-green-500 text-white text-sm flex items-center hover:scale-110 transition-all cursor-pointer;
box-shadow: 0 2px 10px rgba(0,0,0,0.15);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
z-index: 9998;
min-width: 80px;
text-align: center;

View File

@@ -34,7 +34,7 @@
</template>
<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue';
import { defineEmits, defineProps, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
const props = defineProps({

View File

@@ -34,7 +34,10 @@
</div>
<!-- GD音乐台设置 -->
<div v-if="selectedSources.includes('gdmusic')" class="mt-4 border-t pt-4 border-gray-200 dark:border-gray-700">
<div
v-if="selectedSources.includes('gdmusic')"
class="mt-4 border-t pt-4 border-gray-200 dark:border-gray-700"
>
<h3 class="text-base font-medium mb-2">GD音乐台(music.gdstudio.xyz)设置</h3>
<p class="text-sm text-gray-500 dark:text-gray-400 mb-2">
GD音乐台将自动尝试多个音乐平台进行解析无需额外配置优先级高于其他解析方式但是请求可能较慢感谢music.gdstudio.xyz
@@ -45,8 +48,9 @@
</template>
<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue';
import { defineEmits, defineProps, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { type Platform } from '@/types/music';
const props = defineProps({
@@ -102,9 +106,8 @@ watch(
const handleConfirm = () => {
// 确保至少选择一个音源
const defaultPlatforms = ['migu', 'kugou', 'pyncmd', 'bilibili'];
const valuesToEmit = selectedSources.value.length > 0
? [...new Set(selectedSources.value)]
: defaultPlatforms;
const valuesToEmit =
selectedSources.value.length > 0 ? [...new Set(selectedSources.value)] : defaultPlatforms;
emit('update:sources', valuesToEmit);
visible.value = false;

View File

@@ -46,10 +46,10 @@
</template>
<script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from 'naive-ui';
import type { FormRules } from 'naive-ui';
import { useMessage } from 'naive-ui';
import { defineEmits, defineProps, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
const props = defineProps({
show: {
@@ -92,7 +92,8 @@ const proxyRules: FormRules = {
validator: (_rule, value) => {
if (!value) return false;
// 简单的IP或域名验证
const ipRegex = /^(\d{1,3}\.){3}\d{1,3}$|^localhost$|^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/;
const ipRegex =
/^(\d{1,3}\.){3}\d{1,3}$|^localhost$|^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/;
return ipRegex.test(value);
}
},
@@ -142,6 +143,7 @@ const handleProxyConfirm = async () => {
visible.value = false;
message.success(t('settings.network.messages.proxySuccess'));
} catch (err) {
console.error('代理设置验证失败:', err);
message.error(t('settings.network.messages.proxyError'));
}
};

View File

@@ -24,8 +24,15 @@
<n-form-item :label="t('settings.remoteControl.allowedIps')">
<div class="allowed-ips-container">
<div v-for="(_, index) in remoteControlConfig.allowedIps" :key="index" class="ip-item">
<n-input v-model:value="remoteControlConfig.allowedIps[index]" :disabled="!remoteControlConfig.enabled" />
<div
v-for="(_, index) in remoteControlConfig.allowedIps"
:key="index"
class="ip-item"
>
<n-input
v-model:value="remoteControlConfig.allowedIps[index]"
:disabled="!remoteControlConfig.enabled"
/>
<n-button
quaternary
circle
@@ -57,11 +64,7 @@
<n-form-item>
<n-space>
<n-button
type="primary"
:disabled="!remoteControlConfig.enabled"
@click="saveConfig"
>
<n-button type="primary" :disabled="!remoteControlConfig.enabled" @click="saveConfig">
{{ t('common.save') }}
</n-button>
<n-button @click="resetConfig">
@@ -78,15 +81,11 @@
</template>
<p>{{ t('settings.remoteControl.accessInfo') }}</p>
<div class="access-url">
<n-tag type="success">
http://localhost:{{ remoteControlConfig.port }}/
</n-tag>
<n-tag type="success"> http://localhost:{{ remoteControlConfig.port }}/ </n-tag>
</div>
<div v-if="localIpAddresses.length" class="local-ips">
<div v-for="ip in localIpAddresses" :key="ip" class="ip-address">
<n-tag type="info">
http://{{ ip }}:{{ remoteControlConfig.port }}/
</n-tag>
<n-tag type="info"> http://{{ ip }}:{{ remoteControlConfig.port }}/ </n-tag>
</div>
</div>
</n-alert>
@@ -99,10 +98,10 @@
</template>
<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { useMessage } from 'naive-ui';
import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from 'naive-ui';
import { cloneDeep } from 'lodash';
const { t } = useI18n();
const message = useMessage();
@@ -111,10 +110,10 @@ const message = useMessage();
const visible = defineModel('visible', { default: false });
// 默认配置
const defaultConfig:{
enabled: boolean,
port: number,
allowedIps: string[]
const defaultConfig: {
enabled: boolean;
port: number;
allowedIps: string[];
} = {
enabled: false,
port: 31888,
@@ -122,7 +121,7 @@ const defaultConfig:{
};
// 远程控制配置
const remoteControlConfig = ref({...defaultConfig});
const remoteControlConfig = ref({ ...defaultConfig });
// 本地IP地址列表
const localIpAddresses = ref<string[]>([]);
@@ -149,10 +148,15 @@ const removeIp = (index: number) => {
// 保存配置
const saveConfig = () => {
// 过滤空IP
remoteControlConfig.value.allowedIps = remoteControlConfig.value.allowedIps.filter(ip => ip.trim() !== '');
remoteControlConfig.value.allowedIps = remoteControlConfig.value.allowedIps.filter(
(ip) => ip.trim() !== ''
);
if (window.electron) {
window.electron.ipcRenderer.send('update-remote-control-config', cloneDeep(remoteControlConfig.value));
window.electron.ipcRenderer.send(
'update-remote-control-config',
cloneDeep(remoteControlConfig.value)
);
message.success(t('settings.remoteControl.saveSuccess'));
}
};

View File

@@ -44,7 +44,6 @@ export const SEARCH_TYPES = [
}
];
export const SEARCH_TYPE = {
MUSIC: 1, // 单曲
ALBUM: 10, // 专辑

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ref } from 'vue';
// 定义表配置的泛型接口

View File

@@ -1,32 +1,59 @@
import { cloneDeep } from 'lodash';
import { createDiscreteApi } from 'naive-ui';
import { computed, nextTick, onUnmounted, ref, watch } from 'vue';
import { computed, type ComputedRef,nextTick, onUnmounted, ref, watch } from 'vue';
import { getBilibiliAudioUrl } from '@/api/bilibili';
import useIndexedDB from '@/hooks/IndexDBHook';
import { audioService } from '@/services/audioService';
import pinia, { usePlayerStore } from '@/store';
import type { usePlayerStore } from '@/store';
import { getSongUrl } from '@/store/modules/player';
import type { Artist, ILyricText, SongResult } from '@/type/music';
import { isElectron } from '@/utils';
import { getTextColors } from '@/utils/linearColor';
import { getSongUrl } from '@/store/modules/player';
const windowData = window as any;
const playerStore = usePlayerStore(pinia);
// 全局 playerStore 引用,通过 initMusicHook 函数注入
let playerStore: ReturnType<typeof usePlayerStore> | null = null;
// 初始化函数,接受 store 实例
export const initMusicHook = (store: ReturnType<typeof usePlayerStore>) => {
playerStore = store;
// 创建 computed 属性
playMusic = computed(() => getPlayerStore().playMusic as SongResult);
artistList = computed(
() => (getPlayerStore().playMusic.ar || getPlayerStore().playMusic?.song?.artists) as Artist[]
);
// 在 store 注入后初始化需要 store 的功能
setupKeyboardListeners();
initProgressAnimation();
setupMusicWatchers();
setupCorrectionTimeWatcher();
setupPlayStateWatcher();
};
// 获取 playerStore 的辅助函数
const getPlayerStore = () => {
if (!playerStore) {
throw new Error('MusicHook not initialized. Call initMusicHook first.');
}
return playerStore;
};
export const lrcArray = ref<ILyricText[]>([]); // 歌词数组
export const lrcTimeArray = ref<number[]>([]); // 歌词时间数组
export const nowTime = ref(0); // 当前播放时间
export const allTime = ref(0); // 总播放时间
export const nowIndex = ref(0); // 当前播放歌词
export const currentLrcProgress = ref(0); // 来存储当前歌词的进度
export const playMusic = computed(() => playerStore.playMusic as SongResult); // 当前播放歌曲
export const sound = ref<Howl | null>(audioService.getCurrentSound());
export const isLyricWindowOpen = ref(false); // 新增状态
export const textColors = ref<any>(getTextColors());
export const artistList = computed(
() => (playerStore.playMusic.ar || playerStore.playMusic?.song?.artists) as Artist[]
);
// 这些 computed 属性需要在初始化后创建
export let playMusic: ComputedRef<SongResult>;
export let artistList: ComputedRef<Artist[]>;
export const musicDB = await useIndexedDB('musicDB', [
{ name: 'music', keyPath: 'id' },
@@ -34,25 +61,29 @@ export const musicDB = await useIndexedDB('musicDB', [
{ name: 'api_cache', keyPath: 'id' }
]);
document.onkeyup = (e) => {
// 检查事件目标是否是输入框元素
const target = e.target as HTMLElement;
if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
return;
}
// 键盘事件处理器,在初始化后设置
const setupKeyboardListeners = () => {
document.onkeyup = (e) => {
// 检查事件目标是否是输入框元素
const target = e.target as HTMLElement;
if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA') {
return;
}
switch (e.code) {
case 'Space':
if (playerStore.play) {
playerStore.setPlayMusic(false);
audioService.getCurrentSound()?.pause();
} else {
playerStore.setPlayMusic(true);
audioService.getCurrentSound()?.play();
}
break;
default:
}
const store = getPlayerStore();
switch (e.code) {
case 'Space':
if (store.play) {
store.setPlayMusic(false);
audioService.getCurrentSound()?.pause();
} else {
store.setPlayMusic(true);
audioService.getCurrentSound()?.play();
}
break;
default:
}
};
};
const { message } = createDiscreteApi(['message']);
@@ -72,7 +103,7 @@ const stopProgressAnimation = () => {
// 全局更新函数
const updateProgress = () => {
if (!playerStore.play) {
if (!getPlayerStore().play) {
stopProgressAnimation();
return;
}
@@ -120,11 +151,11 @@ const updateProgress = () => {
Math.floor(currentTime) !== Math.floor(lastSavedTime.value)
) {
lastSavedTime.value = currentTime;
if (playerStore.playMusic && playerStore.playMusic.id) {
if (getPlayerStore().playMusic && getPlayerStore().playMusic.id) {
localStorage.setItem(
'playProgress',
JSON.stringify({
songId: playerStore.playMusic.id,
songId: getPlayerStore().playMusic.id,
progress: currentTime
})
);
@@ -175,7 +206,7 @@ const initProgressAnimation = () => {
let debounceTimer: any = null;
watch(
() => playerStore.play,
() => getPlayerStore().play,
(newIsPlaying) => {
console.log('播放状态变化:', newIsPlaying);
@@ -217,7 +248,7 @@ const initProgressAnimation = () => {
// 监听当前歌词索引变化
watch(nowIndex, () => {
currentLrcProgress.value = 0;
if (playerStore.play) {
if (getPlayerStore().play) {
startProgressAnimation();
}
});
@@ -225,45 +256,45 @@ const initProgressAnimation = () => {
// 监听音频对象变化
watch(sound, (newSound) => {
console.log('sound 对象变化:', !!newSound);
if (newSound && playerStore.play) {
if (newSound && getPlayerStore().play) {
startProgressAnimation();
}
});
};
// 初始化进度动画
initProgressAnimation();
// 设置音乐相关的监听器
const setupMusicWatchers = () => {
const store = getPlayerStore();
// 移除对 playerStore.playMusicUrl 的监听,因为播放逻辑已经在 player.ts 中处理
// 保留 watch 对 playerStore.playMusic 的监听以更新歌词数据
// 监听 playerStore.playMusic 的变化以更新歌词数据
watch(
() => store.playMusic,
() => {
nextTick(async () => {
console.log('歌曲切换,更新歌词数据');
// 更新歌词数据
lrcArray.value = playMusic.value.lyric?.lrcArray || [];
lrcTimeArray.value = playMusic.value.lyric?.lrcTimeArray || [];
watch(
() => playerStore.playMusic,
() => {
nextTick(async () => {
console.log('歌曲切换,更新歌词数据');
// 更新歌词数据
lrcArray.value = playMusic.value.lyric?.lrcArray || [];
lrcTimeArray.value = playMusic.value.lyric?.lrcTimeArray || [];
// 当歌词数据更新时,如果歌词窗口打开,则发送数据
if (isElectron && isLyricWindowOpen.value) {
console.log('歌词窗口已打开,同步最新歌词数据');
// 不管歌词数组是否为空,都发送最新数据
sendLyricToWin();
// 再次延迟发送,确保歌词窗口已完全加载
setTimeout(() => {
// 当歌词数据更新时,如果歌词窗口打开,则发送数据
if (isElectron && isLyricWindowOpen.value) {
console.log('歌词窗口已打开,同步最新歌词数据');
// 不管歌词数组是否为空,都发送最新数据
sendLyricToWin();
}, 500);
}
});
},
{
deep: true,
immediate: true
}
);
// 再次延迟发送,确保歌词窗口已完全加载
setTimeout(() => {
sendLyricToWin();
}, 500);
}
});
},
{
deep: true,
immediate: true
}
);
};
const setupAudioListeners = () => {
let interval: any = null;
@@ -331,9 +362,9 @@ const setupAudioListeners = () => {
// 监听播放
audioService.on('play', () => {
playerStore.setPlayMusic(true);
getPlayerStore().setPlayMusic(true);
if (isElectron) {
window.api.sendSong(cloneDeep(playerStore.playMusic));
window.api.sendSong(cloneDeep(getPlayerStore().playMusic));
}
clearInterval();
interval = window.setInterval(() => {
@@ -383,7 +414,7 @@ const setupAudioListeners = () => {
// 监听暂停
audioService.on('pause', () => {
console.log('音频暂停事件触发');
playerStore.setPlayMusic(false);
getPlayerStore().setPlayMusic(false);
clearInterval();
if (isElectron && isLyricWindowOpen.value) {
sendLyricToWin();
@@ -400,17 +431,17 @@ const setupAudioListeners = () => {
}
// 重新播放当前歌曲
if (playerStore.playMusicUrl && playMusic.value) {
const newSound = await audioService.play(playerStore.playMusicUrl, playMusic.value);
if (getPlayerStore().playMusicUrl && playMusic.value) {
const newSound = await audioService.play(getPlayerStore().playMusicUrl, playMusic.value);
sound.value = newSound as Howl;
setupAudioListeners();
} else {
console.error('No music URL or playMusic data available');
playerStore.nextPlay();
getPlayerStore().nextPlay();
}
} catch (error) {
console.error('Error replaying song:', error);
playerStore.nextPlay();
getPlayerStore().nextPlay();
}
};
@@ -419,36 +450,36 @@ const setupAudioListeners = () => {
console.log('音频播放结束事件触发');
clearInterval();
if (playerStore.playMode === 1) {
if (getPlayerStore().playMode === 1) {
// 单曲循环模式
if (sound.value) {
replayMusic();
}
} else if (playerStore.playMode === 2) {
} else if (getPlayerStore().playMode === 2) {
// 随机播放模式
if (playerStore.playList.length <= 1) {
if (getPlayerStore().playList.length <= 1) {
replayMusic();
} else {
let randomIndex;
do {
randomIndex = Math.floor(Math.random() * playerStore.playList.length);
} while (randomIndex === playerStore.playListIndex && playerStore.playList.length > 1);
playerStore.playListIndex = randomIndex;
playerStore.setPlay(playerStore.playList[randomIndex]);
randomIndex = Math.floor(Math.random() * getPlayerStore().playList.length);
} while (randomIndex === getPlayerStore().playListIndex && getPlayerStore().playList.length > 1);
getPlayerStore().playListIndex = randomIndex;
getPlayerStore().setPlay(getPlayerStore().playList[randomIndex]);
}
} else {
// 列表循环模式
playerStore.nextPlay();
getPlayerStore().nextPlay();
}
});
audioService.on('previoustrack', () => {
playerStore.prevPlay();
getPlayerStore().prevPlay();
});
audioService.on('nexttrack', () => {
playerStore.nextPlay();
getPlayerStore().nextPlay();
});
return clearInterval;
@@ -464,11 +495,11 @@ export const pause = () => {
try {
// 保存当前播放进度
const currentTime = currentSound.seek() as number;
if (playerStore.playMusic && playerStore.playMusic.id) {
if (getPlayerStore().playMusic && getPlayerStore().playMusic.id) {
localStorage.setItem(
'playProgress',
JSON.stringify({
songId: playerStore.playMusic.id,
songId: getPlayerStore().playMusic.id,
progress: currentTime
})
);
@@ -503,15 +534,18 @@ loadCorrectionMap();
// 歌词矫正时间,当前歌曲
export const correctionTime = ref(0);
// 切歌时自动读取矫正时间
watch(
() => playMusic.value?.id,
(id) => {
if (!id) return;
correctionTime.value = correctionTimeMap.value[id] ?? 0;
},
{ immediate: true }
);
// 设置歌词矫正时间的监听器
const setupCorrectionTimeWatcher = () => {
// 切歌时自动读取矫正时间
watch(
() => playMusic.value?.id,
(id) => {
if (!id) return;
correctionTime.value = correctionTimeMap.value[id] ?? 0;
},
{ immediate: true }
);
};
/**
* 调整歌词矫正时间(每首歌独立)
@@ -557,7 +591,7 @@ const currentLrcTiming = computed(() => {
export const getLrcStyle = (index: number) => {
const currentTime = nowTime.value + correctionTime.value;
const start = lrcTimeArray.value[index];
const end = lrcTimeArray.value[index + 1] ?? (start + 1);
const end = lrcTimeArray.value[index + 1] ?? start + 1;
if (currentTime >= start && currentTime < end) {
// 当前句,显示进度
@@ -638,7 +672,7 @@ export const sendLyricToWin = () => {
nowTime: nowTime.value,
startCurrentTime: lrcTimeArray.value[nowIndex] || 0,
nextTime: lrcTimeArray.value[nowIndex + 1] || 0,
isPlay: playerStore.play,
isPlay: getPlayerStore().play,
lrcArray: lrcArray.value,
lrcTimeArray: lrcTimeArray.value,
allTime: allTime.value,
@@ -657,7 +691,7 @@ export const sendLyricToWin = () => {
nowTime: nowTime.value,
startCurrentTime: 0,
nextTime: 0,
isPlay: playerStore.play,
isPlay: getPlayerStore().play,
lrcArray: [{ text: '当前歌曲暂无歌词', trText: '' }],
lrcTimeArray: [0],
allTime: allTime.value,
@@ -682,14 +716,14 @@ const startLyricSync = () => {
// 每秒同步一次歌词数据
lyricSyncInterval = setInterval(() => {
if (isElectron && isLyricWindowOpen.value && playerStore.play && playMusic.value?.id) {
if (isElectron && isLyricWindowOpen.value && getPlayerStore().play && playMusic.value?.id) {
// 发送当前播放进度的更新
try {
const updateData = {
type: 'update',
nowIndex: getLrcIndex(nowTime.value),
nowTime: nowTime.value,
isPlay: playerStore.play
isPlay: getPlayerStore().play
};
window.api.sendLyric(JSON.stringify(updateData));
} catch (error) {
@@ -735,7 +769,7 @@ export const openLyric = () => {
nowTime: nowTime.value,
startCurrentTime: 0,
nextTime: 0,
isPlay: playerStore.play,
isPlay: getPlayerStore().play,
lrcArray: [{ text: '加载歌词中...', trText: '' }],
lrcTimeArray: [0],
allTime: allTime.value,
@@ -771,25 +805,28 @@ export const closeLyric = () => {
stopLyricSync();
};
// 在组件挂载时设置播放状态监听
watch(
() => playerStore.play,
(isPlaying) => {
// 如果歌词窗口打开,根据播放状态控制同步
if (isElectron && isLyricWindowOpen.value) {
if (isPlaying) {
startLyricSync();
} else {
// 如果暂停播放,发送一次暂停状态的更新
const pauseData = {
type: 'update',
isPlay: false
};
window.api.sendLyric(JSON.stringify(pauseData));
// 设置播放状态监听
const setupPlayStateWatcher = () => {
// 在组件挂载时设置对播放状态的监听
watch(
() => getPlayerStore().play,
(isPlaying) => {
// 如果歌词窗口打开,根据播放状态控制同步
if (isElectron && isLyricWindowOpen.value) {
if (isPlaying) {
startLyricSync();
} else {
// 如果暂停播放,发送一次暂停状态的更新
const pauseData = {
type: 'update',
isPlay: false
};
window.api.sendLyric(JSON.stringify(pauseData));
}
}
}
}
);
);
};
// 在组件卸载时清理资源
onUnmounted(() => {
@@ -801,20 +838,20 @@ if (isElectron) {
windowData.electron.ipcRenderer.on('lyric-control-back', (_, command: string) => {
switch (command) {
case 'playpause':
if (playerStore.play) {
playerStore.setPlayMusic(false);
if (getPlayerStore().play) {
getPlayerStore().setPlayMusic(false);
audioService.getCurrentSound()?.pause();
} else {
playerStore.setPlayMusic(true);
getPlayerStore().setPlayMusic(true);
audioService.getCurrentSound()?.play();
}
break;
case 'prev':
playerStore.prevPlay();
getPlayerStore().prevPlay();
break;
case 'next':
playerStore.nextPlay();
getPlayerStore().nextPlay();
break;
case 'close':
isLyricWindowOpen.value = false; // 确保状态更新
@@ -830,7 +867,7 @@ if (isElectron) {
export const initAudioListeners = async () => {
try {
// 确保有正在播放的音乐
if (!playerStore.playMusic || !playerStore.playMusic.id) {
if (!getPlayerStore().playMusic || !getPlayerStore().playMusic.id) {
console.log('没有正在播放的音乐,跳过音频监听器初始化');
return;
}
@@ -905,7 +942,7 @@ audioService.on('url_expired', async (expiredTrack) => {
// 更新存储
(expiredTrack as any).playMusicUrl = newUrl;
playerStore.playMusicUrl = newUrl;
getPlayerStore().playMusicUrl = newUrl;
// 重新播放并设置进度
const newSound = await audioService.play(newUrl, expiredTrack);
@@ -919,9 +956,9 @@ audioService.on('url_expired', async (expiredTrack) => {
}
// 如果之前是播放状态,继续播放
if (playerStore.play) {
if (getPlayerStore().play) {
newSound.play();
playerStore.setIsPlay(true);
getPlayerStore().setIsPlay(true);
}
message.success('已自动恢复播放');
@@ -933,7 +970,6 @@ audioService.on('url_expired', async (expiredTrack) => {
// 处理网易云音乐重新获取URL
console.log('重新获取网易云音乐URL');
try {
const newUrl = await getSongUrl(expiredTrack.id, expiredTrack as any);
if (newUrl) {
@@ -941,7 +977,7 @@ audioService.on('url_expired', async (expiredTrack) => {
// 更新存储
(expiredTrack as any).playMusicUrl = newUrl;
playerStore.playMusicUrl = newUrl;
getPlayerStore().playMusicUrl = newUrl;
// 重新播放并设置进度
const newSound = await audioService.play(newUrl, expiredTrack);
@@ -955,9 +991,9 @@ audioService.on('url_expired', async (expiredTrack) => {
}
// 如果之前是播放状态,继续播放
if (playerStore.play) {
if (getPlayerStore().play) {
newSound.play();
playerStore.setIsPlay(true);
getPlayerStore().setIsPlay(true);
}
message.success('已自动恢复播放');

View File

@@ -1,7 +1,7 @@
import { cloneDeep } from 'lodash';
import { useMessage } from 'naive-ui';
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from 'naive-ui';
import { getSongUrl } from '@/store/modules/player';
import type { SongResult } from '@/type/music';
@@ -92,10 +92,12 @@ const createDownloadManager = () => {
notifiedDownloads.add(data.filename);
// 显示失败通知
message.error(t('songItem.message.downloadFailed', {
filename: data.filename,
error: data.error || '未知错误'
}));
message.error(
t('songItem.message.downloadFailed', {
filename: data.filename,
error: data.error || '未知错误'
})
);
// 从活动下载移除
activeDownloads.delete(data.filename);

View File

@@ -1,17 +1,16 @@
import { useDialog, useMessage } from 'naive-ui';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { usePlayerStore } from '@/store';
import type { SongResult } from '@/type/music';
import { computed, ref } from 'vue';
import { getImgUrl } from '@/utils';
import { getImageBackground } from '@/utils/linearColor';
import { useMessage, useDialog } from 'naive-ui';
import { useI18n } from 'vue-i18n';
import { useDownload } from './useDownload';
import { useArtist } from './useArtist';
export function useSongItem(props: {
item: SongResult;
canRemove?: boolean;
}) {
import { useArtist } from './useArtist';
import { useDownload } from './useDownload';
export function useSongItem(props: { item: SongResult; canRemove?: boolean }) {
const { t } = useI18n();
const playerStore = usePlayerStore();
const message = useMessage();
@@ -35,12 +34,14 @@ export function useSongItem(props: {
// 收藏与不喜欢状态
const isFavorite = computed(() => {
const numericId = typeof props.item.id === 'string' ? parseInt(props.item.id, 10) : props.item.id;
const numericId =
typeof props.item.id === 'string' ? parseInt(props.item.id, 10) : props.item.id;
return playerStore.favoriteList.includes(numericId);
});
const isDislike = computed(() => {
const numericId = typeof props.item.id === 'string' ? parseInt(props.item.id, 10) : props.item.id;
const numericId =
typeof props.item.id === 'string' ? parseInt(props.item.id, 10) : props.item.id;
return playerStore.dislikeList.includes(numericId);
});
@@ -75,7 +76,8 @@ export function useSongItem(props: {
// 切换收藏状态
const toggleFavorite = async (e: Event) => {
e && e.stopPropagation();
const numericId = typeof props.item.id === 'string' ? parseInt(props.item.id, 10) : props.item.id;
const numericId =
typeof props.item.id === 'string' ? parseInt(props.item.id, 10) : props.item.id;
if (isFavorite.value) {
playerStore.removeFromFavorite(numericId);

View File

@@ -9,7 +9,11 @@
<!-- 搜索栏 -->
<search-bar />
<!-- 主页面路由 -->
<div class="main-content" :native-scrollbar="false" :class="{'mobile-content': !shouldShowMobileMenu}">
<div
class="main-content"
:native-scrollbar="false"
:class="{ 'mobile-content': !shouldShowMobileMenu }"
>
<router-view
v-slot="{ Component }"
class="main-page"
@@ -41,7 +45,7 @@
<install-app-modal v-if="!isElectron"></install-app-modal>
<update-modal v-if="isElectron" />
<playlist-drawer v-model="showPlaylistDrawer" :song-id="currentSongId" />
<SleepTimerTop v-if="!isMobile"/>
<sleep-timer-top v-if="!isMobile" />
<!-- 下载管理抽屉 -->
<download-drawer
v-if="
@@ -64,13 +68,13 @@ import DownloadDrawer from '@/components/common/DownloadDrawer.vue';
import InstallAppModal from '@/components/common/InstallAppModal.vue';
import PlayBottom from '@/components/common/PlayBottom.vue';
import UpdateModal from '@/components/common/UpdateModal.vue';
import SleepTimerTop from '@/components/player/SleepTimerTop.vue';
import homeRouter from '@/router/home';
import otherRouter from '@/router/other';
import { useMenuStore } from '@/store/modules/menu';
import { usePlayerStore } from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings';
import { isElectron, isMobile } from '@/utils';
import SleepTimerTop from '@/components/player/SleepTimerTop.vue';
const keepAliveInclude = computed(() => {
const allRoutes = [...homeRouter, ...otherRouter];
@@ -92,7 +96,9 @@ const PlayBar = defineAsyncComponent(() => import('@/components/player/PlayBar.v
const MobilePlayBar = defineAsyncComponent(() => import('@/components/player/MobilePlayBar.vue'));
const SearchBar = defineAsyncComponent(() => import('./components/SearchBar.vue'));
const TitleBar = defineAsyncComponent(() => import('./components/TitleBar.vue'));
const PlayingListDrawer = defineAsyncComponent(() => import('@/components/player/PlayingListDrawer.vue'));
const PlayingListDrawer = defineAsyncComponent(
() => import('@/components/player/PlayingListDrawer.vue')
);
const PlaylistDrawer = defineAsyncComponent(() => import('@/components/common/PlaylistDrawer.vue'));
const playerStore = usePlayerStore();

View File

@@ -12,8 +12,17 @@
<n-tooltip :delay="200" :disabled="isText || isMobile" placement="bottom">
<template #trigger>
<router-link class="app-menu-item-link" :to="item.path">
<i class="iconfont app-menu-item-icon" :style="iconStyle(index)" :class="item.meta.icon"></i>
<span v-if="isText" class="app-menu-item-text ml-3" :class="isChecked(index) ? 'text-green-500' : ''">{{ t(item.meta.title) }}</span>
<i
class="iconfont app-menu-item-icon"
:style="iconStyle(index)"
:class="item.meta.icon"
></i>
<span
v-if="isText"
class="app-menu-item-text ml-3"
:class="isChecked(index) ? 'text-green-500' : ''"
>{{ t(item.meta.title) }}</span
>
</router-link>
</template>
<div v-if="!isText">{{ t(item.meta.title) }}</div>
@@ -25,9 +34,9 @@
</template>
<script lang="ts" setup>
import { useRoute } from 'vue-router';
import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import icon from '@/assets/icon.png';
import { isMobile } from '@/utils';

View File

@@ -19,7 +19,7 @@
<n-dropdown trigger="hover" :options="searchTypeOptions" @select="selectSearchType">
<div class="w-20 px-3 flex justify-between items-center">
<div>
{{ searchTypeOptions.find(item => item.key === searchStore.searchType)?.label }}
{{ searchTypeOptions.find((item) => item.key === searchStore.searchType)?.label }}
</div>
<i class="iconfont icon-xiasanjiaoxing"></i>
</div>
@@ -64,16 +64,18 @@
</div>
<div class="menu-item" v-if="isElectron">
<i class="iconfont ri-zoom-in-line"></i>
<span>{{ t('comp.searchBar.zoom')}}</span>
<span>{{ t('comp.searchBar.zoom') }}</span>
<div class="zoom-controls ml-auto">
<n-button quaternary circle size="tiny" @click="decreaseZoom">
<i class="ri-subtract-line"></i>
</n-button>
<n-tooltip trigger="hover">
<template #trigger>
<span class="zoom-value" :class="{'zoom-100': isZoom100()}" @click="resetZoom">{{ Math.round(zoomFactor * 100) }}%</span>
<span class="zoom-value" :class="{ 'zoom-100': isZoom100() }" @click="resetZoom"
>{{ Math.round(zoomFactor * 100) }}%</span
>
</template>
{{ isZoom100() ? t('comp.searchBar.zoom100'): t('comp.searchBar.resetZoom')}}
{{ isZoom100() ? t('comp.searchBar.zoom100') : t('comp.searchBar.resetZoom') }}
</n-tooltip>
<n-button quaternary circle size="tiny" @click="increaseZoom">
<i class="ri-add-line"></i>
@@ -126,13 +128,14 @@
import { computed, onMounted, ref, watch, watchEffect } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { getSearchKeyword } from '@/api/home';
import { getUserDetail } from '@/api/login';
import alipay from '@/assets/alipay.png';
import wechat from '@/assets/wechat.png';
import Coffee from '@/components/Coffee.vue';
import { useZoom } from '@/hooks/useZoom';
import { SEARCH_TYPES, USER_SET_OPTIONS } from '@/const/bar-const';
import { useZoom } from '@/hooks/useZoom';
import { useSearchStore } from '@/store/modules/search';
import { useSettingsStore } from '@/store/modules/settings';
import { useUserStore } from '@/store/modules/user';
@@ -149,14 +152,7 @@ const userSetOptions = ref(USER_SET_OPTIONS);
const { t, locale } = useI18n();
// 使用缩放hook
const {
zoomFactor,
initZoomFactor,
increaseZoom,
decreaseZoom,
resetZoom,
isZoom100
} = useZoom();
const { zoomFactor, initZoomFactor, increaseZoom, decreaseZoom, resetZoom, isZoom100 } = useZoom();
// 显示返回按钮
const showBackButton = computed(() => {
@@ -270,14 +266,14 @@ const selectSearchType = (key: number) => {
}
};
const rawSearchTypes = ref(SEARCH_TYPES)
const rawSearchTypes = ref(SEARCH_TYPES);
const searchTypeOptions = computed(() => {
// 引用 locale 以创建响应式依赖
locale.value;
return rawSearchTypes.value.map(type => ({
return rawSearchTypes.value.map((type) => ({
label: t(type.label),
key: type.key
}))
}));
});
const selectItem = async (key: string) => {

View File

@@ -1,12 +1,13 @@
import { createRouter, createWebHashHistory } from 'vue-router';
import { useUserStore } from '../store/modules/user';
import AppLayout from '@/layout/AppLayout.vue';
import MiniLayout from '@/layout/MiniLayout.vue';
import homeRouter from '@/router/home';
import otherRouter from '@/router/other';
import { useSettingsStore } from '@/store/modules/settings';
import { useUserStore } from '../store/modules/user';
function getUserId(): string | null {
const userStore = useUserStore();
return userStore.user?.userId?.toString() || null;

View File

@@ -86,6 +86,6 @@ const otherRouter = [
back: true
},
component: () => import('@/views/playlist/ImportPlaylist.vue')
},
}
];
export default otherRouter;

View File

@@ -265,7 +265,7 @@ class AudioService {
return;
}
const howl = sound as any;
// eslint-disable-next-line no-underscore-dangle
const audioNode = howl._sounds?.[0]?._node;
if (!audioNode || !(audioNode instanceof HTMLMediaElement)) {
@@ -401,10 +401,13 @@ class AudioService {
// 将锁信息存储到 localStorage仅用于调试实际不依赖此值
try {
localStorage.setItem('audioOperationLock', JSON.stringify({
id: this.operationLockId,
startTime: this.operationLockStartTime
}));
localStorage.setItem(
'audioOperationLock',
JSON.stringify({
id: this.operationLockId,
startTime: this.operationLockStartTime
})
);
} catch (error) {
console.error('存储操作锁信息失败:', error);
}
@@ -458,7 +461,12 @@ class AudioService {
}
// 播放控制相关
play(url?: string, track?: SongResult, isPlay: boolean = true, seekTime: number = 0): Promise<Howl> {
play(
url?: string,
track?: SongResult,
isPlay: boolean = true,
seekTime: number = 0
): Promise<Howl> {
// 每次调用play方法时尝试强制重置锁注意仅在页面刷新后的第一次播放时应用
if (!this.currentSound) {
console.log('首次播放请求,强制重置操作锁');
@@ -820,7 +828,7 @@ class AudioService {
// 如果状态为1表示已经加载但未完成状态为2表示正在加载
const state = (this.currentSound as any)._state;
// 如果操作锁激活也认为是加载状态
return this.operationLock || (state === 'loading' || state === 1);
return this.operationLock || state === 'loading' || state === 1;
}
// 检查音频是否真正在播放
@@ -836,7 +844,9 @@ class AudioService {
const isLoading = this.isLoading();
const contextRunning = Howler.ctx && Howler.ctx.state === 'running';
console.log(`实际播放状态检查: playing=${isPlaying}, loading=${isLoading}, contextRunning=${contextRunning}`);
console.log(
`实际播放状态检查: playing=${isPlaying}, loading=${isLoading}, contextRunning=${contextRunning}`
);
// 只有在三个条件都满足时才认为是真正在播放
return isPlaying && !isLoading && contextRunning;

View File

@@ -1,4 +1,5 @@
import { createPinia } from 'pinia';
import router from '@/router';
// 创建 pinia 实例
@@ -12,10 +13,10 @@ pinia.use(({ store }) => {
// 导出所有 store
export * from './modules/lyric';
export * from './modules/menu';
export * from './modules/music';
export * from './modules/player';
export * from './modules/search';
export * from './modules/settings';
export * from './modules/user';
export * from './modules/music';
export default pinia;

View File

@@ -1,7 +1,8 @@
import { useThrottleFn } from '@vueuse/core';
import { cloneDeep } from 'lodash';
import { createDiscreteApi } from 'naive-ui';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { useThrottleFn } from '@vueuse/core';
import i18n from '@/../i18n/renderer';
import { getBilibiliAudioUrl } from '@/api/bilibili';
@@ -9,13 +10,12 @@ import { getLikedList, getMusicLrc, getMusicUrl, getParsingMusicUrl, likeSong }
import { useMusicHistory } from '@/hooks/MusicHistoryHook';
import { audioService } from '@/services/audioService';
import type { ILyric, ILyricText, SongResult } from '@/type/music';
import { type Platform } from '@/types/music';
import { getImgUrl } from '@/utils';
import { getImageLinearBackground } from '@/utils/linearColor';
import { createDiscreteApi } from 'naive-ui';
import { useSettingsStore } from './settings';
import { useUserStore } from './user';
import { type Platform } from '@/types/music';
const musicHistory = useMusicHistory();
const { message } = createDiscreteApi(['message']);
@@ -115,14 +115,14 @@ export const getSongUrl = async (
try {
console.log(`使用自定义音源解析歌曲 ID: ${songId}`);
const res = await getParsingMusicUrl(numericId, cloneDeep(songData));
console.log('res',res)
console.log('res', res);
if (res && res.data && res.data.data && res.data.data.url) {
return res.data.data.url;
}
// 如果自定义音源解析失败,继续使用正常的获取流程
console.warn('自定义音源解析失败,使用默认音源');
} catch (error) {
console.error('error',error)
console.error('error', error);
console.error('自定义音源解析出错:', error);
}
}
@@ -149,7 +149,7 @@ export const getSongUrl = async (
url = url || data.data[0].url;
return url;
} catch (error) {
console.error('error',error)
console.error('error', error);
return null;
}
};
@@ -233,7 +233,7 @@ const getSongDetail = async (playMusic: SongResult) => {
}
playMusic.playLoading = false;
return { ...playMusic} as SongResult;
return { ...playMusic } as SongResult;
} catch (error) {
console.error('获取B站音频详情失败:', error);
playMusic.playLoading = false;
@@ -370,17 +370,17 @@ const loadLrcAsync = async (playMusic: SongResult) => {
// 定时关闭类型
export enum SleepTimerType {
NONE = 'none', // 没有定时
TIME = 'time', // 按时间定时
SONGS = 'songs', // 按歌曲数定时
PLAYLIST_END = 'end' // 播放列表播放完毕定时
NONE = 'none', // 没有定时
TIME = 'time', // 按时间定时
SONGS = 'songs', // 按歌曲数定时
PLAYLIST_END = 'end' // 播放列表播放完毕定时
}
// 定时关闭信息
export interface SleepTimerInfo {
type: SleepTimerType;
value: number; // 对于TIME类型值以分钟为单位对于SONGS类型值为歌曲数量
endTime?: number; // 何时结束仅TIME类型
value: number; // 对于TIME类型值以分钟为单位对于SONGS类型值为歌曲数量
endTime?: number; // 何时结束仅TIME类型
startSongIndex?: number; // 开始时的歌曲索引对于SONGS类型
remainingSongs?: number; // 剩余歌曲数对于SONGS类型
}
@@ -401,17 +401,19 @@ export const usePlayerStore = defineStore('player', () => {
const playListDrawerVisible = ref(false);
// 定时关闭相关状态
const sleepTimer = ref<SleepTimerInfo>(getLocalStorageItem('sleepTimer', {
type: SleepTimerType.NONE,
value: 0
}));
const sleepTimer = ref<SleepTimerInfo>(
getLocalStorageItem('sleepTimer', {
type: SleepTimerType.NONE,
value: 0
})
);
// 播放速度状态
const playbackRate = ref(parseFloat(getLocalStorageItem('playbackRate', '1.0')));
// 清空播放列表
const clearPlayAll = async () => {
audioService.pause()
audioService.pause();
setTimeout(() => {
playMusic.value = {} as SongResult;
playMusicUrl.value = '';
@@ -467,9 +469,9 @@ export const usePlayerStore = defineStore('player', () => {
const originalMusic = { ...music };
// 获取背景色
const { backgroundColor, primaryColor } =
music.backgroundColor && music.primaryColor
? music
: await getImageLinearBackground(getImgUrl(music?.picUrl, '30y30'));
music.backgroundColor && music.primaryColor
? music
: await getImageLinearBackground(getImgUrl(music?.picUrl, '30y30'));
music.backgroundColor = backgroundColor;
music.primaryColor = primaryColor;
music.playLoading = true; // 设置加载状态
@@ -491,7 +493,6 @@ export const usePlayerStore = defineStore('player', () => {
document.title = 'AlgerMusic - ' + title;
try {
// 添加到历史记录
musicHistory.addMusic(music);
@@ -564,7 +565,7 @@ export const usePlayerStore = defineStore('player', () => {
// 添加独立的播放状态检测函数
const checkPlaybackState = (song: SongResult, timeout: number = 4000) => {
if(checkPlayTime) {
if (checkPlayTime) {
clearTimeout(checkPlayTime);
}
const sound = audioService.getCurrentSound();
@@ -630,7 +631,11 @@ export const usePlayerStore = defineStore('player', () => {
}
// 如果是当前正在播放的音乐,则切换播放/暂停状态
if (playMusic.value.id === song.id && playMusic.value.playMusicUrl === song.playMusicUrl && !song.isFirstPlay) {
if (
playMusic.value.id === song.id &&
playMusic.value.playMusicUrl === song.playMusicUrl &&
!song.isFirstPlay
) {
if (play.value) {
setPlayMusic(false);
audioService.getCurrentSound()?.pause();
@@ -650,7 +655,7 @@ export const usePlayerStore = defineStore('player', () => {
return;
}
if(song.isFirstPlay) {
if (song.isFirstPlay) {
song.isFirstPlay = false;
}
// 直接调用 handlePlayMusic它会处理索引更新和播放逻辑
@@ -850,7 +855,10 @@ export const usePlayerStore = defineStore('player', () => {
console.log('歌曲已切换,检查定时器状态:', sleepTimer.value);
// 处理按歌曲数定时
if (sleepTimer.value.type === SleepTimerType.SONGS && sleepTimer.value.remainingSongs !== undefined) {
if (
sleepTimer.value.type === SleepTimerType.SONGS &&
sleepTimer.value.remainingSongs !== undefined
) {
sleepTimer.value.remainingSongs--;
console.log(`剩余歌曲数: ${sleepTimer.value.remainingSongs}`);
@@ -860,7 +868,7 @@ export const usePlayerStore = defineStore('player', () => {
if (sleepTimer.value.remainingSongs <= 0) {
// 歌曲数到达,停止播放
console.log('已播放完设定的歌曲数,停止播放');
stopPlayback()
stopPlayback();
setTimeout(() => {
stopPlayback();
}, 1000);
@@ -870,10 +878,11 @@ export const usePlayerStore = defineStore('player', () => {
// 处理播放列表结束定时
if (sleepTimer.value.type === SleepTimerType.PLAYLIST_END) {
// 检查是否到达播放列表末尾
const isLastSong = (playListIndex.value === playList.value.length - 1);
const isLastSong = playListIndex.value === playList.value.length - 1;
// 如果是列表最后一首歌且不是循环模式,则设置为在这首歌结束后停止
if (isLastSong && playMode.value !== 1) { // 1 是循环模式
if (isLastSong && playMode.value !== 1) {
// 1 是循环模式
console.log('已到达播放列表末尾,将在当前歌曲结束后停止播放');
// 转换为按歌曲数定时剩余1首
sleepTimer.value = {
@@ -888,17 +897,18 @@ export const usePlayerStore = defineStore('player', () => {
};
const _nextPlay = async () => {
try {
if (playList.value.length === 0) {
play.value = true;
return;
}
// 检查是否是播放列表的最后一首且设置了播放列表结束定时
if (playMode.value === 0 && playListIndex.value === playList.value.length - 1 &&
sleepTimer.value.type === SleepTimerType.PLAYLIST_END) {
if (
playMode.value === 0 &&
playListIndex.value === playList.value.length - 1 &&
sleepTimer.value.type === SleepTimerType.PLAYLIST_END
) {
// 已是最后一首且为顺序播放模式,触发停止
stopPlayback();
return;
@@ -958,11 +968,12 @@ export const usePlayerStore = defineStore('player', () => {
const availableIndices = Array.from(
{ length: newPlayList.length },
(_, i) => i
).filter(i => !attemptedIndices.has(i));
).filter((i) => !attemptedIndices.has(i));
if (availableIndices.length > 0) {
// 随机选择一个未尝试过的索引
nowPlayListIndex = availableIndices[Math.floor(Math.random() * availableIndices.length)];
nowPlayListIndex =
availableIndices[Math.floor(Math.random() * availableIndices.length)];
} else {
// 如果所有歌曲都尝试过了,选择下一个索引
nowPlayListIndex = (playListIndex.value + 1) % newPlayList.length;
@@ -970,9 +981,8 @@ export const usePlayerStore = defineStore('player', () => {
} else {
// 顺序播放,选择下一首
// 如果当前索引已经是最后一首,循环到第一首
nowPlayListIndex = playListIndex.value >= newPlayList.length
? 0
: playListIndex.value;
nowPlayListIndex =
playListIndex.value >= newPlayList.length ? 0 : playListIndex.value;
}
playListIndex.value = nowPlayListIndex;
@@ -1014,9 +1024,7 @@ export const usePlayerStore = defineStore('player', () => {
const nextPlay = useThrottleFn(_nextPlay, 500);
const _prevPlay = async () => {
try {
if (playList.value.length === 0) {
play.value = true;
return;
@@ -1064,7 +1072,8 @@ export const usePlayerStore = defineStore('player', () => {
playListIndex.value = 0;
} else {
// 尝试上上一首
const newPrevIndex = (playListIndex.value - 1 + newPlayList.length) % newPlayList.length;
const newPrevIndex =
(playListIndex.value - 1 + newPlayList.length) % newPlayList.length;
playListIndex.value = newPrevIndex;
}
@@ -1104,7 +1113,7 @@ export const usePlayerStore = defineStore('player', () => {
const addToFavorite = async (id: number | string) => {
// 检查是否已存在相同的ID或内容相同的B站视频
const isAlreadyInList = favoriteList.value.some(existingId =>
const isAlreadyInList = favoriteList.value.some((existingId) =>
typeof id === 'string' && id.includes('--')
? isBilibiliIdMatch(existingId, id)
: existingId === id
@@ -1120,9 +1129,11 @@ export const usePlayerStore = defineStore('player', () => {
const removeFromFavorite = async (id: number | string) => {
// 对于B站视频需要根据bvid和cid来匹配
if (typeof id === 'string' && id.includes('--')) {
favoriteList.value = favoriteList.value.filter(existingId => !isBilibiliIdMatch(existingId, id));
favoriteList.value = favoriteList.value.filter(
(existingId) => !isBilibiliIdMatch(existingId, id)
);
} else {
favoriteList.value = favoriteList.value.filter(existingId => existingId !== id);
favoriteList.value = favoriteList.value.filter((existingId) => existingId !== id);
useUserStore().user && likeSong(Number(id), false);
}
localStorage.setItem('favoriteList', JSON.stringify(favoriteList.value));
@@ -1131,12 +1142,12 @@ export const usePlayerStore = defineStore('player', () => {
const addToDislikeList = (id: number | string) => {
dislikeList.value.push(id);
localStorage.setItem('dislikeList', JSON.stringify(dislikeList.value));
}
};
const removeFromDislikeList = (id: number | string) => {
dislikeList.value = dislikeList.value.filter(existingId => existingId!== id);
dislikeList.value = dislikeList.value.filter((existingId) => existingId !== id);
localStorage.setItem('dislikeList', JSON.stringify(dislikeList.value));
}
};
const removeFromPlayList = (id: number | string) => {
const index = playList.value.findIndex((item) => item.id === id);
@@ -1184,7 +1195,10 @@ export const usePlayerStore = defineStore('player', () => {
savedPlayMusic.playMusicUrl = undefined;
}
await handlePlayMusic({ ...savedPlayMusic, isFirstPlay: true, playMusicUrl: undefined }, isPlaying);
await handlePlayMusic(
{ ...savedPlayMusic, isFirstPlay: true, playMusicUrl: undefined },
isPlaying
);
} catch (error) {
console.error('重新获取音乐链接失败:', error);
play.value = false;
@@ -1201,7 +1215,6 @@ export const usePlayerStore = defineStore('player', () => {
setTimeout(() => {
audioService.setPlaybackRate(playbackRate.value);
}, 2000);
};
const initializeFavoriteList = async () => {
@@ -1247,7 +1260,10 @@ export const usePlayerStore = defineStore('player', () => {
}
// 对于B站视频检查URL是否有效
if (playMusic.value.source === 'bilibili' && (!playMusicUrl.value || playMusicUrl.value === 'undefined')) {
if (
playMusic.value.source === 'bilibili' &&
(!playMusicUrl.value || playMusicUrl.value === 'undefined')
) {
console.log('B站视频URL无效尝试重新获取');
// 需要重新获取B站视频URL
@@ -1271,15 +1287,22 @@ export const usePlayerStore = defineStore('player', () => {
// 播放新音频,传递是否应该播放的状态
console.log('调用audioService.play播放状态:', shouldPlay);
const newSound = await audioService.play(playMusicUrl.value, playMusic.value, shouldPlay, initialPosition || 0);
const newSound = await audioService.play(
playMusicUrl.value,
playMusic.value,
shouldPlay,
initialPosition || 0
);
// 添加播放状态检测(仅当需要播放时)
if (shouldPlay) {
checkPlaybackState(playMusic.value);
}
// 发布音频就绪事件,让 MusicHook.ts 来处理设置监听器
window.dispatchEvent(new CustomEvent('audio-ready', { detail: { sound: newSound, shouldPlay } }));
// 发布音频就绪事件
window.dispatchEvent(
new CustomEvent('audio-ready', { detail: { sound: newSound, shouldPlay } })
);
// 确保状态与 localStorage 同步
localStorage.setItem('currentPlayMusic', JSON.stringify(playMusic.value));
@@ -1311,7 +1334,7 @@ export const usePlayerStore = defineStore('player', () => {
// 如果用户仍希望播放
if (userPlayIntent.value && play.value) {
// 直接重试当前歌曲,而不是切换到下一首
playAudio().catch(e => {
playAudio().catch((e) => {
console.error('重试播放失败,切换到下一首:', e);
// 只有再次失败才切换到下一首
@@ -1360,9 +1383,8 @@ export const usePlayerStore = defineStore('player', () => {
}
// 重新获取歌曲URL
const numericId = typeof currentSong.id === 'string'
? parseInt(currentSong.id, 10)
: currentSong.id;
const numericId =
typeof currentSong.id === 'string' ? parseInt(currentSong.id, 10) : currentSong.id;
console.log(`使用音源 ${sourcePlatform} 重新解析歌曲 ${numericId}`);
@@ -1379,7 +1401,7 @@ export const usePlayerStore = defineStore('player', () => {
const updatedMusic = {
...currentSong,
playMusicUrl: newUrl,
expiredAt: Date.now() + 1800000 // 半小时后过期
expiredAt: Date.now() + 1800000 // 半小时后过期
};
// 更新播放器状态并开始播放
@@ -1415,7 +1437,7 @@ export const usePlayerStore = defineStore('player', () => {
} catch (error) {
console.error('暂停播放失败:', error);
}
}
};
return {
play,

View File

@@ -4,7 +4,13 @@ import { ref } from 'vue';
import setDataDefault from '@/../main/set.json';
import { isElectron } from '@/utils';
import { applyTheme, getCurrentTheme, getSystemTheme, watchSystemTheme, ThemeType } from '@/utils/theme';
import {
applyTheme,
getCurrentTheme,
getSystemTheme,
ThemeType,
watchSystemTheme
} from '@/utils/theme';
export const useSettingsStore = defineStore('settings', () => {
const theme = ref<ThemeType>(getCurrentTheme());

View File

@@ -2,17 +2,17 @@ export interface IElectronAPI {
minimize: () => void;
maximize: () => void;
close: () => void;
dragStart: (data: string) => void;
dragStart: (_data: string) => void;
miniTray: () => void;
restart: () => void;
openLyric: () => void;
sendLyric: (data: string) => void;
unblockMusic: (id: number) => Promise<string>;
onLanguageChanged: (callback: (locale: string) => void) => void;
sendLyric: (_data: string) => void;
unblockMusic: (_id: number) => Promise<string>;
onLanguageChanged: (_callback: (_locale: string) => void) => void;
store: {
get: (key: string) => Promise<any>;
set: (key: string, value: any) => Promise<boolean>;
delete: (key: string) => Promise<boolean>;
get: (_key: string) => Promise<any>;
set: (_key: string, _value: any) => Promise<boolean>;
delete: (_key: string) => Promise<boolean>;
};
}

View File

@@ -47,7 +47,9 @@ export async function handleShortcutAction(action: string) {
// 检查是否是同一个动作的重复触发300ms内
if (lastActionInfo.action === action && now - lastActionInfo.timestamp < ACTION_DELAY) {
console.log(`[AppShortcuts] 忽略重复的 ${action} 动作,距上次仅 ${now - lastActionInfo.timestamp}ms`);
console.log(
`[AppShortcuts] 忽略重复的 ${action} 动作,距上次仅 ${now - lastActionInfo.timestamp}ms`
);
return;
}
@@ -146,7 +148,9 @@ export async function handleShortcutAction(action: string) {
// 确保在出错时也能清除超时
clearTimeout(actionTimeout);
actionTimeout = null;
console.log(`[AppShortcuts] 动作完成: ${action}, 时间戳: ${Date.now()}, 耗时: ${Date.now() - now}ms`);
console.log(
`[AppShortcuts] 动作完成: ${action}, 时间戳: ${Date.now()}, 耗时: ${Date.now() - now}ms`
);
}
}

View File

@@ -12,6 +12,7 @@ export const selectDirectory = async (message: MessageApi): Promise<string | und
return result.filePaths[0];
}
} catch (error) {
console.error('选择目录失败:', error);
message.error('选择目录失败');
}
return undefined;

View File

@@ -446,13 +446,11 @@ export const getLyricThemeColors = (): LyricThemeColor[] => {
* 根据主题获取预设颜色的实际值
*/
export const getPresetColorValue = (colorId: string, theme: 'light' | 'dark'): string => {
const color = PRESET_LYRIC_COLORS.find(c => c.id === colorId);
const color = PRESET_LYRIC_COLORS.find((c) => c.id === colorId);
if (!color) return getDefaultHighlightColor(theme);
return theme === 'dark' ? color.dark : color.light;
};
/**
* 安全加载歌词设置
*/

View File

@@ -10,11 +10,7 @@ interface ToastOptions {
showIcon?: boolean;
}
export function showShortcutToast(
message: string,
iconName = '',
options: ToastOptions = {}
) {
export function showShortcutToast(message: string, iconName = '', options: ToastOptions = {}) {
// 如果容器不存在,创建一个新的容器
if (!container) {
container = document.createElement('div');

View File

@@ -135,7 +135,7 @@ export const getLatestReleaseInfo = async (): Promise<GithubReleaseInfo | null>
'https://api.github.com/repos/algerkong/AlgerMusicPlayer/releases/latest',
// 使用代理节点
'https://music.alger.fun/package.json',
'https://music.alger.fun/package.json'
];
if (token) {

View File

@@ -51,10 +51,17 @@
<n-tooltip placement="bottom" trigger="hover">
<template #trigger>
<div class="toggle-button hover-green" @click="toggleLayout">
<i class="icon iconfont" :class="isCompactLayout ? 'ri-list-check-2' : 'ri-grid-line'"></i>
<i
class="icon iconfont"
:class="isCompactLayout ? 'ri-list-check-2' : 'ri-grid-line'"
></i>
</div>
</template>
{{ isCompactLayout ? t('comp.musicList.switchToNormal') : t('comp.musicList.switchToCompact') }}
{{
isCompactLayout
? t('comp.musicList.switchToNormal')
: t('comp.musicList.switchToCompact')
}}
</n-tooltip>
</div>
@@ -73,7 +80,10 @@
<i class="icon iconfont ri-search-line text-sm"></i>
</template>
<template #suffix>
<i class="icon iconfont ri-close-line text-sm cursor-pointer" @click="closeSearch"></i>
<i
class="icon iconfont ri-close-line text-sm cursor-pointer"
@click="closeSearch"
></i>
</template>
</n-input>
</template>
@@ -124,7 +134,11 @@
</n-virtual-list>
<div v-if="songLoading" class="loading-more">{{ t('common.loading') }}</div>
<div v-else-if="songPage.hasMore" ref="songsLoadMoreRef" class="load-more-trigger"></div>
<div
v-else-if="songPage.hasMore"
ref="songsLoadMoreRef"
class="load-more-trigger"
></div>
</div>
</div>
</n-tab-pane>
@@ -146,7 +160,11 @@
}"
/>
<div v-if="albumLoading" class="loading-more">{{ t('common.loading') }}</div>
<div v-else-if="albumPage.hasMore" ref="albumsLoadMoreRef" class="load-more-trigger"></div>
<div
v-else-if="albumPage.hasMore"
ref="albumsLoadMoreRef"
class="load-more-trigger"
></div>
</div>
</div>
</n-tab-pane>
@@ -164,11 +182,20 @@
<script setup lang="ts">
import { useDateFormat } from '@vueuse/core';
import { computed, onMounted, onUnmounted, ref, watch, nextTick, onActivated, onDeactivated } from 'vue';
import { useMessage } from 'naive-ui';
import PinyinMatch from 'pinyin-match';
import {
computed,
nextTick,
onActivated,
onDeactivated,
onMounted,
onUnmounted,
ref,
watch
} from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';
import PinyinMatch from 'pinyin-match';
import { useMessage } from 'naive-ui';
import { getArtistAlbums, getArtistDetail, getArtistTopSongs } from '@/api/artist';
import { getMusicDetail } from '@/api/music';
@@ -232,7 +259,9 @@ const getCacheKey = (id: string | number) => `artist_${id}`;
// 搜索和布局相关
const searchKeyword = ref('');
const isSearchVisible = ref(false);
const isCompactLayout = ref(isMobile.value ? false : localStorage.getItem('musicListLayout') === 'compact');
const isCompactLayout = ref(
isMobile.value ? false : localStorage.getItem('musicListLayout') === 'compact'
);
// 加载歌手信息
const loadArtistInfo = async () => {
@@ -440,10 +469,12 @@ const toggleLayout = () => {
const handlePlayAll = () => {
if (filteredSongs.value.length === 0) return;
playerStore.setPlayList(filteredSongs.value.map(song => ({
...song,
picUrl: song.al.picUrl
})));
playerStore.setPlayList(
filteredSongs.value.map((song) => ({
...song,
picUrl: song.al.picUrl
}))
);
// 开始播放第一首
playerStore.setPlay(filteredSongs.value[0]);
@@ -459,8 +490,8 @@ const addToPlaylist = () => {
const currentList = playerStore.playList;
// 添加歌曲到播放列表(避免重复添加)
const newSongs = filteredSongs.value.filter(song =>
!currentList.some(item => item.id === song.id)
const newSongs = filteredSongs.value.filter(
(song) => !currentList.some((item) => item.id === song.id)
);
if (newSongs.length === 0) {
@@ -471,7 +502,7 @@ const addToPlaylist = () => {
// 合并到当前播放列表末尾
const newList = [
...currentList,
...newSongs.map(song => ({
...newSongs.map((song) => ({
...song,
picUrl: song.al.picUrl
}))
@@ -486,7 +517,7 @@ const handlePlay = (song?: any) => {
// 如果传入了特定歌曲(点击单曲播放),则将其作为播放列表的第一首
if (song) {
const songList = [...filteredSongs.value];
const index = songList.findIndex(item => item.id === song.id);
const index = songList.findIndex((item) => item.id === song.id);
if (index !== -1) {
// 将点击的歌曲移到第一位
@@ -495,7 +526,7 @@ const handlePlay = (song?: any) => {
}
playerStore.setPlayList(
songList.map(item => ({
songList.map((item) => ({
...item,
picUrl: item.al?.picUrl || item.picUrl
}))
@@ -506,7 +537,7 @@ const handlePlay = (song?: any) => {
} else {
// 默认行为:播放整个过滤后的列表
playerStore.setPlayList(
filteredSongs.value.map(item => ({
filteredSongs.value.map((item) => ({
...item,
picUrl: item.al?.picUrl || item.picUrl
}))
@@ -721,7 +752,8 @@ const handleVirtualScroll = (e: any) => {
.songs-toolbar {
@apply flex items-center justify-between mb-4;
.toolbar-left, .toolbar-right {
.toolbar-left,
.toolbar-right {
@apply flex items-center gap-2;
}
}
@@ -787,7 +819,7 @@ const handleVirtualScroll = (e: any) => {
}
.mobile {
.songs-toolbar{
.songs-toolbar {
@apply mb-0;
}
}

View File

@@ -10,14 +10,14 @@
<div class="segment-control">
<div
class="segment-item"
:class="{ 'active': tabName === 'downloading' }"
:class="{ active: tabName === 'downloading' }"
@click="tabName = 'downloading'"
>
{{ t('download.tabs.downloading') }}
</div>
<div
class="segment-item"
:class="{ 'active': tabName === 'downloaded' }"
:class="{ active: tabName === 'downloaded' }"
@click="tabName = 'downloaded'"
>
{{ t('download.tabs.downloaded') }}
@@ -42,16 +42,11 @@
<div class="progress-title">
{{ t('download.progress.total', { progress: totalProgress.toFixed(1) }) }}
</div>
<div class="progress-info">
{{ downloadList.length }} {{ t('download.items') }}
</div>
<div class="progress-info">{{ downloadList.length }} {{ t('download.items') }}</div>
</div>
<div class="progress-bar-wrapper">
<div class="progress-bar">
<div
class="progress-fill"
:style="{ width: `${totalProgress}%` }"
></div>
<div class="progress-fill" :style="{ width: `${totalProgress}%` }"></div>
</div>
</div>
</div>
@@ -63,11 +58,17 @@
<img :src="getImgUrl(item.songInfo?.picUrl, '200y200')" alt="Cover" />
</div>
<div class="item-info flex items-center gap-4 w-full">
<div class="item-name min-w-[160px] max-w-[160px] truncate" :title="item.filename">
<div
class="item-name min-w-[160px] max-w-[160px] truncate"
:title="item.filename"
>
{{ item.filename }}
</div>
<div class="item-artist min-w-[120px] max-w-[120px] truncate">
{{ item.songInfo?.ar?.map((a) => a.name).join(', ') || t('download.artist.unknown') }}
{{
item.songInfo?.ar?.map((a) => a.name).join(', ') ||
t('download.artist.unknown')
}}
</div>
<div class="item-progress flex-1 min-w-0">
<div class="progress-bar">
@@ -126,10 +127,15 @@
<img :src="getImgUrl(item.picUrl, '200y200')" alt="Cover" />
</div>
<div class="item-info flex items-center gap-4 w-full">
<div class="item-name min-w-[160px] max-w-[160px] truncate" :title="item.displayName || item.filename">
<div
class="item-name min-w-[160px] max-w-[160px] truncate"
:title="item.displayName || item.filename"
>
{{ item.displayName || item.filename }}
</div>
<div class="item-artist min-w-[120px] max-w-[120px] flex items-center gap-1 truncate">
<div
class="item-artist min-w-[120px] max-w-[120px] flex items-center gap-1 truncate"
>
<i class="iconfont ri-user-line"></i>
<span>{{ item.ar?.map((a) => a.name).join(', ') }}</span>
</div>
@@ -137,7 +143,10 @@
<i class="iconfont ri-file-line"></i>
<span>{{ formatSize(item.size) }}</span>
</div>
<div class="item-path min-w-[220px] max-w-[220px] flex items-center gap-1" :title="item.path">
<div
class="item-path min-w-[220px] max-w-[220px] flex items-center gap-1"
:title="item.path"
>
<i class="iconfont ri-folder-path-line"></i>
<span>{{ shortenPath(item.path) }}</span>
<button class="copy-button" @click="copyPath(item.path)">
@@ -172,7 +181,11 @@
<span>{{ t('download.delete.title') }}</span>
</div>
<div class="modal-body">
{{ t('download.delete.message', { filename: itemToDelete?.displayName || itemToDelete?.filename }) }}
{{
t('download.delete.message', {
filename: itemToDelete?.displayName || itemToDelete?.filename
})
}}
</div>
<div class="modal-footer">
<button class="modal-btn cancel" @click="showDeleteConfirm = false">
@@ -230,7 +243,9 @@
class="flex-1"
/>
<div class="flex items-center gap-2">
<n-button class="flex-1" @click="selectDownloadPath">{{ t('download.settingsPanel.select') }}</n-button>
<n-button class="flex-1" @click="selectDownloadPath">{{
t('download.settingsPanel.select')
}}</n-button>
<n-button class="flex-1" @click="openDownloadPath">
{{ t('download.settingsPanel.open') }}
<i class="iconfont ri-folder-open-line"></i>
@@ -248,14 +263,18 @@
<div class="flex gap-2 my-2">
<n-button
size="small"
:type="downloadSettings.nameFormat === '{songName} - {artistName}' ? 'primary' : 'default'"
:type="
downloadSettings.nameFormat === '{songName} - {artistName}' ? 'primary' : 'default'
"
@click="downloadSettings.nameFormat = '{songName} - {artistName}'"
>
{{ t('download.settingsPanel.presets.songArtist') }}
</n-button>
<n-button
size="small"
:type="downloadSettings.nameFormat === '{artistName} - {songName}' ? 'primary' : 'default'"
:type="
downloadSettings.nameFormat === '{artistName} - {songName}' ? 'primary' : 'default'
"
@click="downloadSettings.nameFormat = '{artistName} - {songName}'"
>
{{ t('download.settingsPanel.presets.artistSong') }}
@@ -271,7 +290,9 @@
<!-- 分隔符设置 -->
<div class="my-3">
<div class="text-sm text-gray-500 mb-2">{{ t('download.settingsPanel.separator') || '分隔符' }}</div>
<div class="text-sm text-gray-500 mb-2">
{{ t('download.settingsPanel.separator') || '分隔符' }}
</div>
<div class="flex items-center gap-2">
<n-button
size="small"
@@ -305,32 +326,68 @@
<!-- 组件排序 -->
<div class="my-3">
<div class="text-sm text-gray-500 mb-2">{{ t('download.settingsPanel.dragToArrange') }}</div>
<div class="text-sm text-gray-500 mb-2">
{{ t('download.settingsPanel.dragToArrange') }}
</div>
<div class="format-components">
<div v-for="(component, index) in formatComponents" :key="component.id" class="format-item">
<div
v-for="(component, index) in formatComponents"
:key="component.id"
class="format-item"
>
<div class="flex items-center justify-between w-full">
<span>{{ t(`download.settingsPanel.components.${component.type}`) }}</span>
<div class="flex items-center">
<n-button quaternary circle size="small" @click="handleMoveUp(index)" :disabled="index === 0">
<n-button
quaternary
circle
size="small"
@click="handleMoveUp(index)"
:disabled="index === 0"
>
<template #icon><i class="iconfont ri-arrow-up-s-line"></i></template>
</n-button>
<n-button quaternary circle size="small" @click="handleMoveDown(index)" :disabled="index === formatComponents.length - 1">
<n-button
quaternary
circle
size="small"
@click="handleMoveDown(index)"
:disabled="index === formatComponents.length - 1"
>
<template #icon><i class="iconfont ri-arrow-down-s-line"></i></template>
</n-button>
<n-button quaternary circle size="small" @click="removeFormatComponent(index)" :disabled="formatComponents.length <= 1">
<n-button
quaternary
circle
size="small"
@click="removeFormatComponent(index)"
:disabled="formatComponents.length <= 1"
>
<template #icon><i class="iconfont ri-close-line"></i></template>
</n-button>
</div>
</div>
</div>
<div class="mt-2 flex gap-2">
<n-button size="small" @click="addFormatComponent('songName')" :disabled="formatComponents.some(c => c.type === 'songName')">
<n-button
size="small"
@click="addFormatComponent('songName')"
:disabled="formatComponents.some((c) => c.type === 'songName')"
>
+{{ t('download.settingsPanel.components.songName') }}
</n-button>
<n-button size="small" @click="addFormatComponent('artistName')" :disabled="formatComponents.some(c => c.type === 'artistName')">
<n-button
size="small"
@click="addFormatComponent('artistName')"
:disabled="formatComponents.some((c) => c.type === 'artistName')"
>
+{{ t('download.settingsPanel.components.artistName') }}
</n-button>
<n-button size="small" @click="addFormatComponent('albumName')" :disabled="formatComponents.some(c => c.type === 'albumName')">
<n-button
size="small"
@click="addFormatComponent('albumName')"
:disabled="formatComponents.some((c) => c.type === 'albumName')"
>
+{{ t('download.settingsPanel.components.albumName') }}
</n-button>
</div>
@@ -339,7 +396,9 @@
<!-- 自定义格式 -->
<div class="my-3">
<div class="text-sm text-gray-500 mb-2">{{ t('download.settingsPanel.customFormat') }}</div>
<div class="text-sm text-gray-500 mb-2">
{{ t('download.settingsPanel.customFormat') }}
</div>
<n-input
v-model:value="downloadSettings.nameFormat"
placeholder="{artistName} - {songName} - {albumName}"
@@ -348,7 +407,7 @@
<div class="mt-2 text-xs text-amber-500">
<i class="iconfont ri-information-line"></i>
{{ t('download.settingsPanel.formatVariables') }}:<br>
{{ t('download.settingsPanel.formatVariables') }}:<br />
{songName}, {artistName}, {albumName}
</div>
@@ -358,8 +417,6 @@
<div class="preview-content">{{ formatNamePreview }}</div>
</div>
</div>
</div>
</n-drawer-content>
</n-drawer>
@@ -372,8 +429,8 @@ import { useI18n } from 'vue-i18n';
import { getMusicDetail } from '@/api/music';
import { usePlayerStore } from '@/store/modules/player';
import { getImgUrl } from '@/utils';
import type { SongResult } from '@/type/music';
import { getImgUrl } from '@/utils';
const { t } = useI18n();
const playerStore = usePlayerStore();
@@ -446,11 +503,12 @@ const formatSize = (bytes: number) => {
// 复制文件路径
const copyPath = (path: string) => {
navigator.clipboard.writeText(path)
navigator.clipboard
.writeText(path)
.then(() => {
message.success(t('download.path.copied'));
})
.catch(err => {
.catch((err) => {
console.error('复制失败:', err);
message.error(t('download.path.copyFailed'));
});
@@ -503,20 +561,21 @@ const handlePlayMusic = async (item: DownloadedItem) => {
const song: SongResult = {
id: item.id,
name: item.displayName || item.filename,
ar: item.ar?.map(a => ({
id: 0,
name: a.name,
picId: 0,
img1v1Id: 0,
briefDesc: '',
picUrl: '',
img1v1Url: '',
albumSize: 0,
alias: [],
trans: '',
musicSize: 0,
topicPerson: 0
})) || [],
ar:
item.ar?.map((a) => ({
id: 0,
name: a.name,
picId: 0,
img1v1Id: 0,
briefDesc: '',
picUrl: '',
img1v1Url: '',
albumSize: 0,
alias: [],
trans: '',
musicSize: 0,
topicPerson: 0
})) || [],
al: {
name: item.filename,
id: 0,
@@ -561,13 +620,10 @@ const confirmDelete = async () => {
if (!item) return;
try {
const success = await window.electron.ipcRenderer.invoke(
'delete-downloaded-music',
item.path
);
const success = await window.electron.ipcRenderer.invoke('delete-downloaded-music', item.path);
if (success) {
const newList = downloadedList.value.filter(i => i.id !== item.id);
const newList = downloadedList.value.filter((i) => i.id !== item.id);
downloadedList.value = newList;
localStorage.setItem('downloadedList', JSON.stringify(newList));
message.success(t('download.delete.success'));
@@ -637,10 +693,10 @@ const refreshDownloadedList = async () => {
return;
}
const songIds = list.filter(item => item.id).map(item => item.id);
const songIds = list.filter((item) => item.id).map((item) => item.id);
if (songIds.length === 0) {
// 处理显示格式化文件名
const updatedList = list.map(item => ({
const updatedList = list.map((item) => ({
...item,
displayName: formatSongName(item) || item.filename
}));
@@ -657,7 +713,7 @@ const refreshDownloadedList = async () => {
return acc;
}, {});
const updatedList = list.map(item => {
const updatedList = list.map((item) => {
const songDetail = songDetails[item.id];
const updatedItem = {
...item,
@@ -676,7 +732,7 @@ const refreshDownloadedList = async () => {
} catch (error) {
console.error('Failed to get music details:', error);
// 处理显示格式化文件名
const updatedList = list.map(item => ({
const updatedList = list.map((item) => ({
...item,
displayName: formatSongName(item) || item.filename
}));
@@ -750,7 +806,7 @@ onMounted(() => {
// 下载成功处理
if (data.success) {
// 从下载列表中移除
downloadList.value = downloadList.value.filter(item => item.filename !== data.filename);
downloadList.value = downloadList.value.filter((item) => item.filename !== data.filename);
// 延迟刷新已下载列表,避免文件系统未完全写入
setTimeout(() => refreshDownloadedList(), 500);
@@ -764,7 +820,7 @@ onMounted(() => {
}, 10000); // 10秒后清除
} else {
// 下载失败处理
const existingItem = downloadList.value.find(item => item.filename === data.filename);
const existingItem = downloadList.value.find((item) => item.filename === data.filename);
if (existingItem) {
Object.assign(existingItem, {
status: 'error',
@@ -772,12 +828,14 @@ onMounted(() => {
progress: 0
});
setTimeout(() => {
downloadList.value = downloadList.value.filter(item => item.filename !== data.filename);
downloadList.value = downloadList.value.filter((item) => item.filename !== data.filename);
processedDownloads.delete(data.filename);
}, 3000);
}
message.error(t('download.message.downloadFailed', { filename: data.filename, error: data.error }));
message.error(
t('download.message.downloadFailed', { filename: data.filename, error: data.error })
);
}
});
@@ -809,7 +867,7 @@ const downloadSettings = ref({
// 格式组件(用于拖拽排序)
const formatComponents = ref([
{ id: 1, type: 'songName' },
{ id: 2, type: 'artistName' },
{ id: 2, type: 'artistName' }
]);
// 处理组件排序
@@ -829,7 +887,7 @@ const handleMoveDown = (index: number) => {
// 添加新的格式组件
const addFormatComponent = (type: string) => {
if (!formatComponents.value.some(item => item.type === type)) {
if (!formatComponents.value.some((item) => item.type === type)) {
formatComponents.value.push({
id: Date.now(),
type
@@ -843,31 +901,38 @@ const removeFormatComponent = (index: number) => {
};
// 监听组件变化更新格式
watch(formatComponents, (newComponents) => {
let format = '';
newComponents.forEach((component, index) => {
format += `{${component.type}}`;
if (index < newComponents.length - 1) {
format += downloadSettings.value.separator;
}
});
downloadSettings.value.nameFormat = format;
}, { deep: true });
// 监听分隔符变化更新格式
watch(() => downloadSettings.value.separator, (newSeparator) => {
if (formatComponents.value.length > 1) {
// 重新构建格式字符串
watch(
formatComponents,
(newComponents) => {
let format = '';
formatComponents.value.forEach((component, index) => {
newComponents.forEach((component, index) => {
format += `{${component.type}}`;
if (index < formatComponents.value.length - 1) {
format += newSeparator;
if (index < newComponents.length - 1) {
format += downloadSettings.value.separator;
}
});
downloadSettings.value.nameFormat = format;
},
{ deep: true }
);
// 监听分隔符变化更新格式
watch(
() => downloadSettings.value.separator,
(newSeparator) => {
if (formatComponents.value.length > 1) {
// 重新构建格式字符串
let format = '';
formatComponents.value.forEach((component, index) => {
format += `{${component.type}}`;
if (index < formatComponents.value.length - 1) {
format += newSeparator;
}
});
downloadSettings.value.nameFormat = format;
}
}
});
);
// 格式名称预览
const formatNamePreview = computed(() => {
@@ -898,9 +963,21 @@ const openDownloadPath = () => {
// 保存下载设置
const saveDownloadSettings = () => {
// 保存到配置
window.electron.ipcRenderer.send('set-store-value', 'set.downloadPath', downloadSettings.value.path);
window.electron.ipcRenderer.send('set-store-value', 'set.downloadNameFormat', downloadSettings.value.nameFormat);
window.electron.ipcRenderer.send('set-store-value', 'set.downloadSeparator', downloadSettings.value.separator);
window.electron.ipcRenderer.send(
'set-store-value',
'set.downloadPath',
downloadSettings.value.path
);
window.electron.ipcRenderer.send(
'set-store-value',
'set.downloadNameFormat',
downloadSettings.value.nameFormat
);
window.electron.ipcRenderer.send(
'set-store-value',
'set.downloadSeparator',
downloadSettings.value.separator
);
// 如果是在已下载页面,刷新列表以更新显示
if (tabName.value === 'downloaded') {
@@ -915,11 +992,17 @@ const saveDownloadSettings = () => {
const initDownloadSettings = async () => {
// 获取当前配置
const path = await window.electron.ipcRenderer.invoke('get-store-value', 'set.downloadPath');
const nameFormat = await window.electron.ipcRenderer.invoke('get-store-value', 'set.downloadNameFormat');
const separator = await window.electron.ipcRenderer.invoke('get-store-value', 'set.downloadSeparator');
const nameFormat = await window.electron.ipcRenderer.invoke(
'get-store-value',
'set.downloadNameFormat'
);
const separator = await window.electron.ipcRenderer.invoke(
'get-store-value',
'set.downloadSeparator'
);
downloadSettings.value = {
path: path || await window.electron.ipcRenderer.invoke('get-downloads-path'),
path: path || (await window.electron.ipcRenderer.invoke('get-downloads-path')),
nameFormat: nameFormat || '{songName} - {artistName}',
separator: separator || ' - '
};
@@ -952,18 +1035,21 @@ const updateFormatComponents = () => {
watch(() => downloadSettings.value.nameFormat, updateFormatComponents);
// 监听命名格式变化,更新已下载文件的显示名称
watch(() => downloadSettings.value.nameFormat, () => {
if (downloadedList.value.length > 0) {
// 更新所有已下载项的显示名称
downloadedList.value = downloadedList.value.map(item => ({
...item,
displayName: formatSongName(item) || item.filename
}));
watch(
() => downloadSettings.value.nameFormat,
() => {
if (downloadedList.value.length > 0) {
// 更新所有已下载项的显示名称
downloadedList.value = downloadedList.value.map((item) => ({
...item,
displayName: formatSongName(item) || item.filename
}));
// 保存到本地存储
localStorage.setItem('downloadedList', JSON.stringify(downloadedList.value));
// 保存到本地存储
localStorage.setItem('downloadedList', JSON.stringify(downloadedList.value));
}
}
});
);
// 初始化
onMounted(() => {
@@ -1425,6 +1511,3 @@ onMounted(() => {
@apply text-sm;
}
</style>

View File

@@ -8,19 +8,11 @@
<div v-if="!isComponent && isElectron" class="favorite-header-right">
<div class="sort-controls" v-if="!isSelecting">
<div class="sort-buttons">
<div
class="sort-button"
:class="{ active: isDescending }"
@click="toggleSort(true)"
>
<div class="sort-button" :class="{ active: isDescending }" @click="toggleSort(true)">
<i class="iconfont ri-sort-desc"></i>
{{ t('favorite.descending') }}
</div>
<div
class="sort-button"
:class="{ active: !isDescending }"
@click="toggleSort(false)"
>
<div class="sort-button" :class="{ active: !isDescending }" @click="toggleSort(false)">
<i class="iconfont ri-sort-asc"></i>
{{ t('favorite.ascending') }}
</div>
@@ -104,53 +96,53 @@
</template>
<script setup lang="ts">
import { computed, ref, watch, onMounted } from 'vue';
import { computed, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { getMusicDetail } from '@/api/music';
import { getBilibiliProxyUrl, getBilibiliVideoDetail } from '@/api/bilibili';
import { getMusicDetail } from '@/api/music';
import SongItem from '@/components/common/SongItem.vue';
import { useDownload } from '@/hooks/useDownload';
import { usePlayerStore } from '@/store';
import type { SongResult } from '@/type/music';
import { isElectron, setAnimationClass, setAnimationDelay } from '@/utils';
const { t } = useI18n();
const playerStore = usePlayerStore();
const favoriteList = computed(() => playerStore.favoriteList);
const favoriteSongs = ref<SongResult[]>([]);
const loading = ref(false);
const noMore = ref(false);
const scrollbarRef = ref();
const { t } = useI18n();
const playerStore = usePlayerStore();
const favoriteList = computed(() => playerStore.favoriteList);
const favoriteSongs = ref<SongResult[]>([]);
const loading = ref(false);
const noMore = ref(false);
const scrollbarRef = ref();
// 多选相关
// 多选相关
const isSelecting = ref(false);
const selectedSongs = ref<number[]>([]);
const { isDownloading, batchDownloadMusic } = useDownload();
// 开始多选
const startSelect = () => {
isSelecting.value = true;
selectedSongs.value = [];
};
// 开始多选
const startSelect = () => {
isSelecting.value = true;
selectedSongs.value = [];
};
// 取消多选
const cancelSelect = () => {
isSelecting.value = false;
selectedSongs.value = [];
};
// 取消多选
const cancelSelect = () => {
isSelecting.value = false;
selectedSongs.value = [];
};
// 处理选择
const handleSelect = (songId: number, selected: boolean) => {
if (selected) {
selectedSongs.value.push(songId);
} else {
selectedSongs.value = selectedSongs.value.filter((id) => id !== songId);
}
};
// 处理选择
const handleSelect = (songId: number, selected: boolean) => {
if (selected) {
selectedSongs.value.push(songId);
} else {
selectedSongs.value = selectedSongs.value.filter((id) => id !== songId);
}
};
// 批量下载
// 批量下载
const handleBatchDownload = async () => {
// 获取选中歌曲的信息
const selectedSongsList = selectedSongs.value
@@ -164,390 +156,390 @@ const handleBatchDownload = async () => {
cancelSelect();
};
// 排序相关
const isDescending = ref(true); // 默认倒序显示
// 排序相关
const isDescending = ref(true); // 默认倒序显示
// 切换排序方式
const toggleSort = (descending: boolean) => {
if (isDescending.value === descending) return;
isDescending.value = descending;
currentPage.value = 1;
// 切换排序方式
const toggleSort = (descending: boolean) => {
if (isDescending.value === descending) return;
isDescending.value = descending;
currentPage.value = 1;
favoriteSongs.value = [];
noMore.value = false;
getFavoriteSongs();
};
// 无限滚动相关
const pageSize = 100;
const currentPage = ref(1);
const props = defineProps({
isComponent: {
type: Boolean,
default: false
}
});
// 获取当前页的收藏歌曲ID
const getCurrentPageIds = () => {
let ids = [...favoriteList.value]; // 复制一份以免修改原数组
// 根据排序方式调整顺序
if (isDescending.value) {
ids = ids.reverse(); // 倒序,最新收藏的在前面
}
const startIndex = (currentPage.value - 1) * pageSize;
const endIndex = startIndex + pageSize;
// 返回原始ID不进行类型转换
return ids.slice(startIndex, endIndex);
};
// 获取收藏歌曲详情
const getFavoriteSongs = async () => {
if (favoriteList.value.length === 0) {
favoriteSongs.value = [];
noMore.value = false;
getFavoriteSongs();
};
return;
}
// 无限滚动相关
const pageSize = 100;
const currentPage = ref(1);
if (props.isComponent && favoriteSongs.value.length >= 16) {
return;
}
const props = defineProps({
isComponent: {
type: Boolean,
default: false
}
});
loading.value = true;
try {
const currentIds = getCurrentPageIds();
// 获取当前页的收藏歌曲ID
const getCurrentPageIds = () => {
let ids = [...favoriteList.value]; // 复制一份以免修改原数组
// 分离网易云音乐ID和B站视频ID
const musicIds = currentIds.filter((id) => typeof id === 'number') as number[];
// B站ID可能是字符串格式包含"--"或特定数字ID如113911642789603
const bilibiliIds = currentIds.filter((id) => typeof id === 'string');
// 根据排序方式调整顺序
if (isDescending.value) {
ids = ids.reverse(); // 倒序,最新收藏的在前面
}
const startIndex = (currentPage.value - 1) * pageSize;
const endIndex = startIndex + pageSize;
// 返回原始ID不进行类型转换
return ids.slice(startIndex, endIndex);
};
// 获取收藏歌曲详情
const getFavoriteSongs = async () => {
if (favoriteList.value.length === 0) {
favoriteSongs.value = [];
return;
}
if (props.isComponent && favoriteSongs.value.length >= 16) {
return;
}
loading.value = true;
try {
const currentIds = getCurrentPageIds();
// 分离网易云音乐ID和B站视频ID
const musicIds = currentIds.filter((id) => typeof id === 'number') as number[];
// B站ID可能是字符串格式包含"--"或特定数字ID如113911642789603
const bilibiliIds = currentIds.filter((id) => typeof id === 'string');
// 处理网易云音乐数据
let neteaseSongs: SongResult[] = [];
if (musicIds.length > 0) {
const res = await getMusicDetail(musicIds);
if (res.data.songs) {
neteaseSongs = res.data.songs.map((song: SongResult) => ({
...song,
picUrl: song.al?.picUrl || '',
source: 'netease'
}));
}
// 处理网易云音乐数据
let neteaseSongs: SongResult[] = [];
if (musicIds.length > 0) {
const res = await getMusicDetail(musicIds);
if (res.data.songs) {
neteaseSongs = res.data.songs.map((song: SongResult) => ({
...song,
picUrl: song.al?.picUrl || '',
source: 'netease'
}));
}
}
// 处理B站视频数据
const bilibiliSongs: SongResult[] = [];
for (const biliId of bilibiliIds) {
const strBiliId = String(biliId);
console.log(`处理B站ID: ${strBiliId}`);
// 处理B站视频数据
const bilibiliSongs: SongResult[] = [];
for (const biliId of bilibiliIds) {
const strBiliId = String(biliId);
console.log(`处理B站ID: ${strBiliId}`);
if (strBiliId.includes('--')) {
// 从ID中提取B站视频信息 (bvid--pid--cid格式)
try {
const [bvid, pid, cid] = strBiliId.split('--');
if (!bvid || !pid || !cid) {
console.warn(`B站ID格式错误: ${strBiliId}, 正确格式应为 bvid--pid--cid`);
continue;
}
if (strBiliId.includes('--')) {
// 从ID中提取B站视频信息 (bvid--pid--cid格式)
try {
const [bvid, pid, cid] = strBiliId.split('--');
if (!bvid || !pid || !cid) {
console.warn(`B站ID格式错误: ${strBiliId}, 正确格式应为 bvid--pid--cid`);
continue;
}
const res = await getBilibiliVideoDetail(bvid);
const videoDetail = res.data;
const res = await getBilibiliVideoDetail(bvid);
const videoDetail = res.data;
// 找到对应的分P
const page = videoDetail.pages.find(p => p.cid === Number(cid));
if (!page) {
console.warn(`未找到对应的分P: cid=${cid}`);
continue;
}
// 找到对应的分P
const page = videoDetail.pages.find((p) => p.cid === Number(cid));
if (!page) {
console.warn(`未找到对应的分P: cid=${cid}`);
continue;
}
const songData = {
id: strBiliId,
name: `${page.part || ''} - ${videoDetail.title}`,
picUrl: getBilibiliProxyUrl(videoDetail.pic),
ar: [
{
name: videoDetail.owner.name,
id: videoDetail.owner.mid
}
],
al: {
name: videoDetail.title,
picUrl: getBilibiliProxyUrl(videoDetail.pic)
},
source: 'bilibili',
bilibiliData: {
bvid,
cid: Number(cid)
const songData = {
id: strBiliId,
name: `${page.part || ''} - ${videoDetail.title}`,
picUrl: getBilibiliProxyUrl(videoDetail.pic),
ar: [
{
name: videoDetail.owner.name,
id: videoDetail.owner.mid
}
} as SongResult;
],
al: {
name: videoDetail.title,
picUrl: getBilibiliProxyUrl(videoDetail.pic)
},
source: 'bilibili',
bilibiliData: {
bvid,
cid: Number(cid)
}
} as SongResult;
bilibiliSongs.push(songData);
} catch (error) {
console.error(`获取B站视频详情失败 (${strBiliId}):`, error);
bilibiliSongs.push(songData);
} catch (error) {
console.error(`获取B站视频详情失败 (${strBiliId}):`, error);
}
}
}
console.log('获取数据统计:', {
neteaseSongs: neteaseSongs.length,
bilibiliSongs: bilibiliSongs.length
});
// 合并数据,保持原有顺序
const newSongs = currentIds
.map((id) => {
const strId = String(id);
// 查找B站视频
if (typeof id === 'string') {
const found = bilibiliSongs.find((song) => String(song.id) === strId);
if (found) return found;
}
// 查找网易云音乐
const found = neteaseSongs.find((song) => String(song.id) === strId);
return found;
})
.filter((song): song is SongResult => !!song);
console.log(`最终歌曲列表: ${newSongs.length}`);
// 追加新数据而不是替换
if (currentPage.value === 1) {
favoriteSongs.value = newSongs;
} else {
favoriteSongs.value = [...favoriteSongs.value, ...newSongs];
}
// 判断是否还有更多数据
noMore.value = favoriteSongs.value.length >= favoriteList.value.length;
} catch (error) {
console.error('获取收藏歌曲失败:', error);
} finally {
loading.value = false;
}
};
// 处理滚动事件
const handleScroll = (e: any) => {
const { scrollTop, scrollHeight, offsetHeight } = e.target;
const threshold = 100; // 距离底部多少像素时加载更多
if (!loading.value && !noMore.value && scrollHeight - (scrollTop + offsetHeight) < threshold) {
currentPage.value++;
getFavoriteSongs();
}
};
const hasLoaded = ref(false);
onMounted(async () => {
if (!hasLoaded.value) {
await playerStore.initializeFavoriteList();
await getFavoriteSongs();
hasLoaded.value = true;
}
});
// 监听收藏列表变化,变化时重置并重新加载
watch(
favoriteList,
async () => {
hasLoaded.value = false;
currentPage.value = 1;
noMore.value = false;
await getFavoriteSongs();
hasLoaded.value = true;
},
{ deep: true }
);
const handlePlay = () => {
playerStore.setPlayList(favoriteSongs.value);
};
const getItemAnimationDelay = (index: number) => {
return setAnimationDelay(index, 30);
};
const router = useRouter();
const handleMore = () => {
router.push('/history');
};
// 全选相关
const isAllSelected = computed(() => {
return (
favoriteSongs.value.length > 0 && selectedSongs.value.length === favoriteSongs.value.length
);
});
const isIndeterminate = computed(() => {
return selectedSongs.value.length > 0 && selectedSongs.value.length < favoriteSongs.value.length;
});
// 处理全选/取消全选
const handleSelectAll = (checked: boolean) => {
if (checked) {
selectedSongs.value = favoriteSongs.value.map((song) => song.id as number);
} else {
selectedSongs.value = [];
}
};
</script>
<style lang="scss" scoped>
.favorite-page {
@apply h-full flex flex-col pt-2;
@apply bg-light dark:bg-black;
.favorite-header {
@apply flex items-center justify-between flex-shrink-0 px-4 pb-2;
&-left {
@apply flex items-center gap-4;
h2 {
@apply text-xl font-bold;
@apply text-gray-900 dark:text-white;
}
.favorite-count {
@apply text-gray-500 dark:text-gray-400 text-sm;
}
}
&-right {
@apply flex items-center gap-3;
.sort-controls {
@apply flex items-center;
.sort-buttons {
@apply flex items-center bg-gray-100 dark:bg-gray-800 rounded-full overflow-hidden;
@apply border border-gray-200 dark:border-gray-700;
.sort-button {
@apply flex items-center py-1 px-3 text-sm cursor-pointer;
@apply text-gray-600 dark:text-gray-400;
@apply transition-all duration-300;
&:first-child {
@apply border-r border-gray-200 dark:border-gray-700;
}
.iconfont {
@apply mr-1 text-base;
}
&.active {
@apply bg-green-500 text-white dark:text-gray-100;
@apply font-medium;
}
&:hover:not(.active) {
@apply bg-gray-200 dark:bg-gray-700;
}
}
}
}
console.log('获取数据统计:', {
neteaseSongs: neteaseSongs.length,
bilibiliSongs: bilibiliSongs.length
});
.select-btn {
@apply rounded-full px-4 h-8;
@apply transition-all duration-300 ease-in-out;
@apply hover:bg-primary hover:text-white;
@apply dark:border-gray-600;
// 合并数据,保持原有顺序
const newSongs = currentIds
.map(id => {
const strId = String(id);
// 查找B站视频
if (typeof id === 'string') {
const found = bilibiliSongs.find(song => String(song.id) === strId);
if (found) return found;
}
// 查找网易云音乐
const found = neteaseSongs.find(song => String(song.id) === strId);
return found;
})
.filter((song): song is SongResult => !!song);
console.log(`最终歌曲列表: ${newSongs.length}`);
// 追加新数据而不是替换
if (currentPage.value === 1) {
favoriteSongs.value = newSongs;
} else {
favoriteSongs.value = [...favoriteSongs.value, ...newSongs];
.iconfont {
@apply mr-1 text-lg;
}
}
// 判断是否还有更多数据
noMore.value = favoriteSongs.value.length >= favoriteList.value.length;
} catch (error) {
console.error('获取收藏歌曲失败:', error);
} finally {
loading.value = false;
.select-controls {
@apply flex items-center gap-3;
@apply bg-gray-50 dark:bg-gray-800;
@apply rounded-full px-3 py-1;
@apply border border-gray-200 dark:border-gray-700;
@apply transition-all duration-300;
.select-all-checkbox {
@apply text-sm text-gray-900 dark:text-gray-200;
}
.operation-btns {
@apply flex items-center gap-2 ml-2;
.download-btn {
@apply rounded-full px-4 h-7;
@apply bg-primary text-white;
@apply hover:bg-primary-dark;
@apply disabled:opacity-50 disabled:cursor-not-allowed;
.iconfont {
@apply mr-1 text-lg;
}
}
.cancel-btn {
@apply rounded-full px-4 h-7;
@apply text-gray-600 dark:text-gray-300;
@apply hover:bg-gray-100 dark:hover:bg-gray-700;
@apply border-gray-300 dark:border-gray-600;
}
}
}
}
};
}
// 处理滚动事件
const handleScroll = (e: any) => {
const { scrollTop, scrollHeight, offsetHeight } = e.target;
const threshold = 100; // 距离底部多少像素时加载更多
.favorite-main {
@apply flex flex-col flex-grow min-h-0;
if (!loading.value && !noMore.value && scrollHeight - (scrollTop + offsetHeight) < threshold) {
currentPage.value++;
getFavoriteSongs();
.favorite-content {
@apply flex-grow min-h-0;
.empty-tip {
@apply h-full flex items-center justify-center;
@apply text-gray-500 dark:text-gray-400;
}
.favorite-list {
@apply space-y-2 pb-4 px-4;
&-item {
@apply bg-light-100 dark:bg-dark-100 hover:bg-light-200 dark:hover:bg-dark-200 transition-all;
}
&-more {
@apply mt-4;
.n-button {
@apply text-green-500 hover:text-green-600;
}
}
}
}
};
}
}
const hasLoaded = ref(false);
.loading-wrapper {
@apply flex justify-center items-center py-20;
}
onMounted(async () => {
if (!hasLoaded.value) {
await playerStore.initializeFavoriteList();
await getFavoriteSongs();
hasLoaded.value = true;
}
});
.no-more-tip {
@apply text-center py-4 text-sm;
@apply text-gray-500 dark:text-gray-400;
}
// 监听收藏列表变化,变化时重置并重新加载
watch(
favoriteList,
async () => {
hasLoaded.value = false;
currentPage.value = 1;
noMore.value = false;
await getFavoriteSongs();
hasLoaded.value = true;
},
{ deep: true }
);
const handlePlay = () => {
playerStore.setPlayList(favoriteSongs.value);
};
const getItemAnimationDelay = (index: number) => {
return setAnimationDelay(index, 30);
};
const router = useRouter();
const handleMore = () => {
router.push('/history');
};
// 全选相关
const isAllSelected = computed(() => {
return (
favoriteSongs.value.length > 0 && selectedSongs.value.length === favoriteSongs.value.length
);
});
const isIndeterminate = computed(() => {
return selectedSongs.value.length > 0 && selectedSongs.value.length < favoriteSongs.value.length;
});
// 处理全选/取消全选
const handleSelectAll = (checked: boolean) => {
if (checked) {
selectedSongs.value = favoriteSongs.value.map((song) => song.id as number);
} else {
selectedSongs.value = [];
}
};
</script>
<style lang="scss" scoped>
.mobile {
.favorite-page {
@apply h-full flex flex-col pt-2;
@apply bg-light dark:bg-black;
@apply p-4 m-0;
.favorite-header {
@apply flex items-center justify-between flex-shrink-0 px-4 pb-2;
@apply mb-4;
&-left {
@apply flex items-center gap-4;
h2 {
@apply text-xl font-bold;
@apply text-gray-900 dark:text-white;
}
.favorite-count {
@apply text-gray-500 dark:text-gray-400 text-sm;
}
}
&-right {
@apply flex items-center gap-3;
.sort-controls {
@apply flex items-center;
.sort-buttons {
@apply flex items-center bg-gray-100 dark:bg-gray-800 rounded-full overflow-hidden;
@apply border border-gray-200 dark:border-gray-700;
.sort-button {
@apply flex items-center py-1 px-3 text-sm cursor-pointer;
@apply text-gray-600 dark:text-gray-400;
@apply transition-all duration-300;
&:first-child {
@apply border-r border-gray-200 dark:border-gray-700;
}
.iconfont {
@apply mr-1 text-base;
}
&.active {
@apply bg-green-500 text-white dark:text-gray-100;
@apply font-medium;
}
&:hover:not(.active) {
@apply bg-gray-200 dark:bg-gray-700;
}
}
}
}
.select-btn {
@apply rounded-full px-4 h-8;
@apply transition-all duration-300 ease-in-out;
@apply hover:bg-primary hover:text-white;
@apply dark:border-gray-600;
.iconfont {
@apply mr-1 text-lg;
}
}
.select-controls {
@apply flex items-center gap-3;
@apply bg-gray-50 dark:bg-gray-800;
@apply rounded-full px-3 py-1;
@apply border border-gray-200 dark:border-gray-700;
@apply transition-all duration-300;
.select-all-checkbox {
@apply text-sm text-gray-900 dark:text-gray-200;
}
.operation-btns {
@apply flex items-center gap-2 ml-2;
.download-btn {
@apply rounded-full px-4 h-7;
@apply bg-primary text-white;
@apply hover:bg-primary-dark;
@apply disabled:opacity-50 disabled:cursor-not-allowed;
.iconfont {
@apply mr-1 text-lg;
}
}
.cancel-btn {
@apply rounded-full px-4 h-7;
@apply text-gray-600 dark:text-gray-300;
@apply hover:bg-gray-100 dark:hover:bg-gray-700;
@apply border-gray-300 dark:border-gray-600;
}
}
}
}
}
.favorite-main {
@apply flex flex-col flex-grow min-h-0;
.favorite-content {
@apply flex-grow min-h-0;
.empty-tip {
@apply h-full flex items-center justify-center;
@apply text-gray-500 dark:text-gray-400;
}
.favorite-list {
@apply space-y-2 pb-4 px-4;
&-item {
@apply bg-light-100 dark:bg-dark-100 hover:bg-light-200 dark:hover:bg-dark-200 transition-all;
}
&-more {
@apply mt-4;
.n-button {
@apply text-green-500 hover:text-green-600;
}
}
}
h2 {
@apply text-xl;
}
}
}
.loading-wrapper {
@apply flex justify-center items-center py-20;
}
.no-more-tip {
@apply text-center py-4 text-sm;
@apply text-gray-500 dark:text-gray-400;
}
.mobile {
.favorite-page {
@apply p-4 m-0;
.favorite-header {
@apply mb-4;
h2 {
@apply text-xl;
}
}
}
}
</style>
}
</style>

Some files were not shown because too many files have changed in this diff Show More