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 name: 反馈 Bug
description: 通过 github 模板进行 Bug 反馈。 description: 通过 github 模板进行 Bug 反馈。
title: "描述问题的标题" title: '描述问题的标题'
body: body:
- type: markdown - type: markdown
attributes: attributes:

View File

@@ -1,5 +1,5 @@
blank_issues_enabled: true blank_issues_enabled: true
contact_links: contact_links:
- name: - name:
url: url:
about: about:

View File

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

View File

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

View File

@@ -8,11 +8,11 @@ on:
jobs: jobs:
release: release:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
strategy: strategy:
matrix: matrix:
os: [macos-latest, windows-latest, ubuntu-latest] os: [macos-latest, windows-latest, ubuntu-latest]
steps: steps:
- name: Check out Git repository - name: Check out Git repository
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -85,4 +85,4 @@ jobs:
draft: false draft: false
prerelease: false prerelease: false
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -16,7 +16,7 @@ jobs:
uses: actions/setup-node@v3 uses: actions/setup-node@v3
with: with:
node-version: '18' node-version: '18'
- name: 创建环境变量文件 - name: 创建环境变量文件
run: | run: |
echo "VITE_API=${{ secrets.VITE_API }}" > .env.production.local echo "VITE_API=${{ secrets.VITE_API }}" > .env.production.local
@@ -36,7 +36,7 @@ jobs:
host: ${{ secrets.SERVER_HOST }} host: ${{ secrets.SERVER_HOST }}
username: ${{ secrets.SERVER_USERNAME }} username: ${{ secrets.SERVER_USERNAME }}
key: ${{ secrets.DEPLOY_KEY }} key: ${{ secrets.DEPLOY_KEY }}
source: "out/renderer/*" source: 'out/renderer/*'
target: ${{ secrets.DEPLOY_PATH }} target: ${{ secrets.DEPLOY_PATH }}
strip_components: 2 strip_components: 2
@@ -48,4 +48,4 @@ jobs:
key: ${{ secrets.DEPLOY_KEY }} key: ${{ secrets.DEPLOY_KEY }}
script: | script: |
cd ${{ secrets.DEPLOY_PATH }} cd ${{ secrets.DEPLOY_PATH }}
echo "部署完成于 $(date)" echo "部署完成于 $(date)"

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

40
DEV.md
View File

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

View File

@@ -1,4 +1,3 @@
<h2 align="center">🎵 Alger Music Player</h2> <h2 align="center">🎵 Alger Music Player</h2>
<div align="center"> <div align="center">
<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> <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> </div>
[项目下安装以及常用问题文档](https://www.yuque.com/alger-pfg5q/ip4f1a/bmgmfmghnhgwghkm?singleDoc#) [项目下安装以及常用问题文档](https://www.yuque.com/alger-pfg5q/ip4f1a/bmgmfmghnhgwghkm?singleDoc#)
主要功能如下 主要功能如下
- 🎵 音乐推荐 - 🎵 音乐推荐
- 🔐 网易云账号登录与同步 - 🔐 网易云账号登录与同步
- 📝 功能 - 📝 功能
@@ -41,7 +40,6 @@
- 迷你模式 - 迷你模式
- 状态栏控制 - 状态栏控制
- 多语言支持 - 多语言支持
- 🎼 音乐功能 - 🎼 音乐功能
- 支持歌单、MV、专辑等完整音乐服务 - 支持歌单、MV、专辑等完整音乐服务
- 音乐资源解析(基于 @unblockneteasemusic/server - 音乐资源解析(基于 @unblockneteasemusic/server
@@ -56,12 +54,15 @@
- 全平台适配Desktop & Web & Mobile Web & Android<测试> & ios<后续> - 全平台适配Desktop & Web & Mobile Web & Android<测试> & ios<后续>
## 项目简介 ## 项目简介
一个第三方音乐播放器、本地服务、桌面歌词、音乐下载、最高音质
一个第三方音乐播放器、本地服务、桌面歌词、音乐下载、最高音质
## 预览地址 ## 预览地址
[http://music.alger.fun/](http://music.alger.fun/) [http://music.alger.fun/](http://music.alger.fun/)
## 软件截图 ## 软件截图
![首页白](./docs/image.png) ![首页白](./docs/image.png)
![首页黑](./docs/image3.png) ![首页黑](./docs/image3.png)
![歌词](./docs/image6.png) ![歌词](./docs/image6.png)
@@ -70,31 +71,31 @@
![音乐远程控制](./docs/image5.png) ![音乐远程控制](./docs/image5.png)
## 项目启动 ## 项目启动
```bash ```bash
npm install npm install
npm run dev npm run dev
``` ```
## 开发文档 ## 开发文档
点击这里[开发文档](./DEV.md) 点击这里[开发文档](./DEV.md)
## 赞赏☕️ ## 赞赏☕️
[赞赏列表](http://donate.alger.fun/) [赞赏列表](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> | | <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) [![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 ## 欢迎提Issues
## 声明 ## 声明
本软件仅用于学习交流,禁止用于商业用途,否则后果自负。 本软件仅用于学习交流,禁止用于商业用途,否则后果自负。
希望大家还是要多多支持官方正版,此软件仅用作开发教学。 希望大家还是要多多支持官方正版,此软件仅用作开发教学。

View File

@@ -39,7 +39,7 @@ export default defineConfig({
], ],
publicDir: resolve('resources'), publicDir: resolve('resources'),
server: { 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": { "scripts": {
"prepare": "husky", "prepare": "husky",
"format": "prettier --write .", "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:node": "tsc --noEmit -p tsconfig.node.json --composite false",
"typecheck:web": "vue-tsc --noEmit -p tsconfig.web.json --composite false", "typecheck:web": "vue-tsc --noEmit -p tsconfig.web.json --composite false",
"typecheck": "npm run typecheck:node && npm run typecheck:web", "typecheck": "npm run typecheck:node && npm run typecheck:web",
@@ -44,6 +44,7 @@
"@electron-toolkit/eslint-config": "^2.1.0", "@electron-toolkit/eslint-config": "^2.1.0",
"@electron-toolkit/eslint-config-ts": "^3.1.0", "@electron-toolkit/eslint-config-ts": "^3.1.0",
"@electron-toolkit/tsconfig": "^1.0.1", "@electron-toolkit/tsconfig": "^1.0.1",
"@eslint/js": "^9.31.0",
"@rushstack/eslint-patch": "^1.10.3", "@rushstack/eslint-patch": "^1.10.3",
"@tailwindcss/postcss7-compat": "^2.2.4", "@tailwindcss/postcss7-compat": "^2.2.4",
"@types/howler": "^2.2.12", "@types/howler": "^2.2.12",
@@ -66,12 +67,13 @@
"electron-builder": "^25.1.8", "electron-builder": "^25.1.8",
"electron-vite": "^3.1.0", "electron-vite": "^3.1.0",
"eslint": "^9.0.0", "eslint": "^9.0.0",
"eslint-config-prettier": "^10.1.2", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-import": "^2.29.1", "eslint-plugin-import": "^2.32.0",
"eslint-plugin-prettier": "^5.1.3", "eslint-plugin-prettier": "^5.5.3",
"eslint-plugin-simple-import-sort": "^12.0.0", "eslint-plugin-simple-import-sort": "^12.1.1",
"eslint-plugin-vue": "^10.0.0", "eslint-plugin-vue": "^10.3.0",
"eslint-plugin-vue-scoped-css": "^2.9.0", "eslint-plugin-vue-scoped-css": "^2.11.0",
"globals": "^16.3.0",
"howler": "^2.2.4", "howler": "^2.2.4",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"marked": "^15.0.4", "marked": "^15.0.4",
@@ -79,7 +81,7 @@
"pinia": "^3.0.1", "pinia": "^3.0.1",
"pinyin-match": "^1.2.6", "pinyin-match": "^1.2.6",
"postcss": "^8.5.3", "postcss": "^8.5.3",
"prettier": "^3.3.2", "prettier": "^3.6.2",
"remixicon": "^4.6.0", "remixicon": "^4.6.0",
"sass": "^1.86.0", "sass": "^1.86.0",
"tailwindcss": "^3.4.17", "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"> <html lang="zh-CN">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta
<title>AlgerMusicPlayer 远程控制</title> name="viewport"
<style> content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
:root { />
--primary-color: #007AFF; <title>AlgerMusicPlayer 远程控制</title>
--secondary-color: #5AC8FA; <style>
--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) {
:root { :root {
--primary-color: #0A84FF; --primary-color: #007aff;
--secondary-color: #64D2FF; --secondary-color: #5ac8fa;
--success-color: #30D158; --success-color: #4cd964;
--danger-color: #FF453A; --danger-color: #ff3b30;
--warning-color: #FF9F0A; --warning-color: #ff9500;
--light-gray: #1C1C1E; --light-gray: #f2f2f7;
--medium-gray: #2C2C2E; --medium-gray: #e5e5ea;
--dark-gray: #8E8E93; --dark-gray: #8e8e93;
--text-color: #FFFFFF; --text-color: #000000;
--text-secondary: #AEAEB2; --text-secondary: #6c6c6c;
--background-color: #000000; --background-color: #ffffff;
} }
}
* { @media (prefers-color-scheme: dark) {
margin: 0; :root {
padding: 0; --primary-color: #0a84ff;
box-sizing: border-box; --secondary-color: #64d2ff;
-webkit-tap-highlight-color: transparent; --success-color: #30d158;
} --danger-color: #ff453a;
--warning-color: #ff9f0a;
body { --light-gray: #1c1c1e;
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Helvetica Neue', Arial, sans-serif; --medium-gray: #2c2c2e;
line-height: 1.6; --dark-gray: #8e8e93;
color: var(--text-color); --text-color: #ffffff;
background-color: var(--light-gray); --text-secondary: #aeaeb2;
display: flex; --background-color: #000000;
flex-direction: column; }
min-height: 100vh;
padding: 0;
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);
}
.header h1 {
font-size: 18px;
font-weight: 600;
margin: 0;
}
.container {
max-width: 540px;
margin: 0 auto;
padding: 16px;
width: 100%;
flex: 1;
}
.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-info {
display: flex;
align-items: center;
padding-bottom: 16px;
}
.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 {
margin-left: 16px;
flex: 1;
}
.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 p {
margin: 4px 0 0;
font-size: 15px;
color: var(--text-secondary);
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;
}
.play-state::before {
content: '';
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 6px;
}
.playing .play-state::before {
background-color: var(--success-color);
}
.paused .play-state::before {
background-color: var(--warning-color);
}
.controls {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin-bottom: 16px;
}
.extra-controls {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 12px;
}
.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;
} }
* {
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
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 {
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);
}
.header h1 {
font-size: 18px;
font-weight: 600;
margin: 0;
}
.container {
max-width: 540px;
margin: 0 auto;
padding: 16px;
width: 100%;
flex: 1;
}
.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-info {
display: flex;
align-items: center;
padding-bottom: 16px;
}
.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 {
margin-left: 16px;
flex: 1;
}
.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 p {
margin: 4px 0 0;
font-size: 15px;
color: var(--text-secondary);
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;
}
.play-state::before {
content: '';
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 6px;
}
.playing .play-state::before {
background-color: var(--success-color);
}
.paused .play-state::before {
background-color: var(--warning-color);
}
.controls {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin-bottom: 16px;
}
.extra-controls {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 12px;
}
.btn { .btn {
padding: 12px 0; display: flex;
font-size: 12px; 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 { .btn svg {
width: 20px; margin-bottom: 8px;
height: 20px; width: 24px;
height: 24px;
fill: var(--primary-color);
}
.btn-play svg {
width: 28px;
height: 28px;
margin-bottom: 6px; margin-bottom: 6px;
} }
}
</style>
</head>
<body>
<div class="header">
<h1>AlgerMusicPlayer 远程控制</h1>
</div>
<div class="container"> .status-bar {
<div class="card" id="songInfoCard"> text-align: center;
<div class="song-info"> padding: 8px 16px;
<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="封面"> font-size: 14px;
<div class="song-details"> color: var(--text-secondary);
<h2 id="songTitle">未在播放</h2> background-color: var(--background-color);
<p id="songArtist">--</p> border-top: 1px solid var(--medium-gray);
<div class="play-state" id="playState">未播放</div> 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>
</div> </div>
<div class="card"> <div class="status-bar">
<div class="controls"> <span id="status" class="status-message">准备就绪</span>
<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>
<div class="card"> <script>
<div class="extra-controls"> // 页面加载完成后执行
<button id="favoriteBtn" class="btn"> document.addEventListener('DOMContentLoaded', () => {
<svg viewBox="0 0 24 24" fill="currentColor"> // 获取DOM元素
<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"/> const songInfoCard = document.getElementById('songInfoCard');
</svg> const songTitle = document.getElementById('songTitle');
收藏 const songArtist = document.getElementById('songArtist');
</button> const songCover = document.getElementById('songCover');
<button id="refreshBtn" class="btn"> const playState = document.getElementById('playState');
<svg viewBox="0 0 24 24" fill="currentColor"> const playBtn = document.getElementById('playBtn');
<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"/> const playIcon = document.getElementById('playIcon');
</svg> const prevBtn = document.getElementById('prevBtn');
刷新 const nextBtn = document.getElementById('nextBtn');
</button> const favoriteBtn = document.getElementById('favoriteBtn');
</div> const volumeUpBtn = document.getElementById('volumeUpBtn');
</div> const volumeDownBtn = document.getElementById('volumeDownBtn');
</div> const refreshBtn = document.getElementById('refreshBtn');
const status = document.getElementById('status');
<div class="status-bar"> let isPlaying = false;
<span id="status" class="status-message">准备就绪</span>
</div>
<script> // 显示状态消息并淡出
// 页面加载完成后执行 function showStatus(message, autoClear = true) {
document.addEventListener('DOMContentLoaded', () => { status.textContent = message;
// 获取DOM元素 status.classList.remove('fade');
const songInfoCard = document.getElementById('songInfoCard');
const songTitle = document.getElementById('songTitle'); if (autoClear) {
const songArtist = document.getElementById('songArtist'); setTimeout(() => {
const songCover = document.getElementById('songCover'); status.classList.add('fade');
const playState = document.getElementById('playState'); }, 2000);
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');
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";
} }
// 更新播放状态
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', () => { 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";
}
// 更新播放状态
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(); 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>
</script> </body>
</body> </html>
</html>

View File

@@ -174,7 +174,8 @@ export default {
noTasks: 'No import tasks', noTasks: 'No import tasks',
clearTasks: 'Clear Tasks', clearTasks: 'Clear Tasks',
clearTasksConfirmTitle: 'Confirm Clear', 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', confirm: 'Confirm',
cancel: 'Cancel', cancel: 'Cancel',
clearTasksSuccess: 'Task list cleared', clearTasksSuccess: 'Task list cleared',

View File

@@ -63,7 +63,7 @@ export default {
favorite: 'Favorite {name}', favorite: 'Favorite {name}',
unFavorite: 'Unfavorite {name}', unFavorite: 'Unfavorite {name}',
playbackSpeed: 'Playback Speed', playbackSpeed: 'Playback Speed',
advancedControls: 'Advanced Controls', advancedControls: 'Advanced Controls'
}, },
eq: { eq: {
title: 'Equalizer', title: 'Equalizer',
@@ -117,6 +117,7 @@ export default {
cleared: 'Playlist cleared', cleared: 'Playlist cleared',
empty: 'Playlist is empty', empty: 'Playlist is empty',
clearConfirmTitle: 'Clear Playlist', 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', configureMusicSources: 'Configure Sources',
selectedMusicSources: 'Selected sources:', selectedMusicSources: 'Selected sources:',
noMusicSources: 'No sources selected', 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', autoPlay: 'Auto Play',
autoPlayDesc: 'Auto resume playback when reopening the app', autoPlayDesc: 'Auto resume playback when reopening the app',
showStatusBar: "Show Status Bar", showStatusBar: 'Show Status Bar',
showStatusBarContent: "You can display the music control function in your mac status bar (effective after a restart)" showStatusBarContent:
'You can display the music control function in your mac status bar (effective after a restart)'
}, },
application: { application: {
closeAction: 'Close Action', closeAction: 'Close Action',
@@ -232,9 +234,9 @@ export default {
'spotify-green': 'Spotify Green', 'spotify-green': 'Spotify Green',
'apple-blue': 'Apple Blue', 'apple-blue': 'Apple Blue',
'youtube-red': 'YouTube Red', 'youtube-red': 'YouTube Red',
'orange': 'Vibrant Orange', orange: 'Vibrant Orange',
'purple': 'Mystic Purple', purple: 'Mystic Purple',
'pink': 'Cherry Pink' pink: 'Cherry Pink'
}, },
tooltips: { tooltips: {
openColorPicker: 'Open Color Picker', openColorPicker: 'Open Color Picker',
@@ -280,6 +282,6 @@ export default {
addIp: 'Add IP', addIp: 'Add IP',
emptyListHint: 'Empty list means allow all IPs', emptyListHint: 'Empty list means allow all IPs',
saveSuccess: 'Remote control settings saved', 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', unfavorite: 'Unlike',
removeFromPlaylist: 'Remove from Playlist', removeFromPlaylist: 'Remove from Playlist',
dislike: 'Dislike', dislike: 'Dislike',
undislike: 'Undislike', undislike: 'Undislike'
}, },
message: { message: {
downloading: 'Downloading, please wait...', downloading: 'Downloading, please wait...',
@@ -18,7 +18,7 @@ export default {
getUrlFailed: 'Failed to get music download URL, please check if logged in' getUrlFailed: 'Failed to get music download URL, please check if logged in'
}, },
dialog: { dialog: {
dislike:{ dislike: {
title: 'Dislike', title: 'Dislike',
content: 'Are you sure you want to dislike this song?', content: 'Are you sure you want to dislike this song?',
positiveText: 'Dislike', positiveText: 'Dislike',

View File

@@ -20,14 +20,14 @@ export default {
noFollowings: 'No Followings', noFollowings: 'No Followings',
loadMore: 'Load More', loadMore: 'Load More',
noSignature: 'This guy is lazy, nothing left', noSignature: 'This guy is lazy, nothing left',
userFollowsTitle: '\'s Followings', userFollowsTitle: "'s Followings",
myFollowsTitle: 'My Followings' myFollowsTitle: 'My Followings'
}, },
follower: { follower: {
title: 'Follower List', title: 'Follower List',
noFollowers: 'No Followers', noFollowers: 'No Followers',
loadMore: 'Load More', loadMore: 'Load More',
userFollowersTitle: '\'s Followers', userFollowersTitle: "'s Followers",
myFollowersTitle: 'My Followers' myFollowersTitle: 'My Followers'
}, },
detail: { detail: {
@@ -38,7 +38,7 @@ export default {
artist: 'Artist', artist: 'Artist',
noSignature: 'This guy is lazy, nothing left', noSignature: 'This guy is lazy, nothing left',
invalidUserId: 'Invalid User ID', 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: { message: {
loadFailed: 'Failed to load user page', loadFailed: 'Failed to load user page',

View File

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

View File

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

View File

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

View File

@@ -2,4 +2,4 @@ export default {
hotSongs: '熱門歌曲', hotSongs: '熱門歌曲',
albums: '專輯', albums: '專輯',
description: '藝人介紹' description: '藝人介紹'
}; };

View File

@@ -53,4 +53,4 @@ export default {
play: '播放', play: '播放',
favorite: '收藏' favorite: '收藏'
} }
}; };

View File

@@ -187,4 +187,4 @@ export default {
mv: 'MV', mv: 'MV',
home: '首頁', home: '首頁',
search: '搜尋' search: '搜尋'
}; };

View File

@@ -5,4 +5,4 @@ export default {
toDonateList: '請我喝杯咖啡', toDonateList: '請我喝杯咖啡',
noMessage: '暫無留言', noMessage: '暫無留言',
title: '捐贈列表' title: '捐贈列表'
}; };

View File

@@ -84,4 +84,4 @@ export default {
albumName: '專輯名' albumName: '專輯名'
} }
} }
}; };

View File

@@ -10,4 +10,4 @@ export default {
selectSongsFirst: '請先選擇要下載的歌曲', selectSongsFirst: '請先選擇要下載的歌曲',
descending: '降', descending: '降',
ascending: '升' ascending: '升'
}; };

View File

@@ -2,4 +2,4 @@ export default {
title: '播放歷史', title: '播放歷史',
playCount: '{count}', playCount: '{count}',
getHistoryFailed: '取得歷史記錄失敗' getHistoryFailed: '取得歷史記錄失敗'
}; };

View File

@@ -26,4 +26,4 @@ export default {
download, download,
comp, comp,
artist artist
}; };

View File

@@ -19,4 +19,4 @@ export default {
loadError: '載入登入資訊時出錯', loadError: '載入登入資訊時出錯',
qrCheckError: '檢查二維碼狀態時出錯' qrCheckError: '檢查二維碼狀態時出錯'
} }
}; };

View File

@@ -64,7 +64,7 @@ export default {
unFavorite: '已取消收藏{name}', unFavorite: '已取消收藏{name}',
miniPlayBar: '迷你播放列', miniPlayBar: '迷你播放列',
playbackSpeed: '播放速度', playbackSpeed: '播放速度',
advancedControls: '更多設定s', advancedControls: '更多設定s'
}, },
eq: { eq: {
title: '等化器', title: '等化器',
@@ -120,4 +120,4 @@ export default {
clearConfirmTitle: '清空播放清單', clearConfirmTitle: '清空播放清單',
clearConfirmContent: '這將清空所有播放清單中的歌曲並停止目前播放。是否繼續?' clearConfirmContent: '這將清空所有播放清單中的歌曲並停止目前播放。是否繼續?'
} }
}; };

View File

@@ -24,4 +24,4 @@ export default {
mv: 'MV', mv: 'MV',
bilibili: 'B站' bilibili: 'B站'
} }
}; };

View File

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

View File

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

View File

@@ -45,4 +45,4 @@ export default {
deleteSuccess: '刪除成功', deleteSuccess: '刪除成功',
deleteFailed: '刪除失敗' deleteFailed: '刪除失敗'
} }
}; };

View File

@@ -55,4 +55,4 @@
"mobileUnavailable": "此设置仅在移动端可用" "mobileUnavailable": "此设置仅在移动端可用"
} }
} }
} }

View File

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

View File

@@ -1,14 +1,14 @@
import axios from 'axios'; import axios from 'axios';
import { app, dialog, ipcMain, Notification, protocol, shell } from 'electron'; import { app, dialog, ipcMain, Notification, protocol, shell } from 'electron';
import Store from 'electron-store'; import Store from 'electron-store';
import { fileTypeFromFile } from 'file-type';
import * as fs from 'fs'; import * as fs from 'fs';
import * as http from 'http'; import * as http from 'http';
import * as https from 'https'; 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 * 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'; import { getStore } from './config';
@@ -42,18 +42,18 @@ export function initializeFileManager() {
// 注册本地文件协议 // 注册本地文件协议
protocol.registerFileProtocol('local', (request, callback) => { protocol.registerFileProtocol('local', (request, callback) => {
try { try {
let url = request.url; const url = request.url;
// local://C:/Users/xxx.mp3 // local://C:/Users/xxx.mp3
let filePath = decodeURIComponent(url.replace('local:///', '')); let filePath = decodeURIComponent(url.replace('local:///', ''));
// 兼容 local:///C:/Users/xxx.mp3 这种情况 // 兼容 local:///C:/Users/xxx.mp3 这种情况
if (/^\/[a-zA-Z]:\//.test(filePath)) { if (/^\/[a-zA-Z]:\//.test(filePath)) {
filePath = filePath.slice(1); filePath = filePath.slice(1);
} }
// 还原为系统路径格式 // 还原为系统路径格式
filePath = path.normalize(filePath); filePath = path.normalize(filePath);
// 检查文件是否存在 // 检查文件是否存在
if (!fs.existsSync(filePath)) { if (!fs.existsSync(filePath)) {
console.error('File not found:', filePath); console.error('File not found:', filePath);
@@ -128,13 +128,13 @@ export function initializeFileManager() {
ipcMain.handle('get-downloads-path', () => { ipcMain.handle('get-downloads-path', () => {
return app.getPath('downloads'); return app.getPath('downloads');
}); });
// 获取存储的配置值 // 获取存储的配置值
ipcMain.handle('get-store-value', (_, key) => { ipcMain.handle('get-store-value', (_, key) => {
const store = new Store(); const store = new Store();
return store.get(key); return store.get(key);
}); });
// 设置存储的配置值 // 设置存储的配置值
ipcMain.on('set-store-value', (_, key, value) => { ipcMain.on('set-store-value', (_, key, value) => {
const store = new Store(); const store = new Store();
@@ -189,7 +189,8 @@ export function initializeFileManager() {
const validEntriesPromises = await Promise.all( const validEntriesPromises = await Promise.all(
entriesArray.map(async ([path, info]) => { entriesArray.map(async ([path, info]) => {
try { try {
const exists = await fs.promises.access(path) const exists = await fs.promises
.access(path)
.then(() => true) .then(() => true)
.catch(() => false); .catch(() => false);
return exists ? info : null; return exists ? info : null;
@@ -202,7 +203,7 @@ export function initializeFileManager() {
// 过滤有效的歌曲并排序 // 过滤有效的歌曲并排序
const validSongs = validEntriesPromises const validSongs = validEntriesPromises
.filter(song => song !== null) .filter((song) => song !== null)
.sort((a, b) => (b.downloadTime || 0) - (a.downloadTime || 0)); .sort((a, b) => (b.downloadTime || 0) - (a.downloadTime || 0));
// 更新存储,移除不存在的文件记录 // 更新存储,移除不存在的文件记录
@@ -376,9 +377,9 @@ async function downloadMusic(
const downloadPath = const downloadPath =
(configStore.get('set.downloadPath') as string) || app.getPath('downloads'); (configStore.get('set.downloadPath') as string) || app.getPath('downloads');
const apiPort = configStore.get('set.musicApiPort') || 30488; const apiPort = configStore.get('set.musicApiPort') || 30488;
// 获取文件名格式设置 // 获取文件名格式设置
const nameFormat = const nameFormat =
(configStore.get('set.downloadNameFormat') as string) || '{songName} - {artistName}'; (configStore.get('set.downloadNameFormat') as string) || '{songName} - {artistName}';
// 根据格式创建文件名 // 根据格式创建文件名
@@ -388,7 +389,7 @@ async function downloadMusic(
const artistName = songInfo.ar?.map((a: any) => a.name).join('/') || '未知艺术家'; const artistName = songInfo.ar?.map((a: any) => a.name).join('/') || '未知艺术家';
const songName = songInfo.name || filename; const songName = songInfo.name || filename;
const albumName = songInfo.al?.name || '未知专辑'; const albumName = songInfo.al?.name || '未知专辑';
// 应用自定义格式 // 应用自定义格式
formattedFilename = nameFormat formattedFilename = nameFormat
.replace(/\{songName\}/g, songName) .replace(/\{songName\}/g, songName)
@@ -401,12 +402,12 @@ async function downloadMusic(
// 创建临时文件路径 (在系统临时目录中创建) // 创建临时文件路径 (在系统临时目录中创建)
const tempDir = path.join(os.tmpdir(), 'AlgerMusicPlayerTemp'); const tempDir = path.join(os.tmpdir(), 'AlgerMusicPlayerTemp');
// 确保临时目录存在 // 确保临时目录存在
if (!fs.existsSync(tempDir)) { if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true }); fs.mkdirSync(tempDir, { recursive: true });
} }
tempFilePath = path.join(tempDir, `${Date.now()}_${sanitizedFilename}.tmp`); tempFilePath = path.join(tempDir, `${Date.now()}_${sanitizedFilename}.tmp`);
// 先获取文件大小 // 先获取文件大小
@@ -460,7 +461,7 @@ async function downloadMusic(
// 检测文件类型 // 检测文件类型
let fileExtension = ''; let fileExtension = '';
try { try {
// 首先尝试使用file-type库检测 // 首先尝试使用file-type库检测
const fileType = await fileTypeFromFile(tempFilePath); const fileType = await fileTypeFromFile(tempFilePath);
@@ -475,26 +476,28 @@ async function downloadMusic(
const formatInfo = metadata.format; const formatInfo = metadata.format;
const container = formatInfo.container || ''; const container = formatInfo.container || '';
const codec = formatInfo.codec || ''; const codec = formatInfo.codec || '';
// 音频格式映射表 // 音频格式映射表
const formatMap = { const formatMap = {
'mp3': ['MPEG', 'MP3', 'mp3'], mp3: ['MPEG', 'MP3', 'mp3'],
'aac': ['AAC'], aac: ['AAC'],
'flac': ['FLAC'], flac: ['FLAC'],
'ogg': ['Ogg', 'Vorbis'], ogg: ['Ogg', 'Vorbis'],
'wav': ['WAV', 'PCM'], wav: ['WAV', 'PCM'],
'm4a': ['M4A', 'MP4'] m4a: ['M4A', 'MP4']
}; };
// 查找匹配的格式 // 查找匹配的格式
const format = Object.entries(formatMap).find(([_, keywords]) => 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 // 设置文件扩展名如果没找到则默认为mp3
fileExtension = format ? `.${format[0]}` : '.mp3'; fileExtension = format ? `.${format[0]}` : '.mp3';
console.log(`music-metadata检测结果: 容器:${container}, 编码:${codec}, 扩展名: ${fileExtension}`); console.log(
`music-metadata检测结果: 容器:${container}, 编码:${codec}, 扩展名: ${fileExtension}`
);
} else { } else {
// 两种方法都失败使用传入的type或默认mp3 // 两种方法都失败使用传入的type或默认mp3
fileExtension = type ? `.${type}` : '.mp3'; fileExtension = type ? `.${type}` : '.mp3';
@@ -593,7 +596,7 @@ async function downloadMusic(
try { try {
// 在写入ID3标签前先移除可能存在的旧标签 // 在写入ID3标签前先移除可能存在的旧标签
NodeID3.removeTags(finalFilePath); NodeID3.removeTags(finalFilePath);
const tags = { const tags = {
title: filename, title: filename,
artist: artistNames, artist: artistNames,
@@ -676,7 +679,7 @@ async function downloadMusic(
const notificationId = `download-${finalFilePath}`; const notificationId = `download-${finalFilePath}`;
if (!sentNotifications.has(notificationId)) { if (!sentNotifications.has(notificationId)) {
sentNotifications.set(notificationId, true); sentNotifications.set(notificationId, true);
// 发送桌面通知 // 发送桌面通知
try { try {
const artistNames = const artistNames =
@@ -687,13 +690,13 @@ async function downloadMusic(
body: `${songInfo?.name || filename} - ${artistNames}`, body: `${songInfo?.name || filename} - ${artistNames}`,
silent: false silent: false
}); });
notification.on('click', () => { notification.on('click', () => {
shell.showItemInFolder(finalFilePath); shell.showItemInFolder(finalFilePath);
}); });
notification.show(); notification.show();
// 60秒后清理通知记录释放内存 // 60秒后清理通知记录释放内存
setTimeout(() => { setTimeout(() => {
sentNotifications.delete(notificationId); sentNotifications.delete(notificationId);
@@ -722,7 +725,7 @@ async function downloadMusic(
if (writer) { if (writer) {
writer.end(); writer.end();
} }
// 清理临时文件 // 清理临时文件
if (tempFilePath && fs.existsSync(tempFilePath)) { if (tempFilePath && fs.existsSync(tempFilePath)) {
try { try {
@@ -731,7 +734,7 @@ async function downloadMusic(
console.error('Failed to delete temporary file:', e); console.error('Failed to delete temporary file:', e);
} }
} }
// 清理未完成的最终文件 // 清理未完成的最终文件
if (finalFilePath && fs.existsSync(finalFilePath)) { if (finalFilePath && fs.existsSync(finalFilePath)) {
try { try {

View File

@@ -1,10 +1,11 @@
import cors from 'cors';
import { ipcMain } from 'electron'; import { ipcMain } from 'electron';
import express from 'express'; 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 fs from 'fs';
import os from 'os';
import path from 'path';
import { getStore } from './config';
// 定义远程控制相关接口 // 定义远程控制相关接口
export interface RemoteControlConfig { export interface RemoteControlConfig {
@@ -72,9 +73,9 @@ export function initializeRemoteControl(mainWindow: Electron.BrowserWindow) {
if (server) { if (server) {
stopServer(); stopServer();
} }
store.set('remoteControl', newConfig); store.set('remoteControl', newConfig);
if (newConfig.enabled) { if (newConfig.enabled) {
startServer(newConfig); startServer(newConfig);
} }
@@ -105,16 +106,16 @@ function startServer(config: RemoteControlConfig) {
} }
app = express(); app = express();
// 跨域配置 // 跨域配置
app.use(cors()); app.use(cors());
app.use(express.json()); app.use(express.json());
// IP 过滤中间件 // IP 过滤中间件
app.use((req, res, next) => { app.use((req, res, next) => {
const clientIp = req.ip || req.socket.remoteAddress || ''; const clientIp = req.ip || req.socket.remoteAddress || '';
const cleanIp = clientIp.replace(/^::ffff:/, ''); // 移除IPv6前缀 const cleanIp = clientIp.replace(/^::ffff:/, ''); // 移除IPv6前缀
console.log('config',config) console.log('config', config);
if (config.allowedIps.length === 0 || config.allowedIps.includes(cleanIp)) { if (config.allowedIps.length === 0 || config.allowedIps.includes(cleanIp)) {
next(); next();
} else { } else {
@@ -216,7 +217,7 @@ function setupRoutes(app: express.Application) {
const isDev = process.env.NODE_ENV === 'development'; const isDev = process.env.NODE_ENV === 'development';
const htmlPath = path.join(process.cwd(), 'resources', 'html', 'remote-control.html'); const htmlPath = path.join(process.cwd(), 'resources', 'html', 'remote-control.html');
const finalPath = isDev ? htmlPath : path.join(resourcesPath, 'html', 'remote-control.html'); const finalPath = isDev ? htmlPath : path.join(resourcesPath, 'html', 'remote-control.html');
if (fs.existsSync(finalPath)) { if (fs.existsSync(finalPath)) {
res.sendFile(finalPath); res.sendFile(finalPath);
} else { } else {
@@ -228,4 +229,4 @@ function setupRoutes(app: express.Application) {
res.status(500).send('加载远程控制界面失败'); res.status(500).send('加载远程控制界面失败');
} }
}); });
} }

View File

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

View File

@@ -31,8 +31,6 @@ export interface WindowState {
isMaximized: boolean; isMaximized: boolean;
} }
/** /**
* 窗口大小管理器 * 窗口大小管理器
* 负责保存、恢复和维护窗口大小状态 * 负责保存、恢复和维护窗口大小状态
@@ -42,12 +40,12 @@ class WindowSizeManager {
private mainWindow: BrowserWindow | null = null; private mainWindow: BrowserWindow | null = null;
private savedState: WindowState | null = null; private savedState: WindowState | null = null;
private isInitialized: boolean = false; private isInitialized: boolean = false;
constructor() { constructor() {
this.store = store; this.store = store;
// 初始化时不做与screen相关的操作等app ready后再初始化 // 初始化时不做与screen相关的操作等app ready后再初始化
} }
/** /**
* 初始化窗口大小管理器 * 初始化窗口大小管理器
* 必须在app ready后调用 * 必须在app ready后调用
@@ -57,17 +55,17 @@ class WindowSizeManager {
console.warn('WindowSizeManager.initialize() 必须在 app ready 之后调用!'); console.warn('WindowSizeManager.initialize() 必须在 app ready 之后调用!');
return; return;
} }
if (this.isInitialized) { if (this.isInitialized) {
return; return;
} }
this.initMinimumWindowSize(); this.initMinimumWindowSize();
this.setupIPCHandlers(); this.setupIPCHandlers();
this.isInitialized = true; this.isInitialized = true;
console.log('窗口大小管理器初始化完成'); console.log('窗口大小管理器初始化完成');
} }
/** /**
* 设置主窗口引用 * 设置主窗口引用
*/ */
@@ -75,19 +73,19 @@ class WindowSizeManager {
if (!this.isInitialized) { if (!this.isInitialized) {
this.initialize(); this.initialize();
} }
this.mainWindow = win; this.mainWindow = win;
// 读取保存的状态 // 读取保存的状态
this.savedState = this.getWindowState(); this.savedState = this.getWindowState();
// 监听重要事件 // 监听重要事件
this.setupEventListeners(win); this.setupEventListeners(win);
// 立即保存初始状态 // 立即保存初始状态
this.saveWindowState(win); this.saveWindowState(win);
} }
/** /**
* 初始化最小窗口尺寸 * 初始化最小窗口尺寸
*/ */
@@ -96,14 +94,17 @@ class WindowSizeManager {
console.warn('不能在 app ready 之前访问 screen 模块'); console.warn('不能在 app ready 之前访问 screen 模块');
return; return;
} }
try { try {
const { width: workAreaWidth, height: workAreaHeight } = screen.getPrimaryDisplay().workArea; const { width: workAreaWidth, height: workAreaHeight } = screen.getPrimaryDisplay().workArea;
// 根据工作区大小设置合理的最小尺寸 // 根据工作区大小设置合理的最小尺寸
MIN_WIDTH = Math.min(Math.round(DEFAULT_MAIN_WIDTH * 0.5), Math.round(workAreaWidth * 0.3)); 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}`); console.log(`设置最小窗口尺寸: ${MIN_WIDTH}x${MIN_HEIGHT}`);
} catch (error) { } catch (error) {
console.error('初始化最小窗口尺寸失败:', error); console.error('初始化最小窗口尺寸失败:', error);
@@ -112,7 +113,7 @@ class WindowSizeManager {
MIN_HEIGHT = Math.round(DEFAULT_MAIN_HEIGHT * 0.5); MIN_HEIGHT = Math.round(DEFAULT_MAIN_HEIGHT * 0.5);
} }
} }
/** /**
* 设置事件监听器 * 设置事件监听器
*/ */
@@ -123,46 +124,46 @@ class WindowSizeManager {
this.saveWindowState(win); this.saveWindowState(win);
} }
}); });
// 监听窗口移动事件 // 监听窗口移动事件
win.on('move', () => { win.on('move', () => {
if (!win.isDestroyed() && !win.isMinimized()) { if (!win.isDestroyed() && !win.isMinimized()) {
this.saveWindowState(win); this.saveWindowState(win);
} }
}); });
// 监听窗口最大化事件 // 监听窗口最大化事件
win.on('maximize', () => { win.on('maximize', () => {
if (!win.isDestroyed()) { if (!win.isDestroyed()) {
this.saveWindowState(win); this.saveWindowState(win);
} }
}); });
// 监听窗口从最大化恢复事件 // 监听窗口从最大化恢复事件
win.on('unmaximize', () => { win.on('unmaximize', () => {
if (!win.isDestroyed()) { if (!win.isDestroyed()) {
this.saveWindowState(win); this.saveWindowState(win);
} }
}); });
// 监听窗口关闭事件,确保保存最终状态 // 监听窗口关闭事件,确保保存最终状态
win.on('close', () => { win.on('close', () => {
if (!win.isDestroyed()) { if (!win.isDestroyed()) {
this.saveWindowState(win); this.saveWindowState(win);
} }
}); });
// 在页面加载完成后确保窗口大小正确 // 在页面加载完成后确保窗口大小正确
win.webContents.on('did-finish-load', () => { win.webContents.on('did-finish-load', () => {
this.enforceCorrectSize(win); this.enforceCorrectSize(win);
}); });
// 在窗口准备好显示时确保尺寸正确 // 在窗口准备好显示时确保尺寸正确
win.on('ready-to-show', () => { win.on('ready-to-show', () => {
this.enforceCorrectSize(win); this.enforceCorrectSize(win);
}); });
} }
/** /**
* 强制应用正确的窗口大小 * 强制应用正确的窗口大小
*/ */
@@ -170,30 +171,36 @@ class WindowSizeManager {
if (!this.savedState || win.isMaximized() || win.isMinimized() || win.isDestroyed()) { if (!this.savedState || win.isMaximized() || win.isMinimized() || win.isDestroyed()) {
return; return;
} }
const [currentWidth, currentHeight] = win.getSize(); const [currentWidth, currentHeight] = win.getSize();
if (Math.abs(currentWidth - this.savedState.width) > 2 || if (
Math.abs(currentHeight - this.savedState.height) > 2) { Math.abs(currentWidth - this.savedState.width) > 2 ||
console.log(`强制调整窗口大小: 当前=${currentWidth}x${currentHeight}, 目标=${this.savedState.width}x${this.savedState.height}`); Math.abs(currentHeight - this.savedState.height) > 2
) {
console.log(
`强制调整窗口大小: 当前=${currentWidth}x${currentHeight}, 目标=${this.savedState.width}x${this.savedState.height}`
);
// 临时禁用minimum size限制 // 临时禁用minimum size限制
const [minWidth, minHeight] = win.getMinimumSize(); const [minWidth, minHeight] = win.getMinimumSize();
win.setMinimumSize(1, 1); win.setMinimumSize(1, 1);
// 强制设置正确大小 // 强制设置正确大小
win.setSize(this.savedState.width, this.savedState.height, false); win.setSize(this.savedState.width, this.savedState.height, false);
// 恢复原始minimum size // 恢复原始minimum size
win.setMinimumSize(minWidth, minHeight); win.setMinimumSize(minWidth, minHeight);
// 验证尺寸设置是否成功 // 验证尺寸设置是否成功
const [newWidth, newHeight] = win.getSize(); const [newWidth, newHeight] = win.getSize();
console.log(`调整后窗口大小: ${newWidth}x${newHeight}`); console.log(`调整后窗口大小: ${newWidth}x${newHeight}`);
// 如果调整后的大小仍然与目标不一致,尝试再次调整 // 如果调整后的大小仍然与目标不一致,尝试再次调整
if (Math.abs(newWidth - this.savedState.width) > 1 || if (
Math.abs(newHeight - this.savedState.height) > 1) { Math.abs(newWidth - this.savedState.width) > 1 ||
Math.abs(newHeight - this.savedState.height) > 1
) {
console.log(`窗口大小调整后仍不一致,将再次尝试调整`); console.log(`窗口大小调整后仍不一致,将再次尝试调整`);
setTimeout(() => { setTimeout(() => {
if (!win.isDestroyed() && !win.isMaximized() && !win.isMinimized()) { if (!win.isDestroyed() && !win.isMaximized() && !win.isMinimized()) {
@@ -201,12 +208,12 @@ class WindowSizeManager {
} }
}, 50); }, 50);
} }
// // 开始尺寸强制执行 // // 开始尺寸强制执行
// this.startSizeEnforcement(win); // this.startSizeEnforcement(win);
} }
} }
/** /**
* 开启尺寸强制执行定时器 * 开启尺寸强制执行定时器
*/ */
@@ -216,15 +223,15 @@ class WindowSizeManager {
// clearInterval(this.enforceTimer); // clearInterval(this.enforceTimer);
// this.enforceTimer = null; // this.enforceTimer = null;
// } // }
// this.enforceCount = 0; // this.enforceCount = 0;
// // 创建新的定时器每50ms检查一次窗口大小 // // 创建新的定时器每50ms检查一次窗口大小
// this.enforceTimer = setInterval(() => { // this.enforceTimer = setInterval(() => {
// if (this.enforceCount >= this.MAX_ENFORCE_COUNT || // if (this.enforceCount >= this.MAX_ENFORCE_COUNT ||
// !this.savedState || // !this.savedState ||
// win.isDestroyed() || // win.isDestroyed() ||
// win.isMaximized() || // win.isMaximized() ||
// win.isMinimized()) { // win.isMinimized()) {
// // 达到最大检查次数或不需要检查,清除定时器 // // 达到最大检查次数或不需要检查,清除定时器
// if (this.enforceTimer) { // if (this.enforceTimer) {
@@ -233,35 +240,35 @@ class WindowSizeManager {
// } // }
// return; // return;
// } // }
// const [currentWidth, currentHeight] = win.getSize(); // const [currentWidth, currentHeight] = win.getSize();
// if (Math.abs(currentWidth - this.savedState.width) > 2 || // if (Math.abs(currentWidth - this.savedState.width) > 2 ||
// Math.abs(currentHeight - this.savedState.height) > 2) { // Math.abs(currentHeight - this.savedState.height) > 2) {
// console.log(`[定时检查] 强制调整窗口大小: 当前=${currentWidth}x${currentHeight}, 目标=${this.savedState.width}x${this.savedState.height}`); // console.log(`[定时检查] 强制调整窗口大小: 当前=${currentWidth}x${currentHeight}, 目标=${this.savedState.width}x${this.savedState.height}`);
// // 临时禁用minimum size限制 // // 临时禁用minimum size限制
// const [minWidth, minHeight] = win.getMinimumSize(); // const [minWidth, minHeight] = win.getMinimumSize();
// win.setMinimumSize(1, 1); // win.setMinimumSize(1, 1);
// // 强制设置正确大小 // // 强制设置正确大小
// win.setSize(this.savedState.width, this.savedState.height, false); // win.setSize(this.savedState.width, this.savedState.height, false);
// // 恢复原始minimum size // // 恢复原始minimum size
// win.setMinimumSize(minWidth, minHeight); // win.setMinimumSize(minWidth, minHeight);
// // 验证尺寸设置是否成功 // // 验证尺寸设置是否成功
// const [newWidth, newHeight] = win.getSize(); // const [newWidth, newHeight] = win.getSize();
// if (Math.abs(newWidth - this.savedState.width) <= 1 && // if (Math.abs(newWidth - this.savedState.width) <= 1 &&
// Math.abs(newHeight - this.savedState.height) <= 1) { // Math.abs(newHeight - this.savedState.height) <= 1) {
// console.log(`窗口大小已成功调整为目标尺寸: ${newWidth}x${newHeight}`); // console.log(`窗口大小已成功调整为目标尺寸: ${newWidth}x${newHeight}`);
// } // }
// } // }
// this.enforceCount++; // this.enforceCount++;
// }, 50); // }, 50);
// } // }
/** /**
* 获取窗口创建选项 * 获取窗口创建选项
*/ */
@@ -270,10 +277,10 @@ class WindowSizeManager {
if (!this.isInitialized && app.isReady()) { if (!this.isInitialized && app.isReady()) {
this.initialize(); this.initialize();
} }
// 读取保存的状态 // 读取保存的状态
const savedState = this.getWindowState(); const savedState = this.getWindowState();
// 准备选项 // 准备选项
const options: Electron.BrowserWindowConstructorOptions = { const options: Electron.BrowserWindowConstructorOptions = {
width: savedState?.width || DEFAULT_MAIN_WIDTH, width: savedState?.width || DEFAULT_MAIN_WIDTH,
@@ -287,7 +294,7 @@ class WindowSizeManager {
contextIsolation: true contextIsolation: true
} }
}; };
// 如果有保存的位置,且位置有效,则使用该位置 // 如果有保存的位置,且位置有效,则使用该位置
if (savedState?.x !== undefined && savedState?.y !== undefined && app.isReady()) { if (savedState?.x !== undefined && savedState?.y !== undefined && app.isReady()) {
if (this.isPositionVisible(savedState.x, savedState.y)) { if (this.isPositionVisible(savedState.x, savedState.y)) {
@@ -295,49 +302,57 @@ class WindowSizeManager {
options.y = savedState.y; options.y = savedState.y;
} }
} }
console.log(`窗口创建选项: 大小=${options.width}x${options.height}, 位置=(${options.x}, ${options.y})`); console.log(
`窗口创建选项: 大小=${options.width}x${options.height}, 位置=(${options.x}, ${options.y})`
);
return options; return options;
} }
/** /**
* 应用窗口初始状态 * 应用窗口初始状态
* 在窗口创建后调用 * 在窗口创建后调用
*/ */
applyInitialState(win: BrowserWindow): void { applyInitialState(win: BrowserWindow): void {
const savedState = this.getWindowState(); const savedState = this.getWindowState();
if (!savedState) { if (!savedState) {
win.center(); win.center();
return; return;
} }
// 如果需要最大化,直接最大化 // 如果需要最大化,直接最大化
if (savedState.isMaximized) { if (savedState.isMaximized) {
console.log('应用已保存的最大化状态'); console.log('应用已保存的最大化状态');
win.maximize(); win.maximize();
} }
// 如果位置无效,则居中显示 // 如果位置无效,则居中显示
else if (!app.isReady() || savedState.x === undefined || savedState.y === undefined || else if (
!this.isPositionVisible(savedState.x, savedState.y)) { !app.isReady() ||
savedState.x === undefined ||
savedState.y === undefined ||
!this.isPositionVisible(savedState.x, savedState.y)
) {
console.log('保存的位置无效,窗口居中显示'); console.log('保存的位置无效,窗口居中显示');
win.center(); win.center();
} }
} }
/** /**
* 保存窗口状态 * 保存窗口状态
*/ */
saveWindowState(win: BrowserWindow): WindowState { saveWindowState(win: BrowserWindow): WindowState {
// 如果窗口已销毁,则返回之前的状态或默认状态 // 如果窗口已销毁,则返回之前的状态或默认状态
console.log('win.isDestroyed()',win.isDestroyed()) console.log('win.isDestroyed()', win.isDestroyed());
if (win.isDestroyed()) { if (win.isDestroyed()) {
return this.savedState || { return (
width: DEFAULT_MAIN_WIDTH, this.savedState || {
height: DEFAULT_MAIN_HEIGHT, width: DEFAULT_MAIN_WIDTH,
isMaximized: false height: DEFAULT_MAIN_HEIGHT,
}; isMaximized: false
}
);
} }
// 检查是否是mini模式窗口根据窗口大小判断 // 检查是否是mini模式窗口根据窗口大小判断
@@ -352,9 +367,10 @@ class WindowSizeManager {
// 由于 Electron 的限制,最大化状态下 getBounds() 可能不准确 // 由于 Electron 的限制,最大化状态下 getBounds() 可能不准确
// 所以我们尽量保留之前保存的非最大化时的大小 // 所以我们尽量保留之前保存的非最大化时的大小
const currentBounds = win.getBounds(); const currentBounds = win.getBounds();
const previousSize = this.savedState && !this.savedState.isMaximized const previousSize =
? { width: this.savedState.width, height: this.savedState.height } this.savedState && !this.savedState.isMaximized
: { width: currentBounds.width, height: currentBounds.height }; ? { width: this.savedState.width, height: this.savedState.height }
: { width: currentBounds.width, height: currentBounds.height };
state = { state = {
width: previousSize.width, width: previousSize.width,
@@ -363,19 +379,18 @@ class WindowSizeManager {
y: currentBounds.y, y: currentBounds.y,
isMaximized: true isMaximized: true
}; };
console.log('state IsMaximized',state) console.log('state IsMaximized', state);
} else if (win.isMinimized()) {
}
else if (win.isMinimized()) {
// 最小化状态下不保存窗口大小,因为可能不准确 // 最小化状态下不保存窗口大小,因为可能不准确
console.log('state IsMinimized',this.savedState) console.log('state IsMinimized', this.savedState);
return this.savedState || { return (
width: DEFAULT_MAIN_WIDTH, this.savedState || {
height: DEFAULT_MAIN_HEIGHT, width: DEFAULT_MAIN_WIDTH,
isMaximized: false height: DEFAULT_MAIN_HEIGHT,
}; isMaximized: false
} }
else { );
} else {
// 正常状态下保存当前大小和位置 // 正常状态下保存当前大小和位置
const [width, height] = win.getSize(); const [width, height] = win.getSize();
const [x, y] = win.getPosition(); const [x, y] = win.getPosition();
@@ -387,7 +402,7 @@ class WindowSizeManager {
y, y,
isMaximized: false isMaximized: false
}; };
console.log('state IsNormal',state) console.log('state IsNormal', state);
} }
// 如果是mini模式不保存到持久化存储只返回状态用于内存中的恢复 // 如果是mini模式不保存到持久化存储只返回状态用于内存中的恢复
@@ -402,11 +417,11 @@ class WindowSizeManager {
// 更新内部状态 // 更新内部状态
this.savedState = state; this.savedState = state;
console.log('state',state) console.log('state', state);
return state; return state;
} }
/** /**
* 获取保存的窗口状态 * 获取保存的窗口状态
*/ */
@@ -432,8 +447,6 @@ class WindowSizeManager {
return validatedState; return validatedState;
} }
/** /**
* 检查位置是否在可见屏幕范围内 * 检查位置是否在可见屏幕范围内
*/ */
@@ -441,18 +454,13 @@ class WindowSizeManager {
if (!app.isReady()) { if (!app.isReady()) {
return false; return false;
} }
try { try {
const displays = screen.getAllDisplays(); const displays = screen.getAllDisplays();
for (const display of displays) { for (const display of displays) {
const { x: screenX, y: screenY, width, height } = display.workArea; const { x: screenX, y: screenY, width, height } = display.workArea;
if ( if (x >= screenX && x < screenX + width && y >= screenY && y < screenY + height) {
x >= screenX &&
x < screenX + width &&
y >= screenY &&
y < screenY + height
) {
return true; return true;
} }
} }
@@ -460,10 +468,10 @@ class WindowSizeManager {
console.error('检查位置可见性失败:', error); console.error('检查位置可见性失败:', error);
return false; return false;
} }
return false; return false;
} }
/** /**
* 计算适合当前缩放比的缩放因子 * 计算适合当前缩放比的缩放因子
*/ */
@@ -472,14 +480,14 @@ class WindowSizeManager {
if (!app.isReady()) { if (!app.isReady()) {
return 1; return 1;
} }
try { try {
// 获取系统的缩放因子 // 获取系统的缩放因子
const { scaleFactor } = screen.getPrimaryDisplay(); const { scaleFactor } = screen.getPrimaryDisplay();
// 缩放因子默认为1 // 缩放因子默认为1
let zoomFactor = 1; let zoomFactor = 1;
// 只在高DPI情况下调整 // 只在高DPI情况下调整
if (scaleFactor > 1) { if (scaleFactor > 1) {
// 自定义逻辑来根据不同的缩放比例进行调整 // 自定义逻辑来根据不同的缩放比例进行调整
@@ -500,38 +508,40 @@ class WindowSizeManager {
zoomFactor = 1; zoomFactor = 1;
} }
} }
// 获取用户的自定义缩放设置(如果有) // 获取用户的自定义缩放设置(如果有)
const userZoomFactor = this.store.get('set.contentZoomFactor') as number | undefined; const userZoomFactor = this.store.get('set.contentZoomFactor') as number | undefined;
if (userZoomFactor) { if (userZoomFactor) {
zoomFactor = userZoomFactor; zoomFactor = userZoomFactor;
} }
return zoomFactor; return zoomFactor;
} catch (error) { } catch (error) {
console.error('计算内容缩放因子失败:', error); console.error('计算内容缩放因子失败:', error);
return 1; return 1;
} }
} }
/** /**
* 应用页面内容缩放 * 应用页面内容缩放
*/ */
applyContentZoom(win: BrowserWindow): void { applyContentZoom(win: BrowserWindow): void {
const zoomFactor = this.calculateContentZoomFactor(); const zoomFactor = this.calculateContentZoomFactor();
win.webContents.setZoomFactor(zoomFactor); win.webContents.setZoomFactor(zoomFactor);
if (app.isReady()) { if (app.isReady()) {
try { try {
console.log(`应用页面缩放因子: ${zoomFactor}, 系统缩放比: ${screen.getPrimaryDisplay().scaleFactor}`); console.log(
`应用页面缩放因子: ${zoomFactor}, 系统缩放比: ${screen.getPrimaryDisplay().scaleFactor}`
);
} catch (error) { } catch (error) {
console.log(`应用页面缩放因子: ${zoomFactor}`); console.error('获取系统缩放比失败:', error);
} }
} else { } else {
console.log(`应用页面缩放因子: ${zoomFactor}`); console.log(`应用页面缩放因子: ${zoomFactor}`);
} }
} }
/** /**
* 初始化IPC消息处理程序 * 初始化IPC消息处理程序
*/ */
@@ -541,25 +551,25 @@ class WindowSizeManager {
console.log('IPC处理程序已注册跳过重复注册'); console.log('IPC处理程序已注册跳过重复注册');
return; return;
} }
console.log('注册窗口大小相关的IPC处理程序'); console.log('注册窗口大小相关的IPC处理程序');
// 标记为已注册 // 标记为已注册
ipcHandlersRegistered = true; ipcHandlersRegistered = true;
// 安全地移除已存在的处理程序(如果有) // 安全地移除已存在的处理程序(如果有)
const removeHandlerSafely = (channel: string) => { const removeHandlerSafely = (channel: string) => {
try { try {
ipcMain.removeHandler(channel); ipcMain.removeHandler(channel);
} catch (error) { } catch (error) {
// 忽略错误,处理程序可能不存在 console.warn(`移除IPC处理程序 ${channel} 时出错:`, error);
} }
}; };
// 为需要使用handle方法的通道先移除已有处理程序 // 为需要使用handle方法的通道先移除已有处理程序
removeHandlerSafely('get-content-zoom'); removeHandlerSafely('get-content-zoom');
removeHandlerSafely('get-system-scale-factor'); removeHandlerSafely('get-system-scale-factor');
// 注册新的处理程序 // 注册新的处理程序
ipcMain.on('set-content-zoom', (event, zoomFactor) => { ipcMain.on('set-content-zoom', (event, zoomFactor) => {
const win = BrowserWindow.fromWebContents(event.sender); const win = BrowserWindow.fromWebContents(event.sender);
@@ -568,7 +578,7 @@ class WindowSizeManager {
this.store.set('set.contentZoomFactor', zoomFactor); this.store.set('set.contentZoomFactor', zoomFactor);
} }
}); });
ipcMain.handle('get-content-zoom', (event) => { ipcMain.handle('get-content-zoom', (event) => {
const win = BrowserWindow.fromWebContents(event.sender); const win = BrowserWindow.fromWebContents(event.sender);
if (win && !win.isDestroyed()) { if (win && !win.isDestroyed()) {
@@ -576,12 +586,12 @@ class WindowSizeManager {
} }
return 1; return 1;
}); });
ipcMain.handle('get-system-scale-factor', () => { ipcMain.handle('get-system-scale-factor', () => {
if (!app.isReady()) { if (!app.isReady()) {
return 1; return 1;
} }
try { try {
return screen.getPrimaryDisplay().scaleFactor; return screen.getPrimaryDisplay().scaleFactor;
} catch (error) { } catch (error) {
@@ -589,7 +599,7 @@ class WindowSizeManager {
return 1; return 1;
} }
}); });
ipcMain.on('reset-content-zoom', (event) => { ipcMain.on('reset-content-zoom', (event) => {
const win = BrowserWindow.fromWebContents(event.sender); const win = BrowserWindow.fromWebContents(event.sender);
if (win && !win.isDestroyed()) { if (win && !win.isDestroyed()) {
@@ -597,25 +607,25 @@ class WindowSizeManager {
this.applyContentZoom(win); this.applyContentZoom(win);
} }
}); });
ipcMain.on('resize-window', (event, width, height) => { ipcMain.on('resize-window', (event, width, height) => {
const win = BrowserWindow.fromWebContents(event.sender); const win = BrowserWindow.fromWebContents(event.sender);
if (win && !win.isDestroyed()) { if (win && !win.isDestroyed()) {
console.log(`接收到调整窗口大小请求: ${width}x${height}`); console.log(`接收到调整窗口大小请求: ${width}x${height}`);
// 确保尺寸不小于最小值 // 确保尺寸不小于最小值
const adjustedWidth = Math.max(width, MIN_WIDTH); const adjustedWidth = Math.max(width, MIN_WIDTH);
const adjustedHeight = Math.max(height, MIN_HEIGHT); const adjustedHeight = Math.max(height, MIN_HEIGHT);
// 设置窗口的大小 // 设置窗口的大小
win.setSize(adjustedWidth, adjustedHeight); win.setSize(adjustedWidth, adjustedHeight);
console.log(`窗口大小已调整为: ${adjustedWidth}x${adjustedHeight}`); console.log(`窗口大小已调整为: ${adjustedWidth}x${adjustedHeight}`);
// 保存窗口状态 // 保存窗口状态
this.saveWindowState(win); this.saveWindowState(win);
} }
}); });
ipcMain.on('resize-mini-window', (event, showPlaylist) => { ipcMain.on('resize-mini-window', (event, showPlaylist) => {
const win = BrowserWindow.fromWebContents(event.sender); const win = BrowserWindow.fromWebContents(event.sender);
if (win && !win.isDestroyed()) { if (win && !win.isDestroyed()) {
@@ -632,7 +642,7 @@ class WindowSizeManager {
} }
} }
}); });
// 只在app ready后设置显示器变化监听 // 只在app ready后设置显示器变化监听
if (app.isReady()) { if (app.isReady()) {
// 监听显示器变化事件 // 监听显示器变化事件
@@ -642,13 +652,13 @@ class WindowSizeManager {
if (changedMetrics.includes('scaleFactor')) { if (changedMetrics.includes('scaleFactor')) {
this.applyContentZoom(this.mainWindow); this.applyContentZoom(this.mainWindow);
} }
// 重新初始化最小尺寸 // 重新初始化最小尺寸
this.initMinimumWindowSize(); this.initMinimumWindowSize();
} }
}); });
} }
// 监听 store 中的缩放设置变化 // 监听 store 中的缩放设置变化
this.store.onDidChange('set.contentZoomFactor', () => { this.store.onDidChange('set.contentZoomFactor', () => {
if (this.mainWindow && !this.mainWindow.isDestroyed()) { if (this.mainWindow && !this.mainWindow.isDestroyed()) {
@@ -712,4 +722,3 @@ export const initWindowSizeHandlers = (mainWindow: BrowserWindow | null): void =
export const calculateMinimumWindowSize = (): { minWidth: number; minHeight: number } => { export const calculateMinimumWindowSize = (): { minWidth: number; minHeight: number } => {
return { minWidth: MIN_WIDTH, minHeight: MIN_HEIGHT }; return { minWidth: MIN_WIDTH, minHeight: MIN_HEIGHT };
}; };

View File

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

View File

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

View File

@@ -45,33 +45,33 @@ function ensureDataStructure(data: any): any {
album: { name: '' } album: { name: '' }
}; };
} }
// 确保name字段存在 // 确保name字段存在
if (data.name === undefined || data.name === null) { if (data.name === undefined || data.name === null) {
data.name = ''; data.name = '';
} }
// 确保artists字段存在且为数组 // 确保artists字段存在且为数组
if (!data.artists || !Array.isArray(data.artists)) { if (!data.artists || !Array.isArray(data.artists)) {
data.artists = data.ar && Array.isArray(data.ar) ? data.ar : []; data.artists = data.ar && Array.isArray(data.ar) ? data.ar : [];
} }
// 确保artists中的每个元素都有name属性 // 确保artists中的每个元素都有name属性
if (data.artists.length > 0) { if (data.artists.length > 0) {
data.artists = data.artists.map(artist => { data.artists = data.artists.map((artist) => {
return artist ? { name: artist.name || '' } : { name: '' }; return artist ? { name: artist.name || '' } : { name: '' };
}); });
} }
// 确保album对象存在并有name属性 // 确保album对象存在并有name属性
if (!data.album || typeof data.album !== 'object') { if (!data.album || typeof data.album !== 'object') {
data.album = data.al && typeof data.al === 'object' ? data.al : { name: '' }; data.album = data.al && typeof data.al === 'object' ? data.al : { name: '' };
} }
if (!data.album.name) { if (!data.album.name) {
data.album.name = ''; data.album.name = '';
} }
return data; return data;
} }
@@ -89,15 +89,14 @@ const unblockMusic = async (
retryCount = 1, retryCount = 1,
enabledPlatforms?: Platform[] enabledPlatforms?: Platform[]
): Promise<UnblockResult> => { ): Promise<UnblockResult> => {
// 过滤 enabledPlatforms确保只包含 ALL_PLATFORMS 中存在的平台 // 过滤 enabledPlatforms确保只包含 ALL_PLATFORMS 中存在的平台
const filteredPlatforms = enabledPlatforms const filteredPlatforms = enabledPlatforms
? enabledPlatforms.filter(platform => ALL_PLATFORMS.includes(platform)) ? enabledPlatforms.filter((platform) => ALL_PLATFORMS.includes(platform))
: ALL_PLATFORMS; : ALL_PLATFORMS;
// 处理歌曲数据,确保数据结构完整 // 处理歌曲数据,确保数据结构完整
const processedSongData = ensureDataStructure(songData); const processedSongData = ensureDataStructure(songData);
const retry = async (attempt: number): Promise<UnblockResult> => { const retry = async (attempt: number): Promise<UnblockResult> => {
try { try {
const data = await match(parseInt(String(id), 10), filteredPlatforms, processedSongData); const data = await match(parseInt(String(id), 10), filteredPlatforms, processedSongData);

View File

@@ -16,7 +16,8 @@ const api = {
openLyric: () => ipcRenderer.send('open-lyric'), openLyric: () => ipcRenderer.send('open-lyric'),
sendLyric: (data) => ipcRenderer.send('send-lyric', data), sendLyric: (data) => ipcRenderer.send('send-lyric', data),
sendSong: (data) => ipcRenderer.send('update-current-song', 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) => { onLyricWindowClosed: (callback: () => void) => {
ipcRenderer.on('lyric-window-closed', () => callback()); ipcRenderer.on('lyric-window-closed', () => callback());

View File

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

View File

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

View File

@@ -1,4 +1,5 @@
import axios from 'axios'; import axios from 'axios';
import type { MusicSourceType } from '@/type/music'; import type { MusicSourceType } from '@/type/music';
/** /**
@@ -19,8 +20,8 @@ export interface ParsedMusicResult {
params: { params: {
id: number; id: number;
type: string; type: string;
} };
} };
} }
/** /**
@@ -32,8 +33,8 @@ export interface ParsedMusicResult {
* @returns 解析后的音乐URL及相关信息 * @returns 解析后的音乐URL及相关信息
*/ */
export const parseFromGDMusic = async ( export const parseFromGDMusic = async (
id: number, id: number,
data: any, data: any,
quality: string = '999', quality: string = '999',
timeout: number = 15000 timeout: number = 15000
): Promise<ParsedMusicResult | null> => { ): Promise<ParsedMusicResult | null> => {
@@ -53,32 +54,31 @@ export const parseFromGDMusic = async (
console.error('GD音乐台解析歌曲数据为空'); console.error('GD音乐台解析歌曲数据为空');
throw new Error('歌曲数据为空'); throw new Error('歌曲数据为空');
} }
const songName = data.name || ''; const songName = data.name || '';
let artistNames = ''; let artistNames = '';
// 处理不同的艺术家字段结构 // 处理不同的艺术家字段结构
if (data.artists && Array.isArray(data.artists)) { 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)) { } 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) { } else if (data.artist) {
artistNames = typeof data.artist === 'string' ? data.artist : ''; artistNames = typeof data.artist === 'string' ? data.artist : '';
} }
const searchQuery = `${songName} ${artistNames}`.trim(); const searchQuery = `${songName} ${artistNames}`.trim();
if (!searchQuery || searchQuery.length < 2) { if (!searchQuery || searchQuery.length < 2) {
console.error('GD音乐台解析搜索查询过短', { name: songName, artists: artistNames }); console.error('GD音乐台解析搜索查询过短', { name: songName, artists: artistNames });
throw new Error('搜索查询过短'); throw new Error('搜索查询过短');
} }
// 所有可用的音乐源 netease、joox、tidal // 所有可用的音乐源 netease、joox、tidal
const allSources = ['joox', 'tidal', 'netease' const allSources = ['joox', 'tidal', 'netease'] as MusicSourceType[];
] as MusicSourceType[];
console.log('GD音乐台开始搜索:', searchQuery); console.log('GD音乐台开始搜索:', searchQuery);
// 依次尝试所有音源 // 依次尝试所有音源
for (const source of allSources) { for (const source of allSources) {
try { try {
@@ -109,7 +109,7 @@ export const parseFromGDMusic = async (
continue; continue;
} }
} }
console.log('GD音乐台所有音源均解析失败'); console.log('GD音乐台所有音源均解析失败');
return null; return null;
})(), })(),
@@ -142,32 +142,32 @@ const baseUrl = 'https://music-api.gdstudio.xyz/api.php';
* @returns 音乐URL结果 * @returns 音乐URL结果
*/ */
async function searchAndGetUrl( async function searchAndGetUrl(
source: MusicSourceType, source: MusicSourceType,
searchQuery: string, searchQuery: string,
quality: string quality: string
): Promise<GDMusicUrlResult | null> { ): Promise<GDMusicUrlResult | null> {
// 1. 搜索歌曲 // 1. 搜索歌曲
const searchUrl = `${baseUrl}?types=search&source=${source}&name=${encodeURIComponent(searchQuery)}&count=1&pages=1`; const searchUrl = `${baseUrl}?types=search&source=${source}&name=${encodeURIComponent(searchQuery)}&count=1&pages=1`;
console.log(`GD音乐台尝试音源 ${source} 搜索:`, searchUrl); console.log(`GD音乐台尝试音源 ${source} 搜索:`, searchUrl);
const searchResponse = await axios.get(searchUrl, { timeout: 5000 }); const searchResponse = await axios.get(searchUrl, { timeout: 5000 });
if (searchResponse.data && Array.isArray(searchResponse.data) && searchResponse.data.length > 0) { if (searchResponse.data && Array.isArray(searchResponse.data) && searchResponse.data.length > 0) {
const firstResult = searchResponse.data[0]; const firstResult = searchResponse.data[0];
if (!firstResult || !firstResult.id) { if (!firstResult || !firstResult.id) {
console.log(`GD音乐台 ${source} 搜索结果无效`); console.log(`GD音乐台 ${source} 搜索结果无效`);
return null; return null;
} }
const trackId = firstResult.id; const trackId = firstResult.id;
const trackSource = firstResult.source || source; const trackSource = firstResult.source || source;
// 2. 获取歌曲URL // 2. 获取歌曲URL
const songUrl = `${baseUrl}?types=url&source=${trackSource}&id=${trackId}&br=${quality}`; const songUrl = `${baseUrl}?types=url&source=${trackSource}&id=${trackId}&br=${quality}`;
console.log(`GD音乐台尝试获取 ${trackSource} 歌曲URL:`, songUrl); console.log(`GD音乐台尝试获取 ${trackSource} 歌曲URL:`, songUrl);
const songResponse = await axios.get(songUrl, { timeout: 5000 }); const songResponse = await axios.get(songUrl, { timeout: 5000 });
if (songResponse.data && songResponse.data.url) { if (songResponse.data && songResponse.data.url) {
return { return {
url: songResponse.data.url, url: songResponse.data.url,
@@ -183,4 +183,4 @@ async function searchAndGetUrl(
console.log(`GD音乐台 ${source} 搜索结果为空`); console.log(`GD音乐台 ${source} 搜索结果为空`);
return null; return null;
} }
} }

View File

@@ -1,13 +1,15 @@
import { cloneDeep } from 'lodash';
import { musicDB } from '@/hooks/MusicHook'; import { musicDB } from '@/hooks/MusicHook';
import { useSettingsStore, useUserStore } from '@/store'; import { useSettingsStore, useUserStore } from '@/store';
import type { ILyric } from '@/type/lyric'; import type { ILyric } from '@/type/lyric';
import type { SongResult } from '@/type/music';
import { isElectron } from '@/utils'; import { isElectron } from '@/utils';
import request from '@/utils/request'; import request from '@/utils/request';
import requestMusic from '@/utils/request_music'; 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 { searchAndGetBilibiliAudioUrl } from './bilibili';
import { parseFromGDMusic } from './gdmusic';
const { addData, getData, deleteData } = musicDB; const { addData, getData, deleteData } = musicDB;
@@ -89,12 +91,13 @@ export const getMusicLrc = async (id: number) => {
*/ */
const getBilibiliAudio = async (data: SongResult) => { const getBilibiliAudio = async (data: SongResult) => {
const songName = data?.name || ''; 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 albumName = data?.al && typeof data.al === 'object' && data.al?.name ? data.al.name : '';
const searchQuery = [songName, artistName, albumName].filter(Boolean).join(' ').trim(); const searchQuery = [songName, artistName, albumName].filter(Boolean).join(' ').trim();
console.log('开始搜索bilibili音频:', searchQuery); console.log('开始搜索bilibili音频:', searchQuery);
const url = await searchAndGetBilibiliAudioUrl(searchQuery); const url = await searchAndGetBilibiliAudioUrl(searchQuery);
return { return {
data: { data: {
@@ -131,7 +134,7 @@ const getGDMusicAudio = async (id: number, data: SongResult) => {
* @returns 解析结果 * @returns 解析结果
*/ */
const getUnblockMusicAudio = (id: number, data: SongResult, sources: any[]) => { 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); console.log(`使用unblockMusic解析音源:`, filteredSources);
return window.api.unblockMusic(id, cloneDeep(data), cloneDeep(filteredSources)); return window.api.unblockMusic(id, cloneDeep(data), cloneDeep(filteredSources));
}; };
@@ -144,17 +147,17 @@ const getUnblockMusicAudio = (id: number, data: SongResult, sources: any[]) => {
*/ */
export const getParsingMusicUrl = async (id: number, data: SongResult) => { export const getParsingMusicUrl = async (id: number, data: SongResult) => {
const settingStore = useSettingsStore(); const settingStore = useSettingsStore();
// 如果禁用了音乐解析功能,则直接返回空结果 // 如果禁用了音乐解析功能,则直接返回空结果
if (!settingStore.setData.enableMusicUnblock) { if (!settingStore.setData.enableMusicUnblock) {
return Promise.resolve({ data: { code: 404, message: '音乐解析功能已禁用' } }); return Promise.resolve({ data: { code: 404, message: '音乐解析功能已禁用' } });
} }
// 1. 确定使用的音源列表(自定义或全局) // 1. 确定使用的音源列表(自定义或全局)
const songId = String(id); const songId = String(id);
const savedSourceStr = localStorage.getItem(`song_source_${songId}`); const savedSourceStr = localStorage.getItem(`song_source_${songId}`);
let musicSources: any[] = []; let musicSources: any[] = [];
try { try {
if (savedSourceStr) { if (savedSourceStr) {
// 使用自定义音源 // 使用自定义音源
@@ -172,14 +175,14 @@ export const getParsingMusicUrl = async (id: number, data: SongResult) => {
console.error('解析音源设置失败,使用全局设置', e); console.error('解析音源设置失败,使用全局设置', e);
musicSources = settingStore.setData.enabledMusicSources || []; musicSources = settingStore.setData.enabledMusicSources || [];
} }
// 2. 按优先级解析 // 2. 按优先级解析
// 2.1 Bilibili解析(优先级最高) // 2.1 Bilibili解析(优先级最高)
if (musicSources.includes('bilibili')) { if (musicSources.includes('bilibili')) {
return await getBilibiliAudio(data); return await getBilibiliAudio(data);
} }
// 2.2 GD音乐台解析 // 2.2 GD音乐台解析
if (musicSources.includes('gdmusic')) { if (musicSources.includes('gdmusic')) {
const gdResult = await getGDMusicAudio(id, data); const gdResult = await getGDMusicAudio(id, data);
@@ -187,12 +190,12 @@ export const getParsingMusicUrl = async (id: number, data: SongResult) => {
// GD解析失败继续下一步 // GD解析失败继续下一步
console.log('GD音乐台解析失败尝试使用其他音源'); console.log('GD音乐台解析失败尝试使用其他音源');
} }
console.log('musicSources',musicSources) console.log('musicSources', musicSources);
// 2.3 使用unblockMusic解析其他音源 // 2.3 使用unblockMusic解析其他音源
if (isElectron && musicSources.length > 0) { if (isElectron && musicSources.length > 0) {
return getUnblockMusicAudio(id, data, musicSources); return getUnblockMusicAudio(id, data, musicSources);
} }
// 3. 后备方案使用API请求 // 3. 后备方案使用API请求
console.log('无可用音源或不在Electron环境中使用API请求'); console.log('无可用音源或不在Electron环境中使用API请求');
return requestMusic.get<any>('/music', { params: { id } }); return requestMusic.get<any>('/music', { params: { id } });

View File

@@ -24,4 +24,4 @@ export function getImportTaskStatus(id: string | number) {
method: 'get', method: 'get',
params: { id } params: { id }
}); });
} }

View File

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

View File

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

File diff suppressed because one or more lines are too long

View File

@@ -1,7 +1,8 @@
<template> <template>
<div class="eq-control"> <div class="eq-control">
<div class="eq-header"> <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 type="warning" size="small" round v-if="!isElectron">
桌面版可用网页端不支持 桌面版可用网页端不支持
</n-tag> </n-tag>

View File

@@ -27,18 +27,10 @@
<div class="warning-message"> <div class="warning-message">
<h3>获取完整体验</h3> <h3>获取完整体验</h3>
<p class="platform-support"> <p class="platform-support">
<span> <span> <i class="ri-window-line mr-1"></i>Windows 10+ </span>
<i class="ri-window-line mr-1"></i>Windows 10+ <span> <i class="ri-apple-line mr-1"></i>macOS </span>
</span> <span> <i class="ri-ubuntu-line mr-1"></i>Linux </span>
<span> <span> <i class="ri-android-line mr-1"></i>Android </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>
<p class="description"> <p class="description">
下载桌面应用以获得最佳音乐体验包含完整功能与更高音质 下载桌面应用以获得最佳音乐体验包含完整功能与更高音质
@@ -47,7 +39,11 @@
</div> </div>
<div class="action-links"> <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> 查看使用文档 <i class="ri-file-text-line mr-1"></i> 查看使用文档
</a> </a>
<a href="http://donate.alger.fun/download" target="_blank" class="download-link"> <a href="http://donate.alger.fun/download" target="_blank" class="download-link">
@@ -59,7 +55,7 @@
<img class="qrcode" src="@/assets/gzh.png" alt="公众号" /> <img class="qrcode" src="@/assets/gzh.png" alt="公众号" />
<p>关注公众号获取最新版本与更新信息</p> <p>关注公众号获取最新版本与更新信息</p>
</div> </div>
<div class="support-section"> <div class="support-section">
<h4>支持项目</h4> <h4>支持项目</h4>
<p class="support-desc">您的支持是我们持续改进的动力</p> <p class="support-desc">您的支持是我们持续改进的动力</p>
@@ -78,10 +74,12 @@
</div> </div>
</div> </div>
</div> </div>
<div class="drawer-actions"> <div class="drawer-actions">
<n-button secondary class="action-button" @click="markAsDonated">已支持</n-button> <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> </div>
</div> </div>
@@ -90,7 +88,8 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted } from 'vue'; import { onMounted, ref } from 'vue';
import { isMobile } from '@/utils'; import { isMobile } from '@/utils';
// 控制抽屉显示状态 // 控制抽屉显示状态
@@ -117,7 +116,7 @@ const markAsDonated = () => {
onMounted(() => { onMounted(() => {
// 优先判断是否永久不再提示 // 优先判断是否永久不再提示
if (localStorage.getItem('trafficDonated4Never')) return; if (localStorage.getItem('trafficDonated4Never')) return;
// 判断一天后提醒 // 判断一天后提醒
const remindLaterTime = localStorage.getItem('trafficDonated4RemindLater'); const remindLaterTime = localStorage.getItem('trafficDonated4RemindLater');
if (remindLaterTime) { if (remindLaterTime) {
@@ -126,7 +125,7 @@ onMounted(() => {
const hoursDiff = (now.getTime() - lastRemind.getTime()) / (1000 * 60 * 60); const hoursDiff = (now.getTime() - lastRemind.getTime()) / (1000 * 60 * 60);
if (hoursDiff < 24) return; if (hoursDiff < 24) return;
} }
// 延迟20秒显示 // 延迟20秒显示
setTimeout(() => { setTimeout(() => {
showDrawer.value = true; showDrawer.value = true;
@@ -137,12 +136,12 @@ onMounted(() => {
<style scoped lang="scss"> <style scoped lang="scss">
.traffic-warning-trigger { .traffic-warning-trigger {
display: inline-block; display: inline-block;
.mac-style-button { .mac-style-button {
background-color: rgba(0, 0, 0, 0.05); background-color: rgba(0, 0, 0, 0.05);
color: #333; color: #333;
transition: all 0.2s ease; transition: all 0.2s ease;
&:hover { &:hover {
background-color: rgba(0, 0, 0, 0.1); background-color: rgba(0, 0, 0, 0.1);
} }
@@ -173,7 +172,7 @@ onMounted(() => {
width: 100px; width: 100px;
height: 100px; height: 100px;
margin-bottom: 12px; margin-bottom: 12px;
img { img {
width: 100%; width: 100%;
height: 100%; height: 100%;
@@ -185,21 +184,21 @@ onMounted(() => {
.warning-message { .warning-message {
text-align: center; text-align: center;
max-width: 520px; max-width: 520px;
h3 { h3 {
font-size: 28px; font-size: 28px;
font-weight: 600; font-weight: 600;
margin-bottom: 18px; margin-bottom: 18px;
color: #333; color: #333;
} }
.platform-support { .platform-support {
display: flex; display: flex;
justify-content: center; justify-content: center;
gap: 20px; gap: 20px;
flex-wrap: wrap; flex-wrap: wrap;
margin-bottom: 16px; margin-bottom: 16px;
span { span {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -207,7 +206,7 @@ onMounted(() => {
color: #444; color: #444;
} }
} }
.description { .description {
font-size: 16px; font-size: 16px;
line-height: 1.6; line-height: 1.6;
@@ -222,7 +221,7 @@ onMounted(() => {
justify-content: center; justify-content: center;
flex-wrap: wrap; flex-wrap: wrap;
margin: 6px 0; margin: 6px 0;
a { a {
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
@@ -231,20 +230,20 @@ onMounted(() => {
font-size: 16px; font-size: 16px;
text-decoration: none; text-decoration: none;
transition: all 0.2s ease; transition: all 0.2s ease;
&.doc-link { &.doc-link {
color: #555; color: #555;
background-color: rgba(0, 0, 0, 0.05); background-color: rgba(0, 0, 0, 0.05);
&:hover { &:hover {
background-color: rgba(0, 0, 0, 0.1); background-color: rgba(0, 0, 0, 0.1);
} }
} }
&.download-link { &.download-link {
color: #fff; color: #fff;
background-color: #007aff; background-color: #007aff;
&:hover { &:hover {
background-color: #0062cc; background-color: #0062cc;
} }
@@ -259,7 +258,7 @@ onMounted(() => {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
gap: 10px; gap: 10px;
.qrcode { .qrcode {
width: 180px; width: 180px;
height: 180px; height: 180px;
@@ -268,7 +267,7 @@ onMounted(() => {
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
background: white; background: white;
} }
p { p {
margin-top: 14px; margin-top: 14px;
font-size: 15px; font-size: 15px;
@@ -279,14 +278,14 @@ onMounted(() => {
.support-section { .support-section {
width: 100%; width: 100%;
text-align: center; text-align: center;
h4 { h4 {
font-size: 22px; font-size: 22px;
font-weight: 600; font-weight: 600;
color: #333; color: #333;
margin-bottom: 8px; margin-bottom: 8px;
} }
.support-desc { .support-desc {
font-size: 15px; font-size: 15px;
color: #555; color: #555;
@@ -307,21 +306,21 @@ onMounted(() => {
flex-direction: column; flex-direction: column;
align-items: center; align-items: center;
gap: 10px; gap: 10px;
.payment-icon { .payment-icon {
width: 220px; width: 220px;
height: 220px; height: 220px;
border-radius: 12px; border-radius: 12px;
overflow: hidden; overflow: hidden;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
img { img {
width: 100%; width: 100%;
height: 100%; height: 100%;
object-fit: cover; object-fit: cover;
} }
} }
span { span {
font-size: 15px; font-size: 15px;
color: #444; color: #444;
@@ -341,17 +340,17 @@ onMounted(() => {
padding: 10px; padding: 10px;
background-color: #fff; background-color: #fff;
z-index: 999999999; z-index: 999999999;
.action-button { .action-button {
min-width: 110px; min-width: 110px;
border-radius: 8px; border-radius: 8px;
font-size: 16px; font-size: 16px;
padding: 8px 16px; padding: 8px 16px;
&.primary { &.primary {
background-color: #007aff; background-color: #007aff;
color: white; color: white;
&:hover { &:hover {
background-color: #0062cc; background-color: #0062cc;
} }
@@ -364,48 +363,48 @@ onMounted(() => {
h3 { h3 {
font-size: 20px; font-size: 20px;
} }
.platform-support { .platform-support {
gap: 12px; gap: 12px;
} }
.description { .description {
font-size: 13px; font-size: 13px;
} }
} }
.app-icon { .app-icon {
width: 64px; width: 64px;
height: 64px; height: 64px;
} }
.qrcode-section { .qrcode-section {
.qrcode { .qrcode {
width: 140px; width: 140px;
height: 140px; height: 140px;
} }
} }
.payment-option { .payment-option {
.payment-icon { .payment-icon {
width: 190px; width: 190px;
height: 190px; height: 190px;
} }
} }
.drawer-actions { .drawer-actions {
flex-wrap: wrap; flex-wrap: wrap;
position: fixed; position: fixed;
bottom: 0; bottom: 0;
left: 0; left: 0;
right: 0; right: 0;
padding: 10px; padding: 10px;
background-color: #fff; background-color: #fff;
z-index: 999999999; z-index: 999999999;
.action-button { .action-button {
flex: 1 0 auto; flex: 1 0 auto;
} }
} }
} }
</style> </style>

View File

@@ -4,31 +4,21 @@
<div class="description"> <div class="description">
<p>{{ t('donation.description') }}</p> <p>{{ t('donation.description') }}</p>
<p>{{ t('donation.message') }}</p> <p>{{ t('donation.message') }}</p>
<n-button type="primary" @click="toDonateList"> <n-button type="primary" @click="toDonateList">
<template #icon> <template #icon>
<i class="ri-cup-line"></i> <i class="ri-cup-line"></i>
</template> </template>
{{ t('donation.toDonateList') }} {{ t('donation.toDonateList') }}
</n-button> </n-button>
</div> </div>
<div class="qrcode-grid"> <div class="qrcode-grid">
<div class="qrcode-item"> <div class="qrcode-item">
<n-image <n-image :src="alipay" :alt="t('common.alipay')" class="qrcode-image" preview-disabled />
:src="alipay"
:alt="t('common.alipay')"
class="qrcode-image"
preview-disabled
/>
<span class="qrcode-label">{{ t('common.alipay') }}</span> <span class="qrcode-label">{{ t('common.alipay') }}</span>
</div> </div>
<div class="qrcode-item"> <div class="qrcode-item">
<n-image <n-image :src="wechat" :alt="t('common.wechat')" class="qrcode-image" preview-disabled />
:src="wechat"
:alt="t('common.wechat')"
class="qrcode-image"
preview-disabled
/>
<span class="qrcode-label">{{ t('common.wechat') }}</span> <span class="qrcode-label">{{ t('common.wechat') }}</span>
</div> </div>
</div> </div>
@@ -43,7 +33,7 @@
{{ t('donation.refresh') }} {{ t('donation.refresh') }}
</n-button> </n-button>
</div> </div>
<div class="donation-grid" :class="{ 'grid-expanded': isExpanded }"> <div class="donation-grid" :class="{ 'grid-expanded': isExpanded }">
<div <div
v-for="donor in displayDonors" v-for="donor in displayDonors"
@@ -53,12 +43,7 @@
> >
<div class="card-content"> <div class="card-content">
<div class="donor-avatar"> <div class="donor-avatar">
<n-avatar <n-avatar :src="donor.avatar" :fallback-src="defaultAvatar" round class="avatar-img" />
:src="donor.avatar"
:fallback-src="defaultAvatar"
round
class="avatar-img"
/>
</div> </div>
<div class="donor-info"> <div class="donor-info">
<div class="donor-meta"> <div class="donor-meta">
@@ -68,7 +53,7 @@
<div class="donation-date">{{ donor.date }}</div> <div class="donation-date">{{ donor.date }}</div>
</div> </div>
</div> </div>
<!-- 有留言的情况 --> <!-- 有留言的情况 -->
<n-popover <n-popover
v-if="donor.message" v-if="donor.message"
@@ -90,7 +75,7 @@
<i class="ri-double-quotes-r quote-icon"></i> <i class="ri-double-quotes-r quote-icon"></i>
</div> </div>
</n-popover> </n-popover>
<!-- 没有留言的情况显示占位符 --> <!-- 没有留言的情况显示占位符 -->
<div v-else class="donation-message-placeholder"> <div v-else class="donation-message-placeholder">
<i class="ri-emotion-line"></i> <i class="ri-emotion-line"></i>
@@ -175,7 +160,7 @@ const toDonateList = () => {
.header-container { .header-container {
@apply flex justify-between items-center px-4 py-2; @apply flex justify-between items-center px-4 py-2;
.section-title { .section-title {
@apply text-lg font-medium text-gray-700 dark:text-gray-200; @apply text-lg font-medium text-gray-700 dark:text-gray-200;
} }
@@ -205,7 +190,7 @@ const toDonateList = () => {
@apply border border-gray-200 dark:border-gray-700/10; @apply border border-gray-200 dark:border-gray-700/10;
@apply flex flex-col; @apply flex flex-col;
min-height: 100px; min-height: 100px;
.card-content { .card-content {
@apply flex items-start gap-2 mb-2; @apply flex items-start gap-2 mb-2;
} }
@@ -225,11 +210,11 @@ const toDonateList = () => {
.donor-meta { .donor-meta {
@apply flex justify-between items-center mb-0.5; @apply flex justify-between items-center mb-0.5;
.donor-name { .donor-name {
@apply text-sm font-medium truncate flex-1 mr-1; @apply text-sm font-medium truncate flex-1 mr-1;
} }
.price-tag { .price-tag {
@apply text-xs text-gray-400/80 dark:text-gray-500/80 whitespace-nowrap; @apply text-xs text-gray-400/80 dark:text-gray-500/80 whitespace-nowrap;
} }
@@ -245,19 +230,19 @@ const toDonateList = () => {
@apply bg-gray-100/10 dark:bg-dark-300 rounded; @apply bg-gray-100/10 dark:bg-dark-300 rounded;
@apply flex items-start; @apply flex items-start;
@apply cursor-pointer transition-all duration-200; @apply cursor-pointer transition-all duration-200;
.quote-icon { .quote-icon {
@apply text-gray-300 dark:text-gray-600 flex-shrink-0 opacity-60; @apply text-gray-300 dark:text-gray-600 flex-shrink-0 opacity-60;
&:first-child { &:first-child {
@apply mr-1 self-start; @apply mr-1 self-start;
} }
&:last-child { &:last-child {
@apply ml-1 self-end; @apply ml-1 self-end;
} }
} }
.message-text { .message-text {
@apply flex-1 line-clamp-2; @apply flex-1 line-clamp-2;
} }
@@ -272,7 +257,7 @@ const toDonateList = () => {
@apply bg-gray-100/5 dark:bg-dark-300 rounded; @apply bg-gray-100/5 dark:bg-dark-300 rounded;
@apply flex items-center justify-center gap-1 italic; @apply flex items-center justify-center gap-1 italic;
@apply border border-transparent; @apply border border-transparent;
i { i {
@apply text-gray-300 dark:text-gray-600; @apply text-gray-300 dark:text-gray-600;
} }
@@ -284,11 +269,11 @@ const toDonateList = () => {
.quote-icon { .quote-icon {
@apply text-gray-400 dark:text-gray-500 flex-shrink-0; @apply text-gray-400 dark:text-gray-500 flex-shrink-0;
&:first-child { &:first-child {
@apply mr-1.5 self-start; @apply mr-1.5 self-start;
} }
&:last-child { &:last-child {
@apply ml-1.5 self-end; @apply ml-1.5 self-end;
} }
@@ -305,30 +290,30 @@ const toDonateList = () => {
.qrcode-container { .qrcode-container {
@apply p-5 rounded-lg shadow-sm bg-light-100 dark:bg-gray-800/5 backdrop-blur-sm border border-gray-200 dark:border-gray-700/10; @apply p-5 rounded-lg shadow-sm bg-light-100 dark:bg-gray-800/5 backdrop-blur-sm border border-gray-200 dark:border-gray-700/10;
.description { .description {
@apply text-center text-sm text-gray-600 dark:text-gray-300 mb-4; @apply text-center text-sm text-gray-600 dark:text-gray-300 mb-4;
p { p {
@apply mb-2; @apply mb-2;
} }
} }
.qrcode-grid { .qrcode-grid {
@apply flex justify-between items-center gap-4 flex-wrap; @apply flex justify-between items-center gap-4 flex-wrap;
.qrcode-item { .qrcode-item {
@apply flex flex-col items-center gap-2; @apply flex flex-col items-center gap-2;
.qrcode-image { .qrcode-image {
@apply w-36 h-36 rounded-lg border border-gray-200 dark:border-gray-700/10 shadow-sm transition-transform duration-200 hover:scale-105; @apply w-36 h-36 rounded-lg border border-gray-200 dark:border-gray-700/10 shadow-sm transition-transform duration-200 hover:scale-105;
} }
.qrcode-label { .qrcode-label {
@apply text-sm text-gray-600 dark:text-gray-300; @apply text-sm text-gray-600 dark:text-gray-300;
} }
} }
.donate-button { .donate-button {
@apply flex flex-col items-center justify-center; @apply flex flex-col items-center justify-center;
} }

View File

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

View File

@@ -1,4 +1,5 @@
import { Router } from 'vue-router'; import { Router } from 'vue-router';
import { useMusicStore } from '@/store/modules/music'; import { useMusicStore } from '@/store/modules/music';
/** /**
@@ -35,4 +36,4 @@ export function navigateToMusicList(
name: 'musicList' name: 'musicList'
}); });
} }
} }

View File

@@ -31,13 +31,14 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { useRouter } from 'vue-router';
import { getAlbum, getListDetail } from '@/api/list'; import { getAlbum, getListDetail } from '@/api/list';
import MvPlayer from '@/components/MvPlayer.vue'; import MvPlayer from '@/components/MvPlayer.vue';
import { useMusicStore } from '@/store/modules/music';
import { usePlayerStore } from '@/store/modules/player'; import { usePlayerStore } from '@/store/modules/player';
import { IMvItem } from '@/type/mv'; import { IMvItem } from '@/type/mv';
import { getImgUrl } from '@/utils'; import { getImgUrl } from '@/utils';
import { useRouter } from 'vue-router';
import { useMusicStore } from '@/store/modules/music';
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
@@ -88,15 +89,10 @@ const handleClick = async () => {
}, },
description: res.data.album.description description: res.data.album.description
}; };
// 保存数据到store // 保存数据到store
musicStore.setCurrentMusicList( musicStore.setCurrentMusicList(songList.value, props.item.name, listInfo.value, false);
songList.value,
props.item.name,
listInfo.value,
false
);
// 使用路由跳转 // 使用路由跳转
router.push({ router.push({
name: 'musicList', name: 'musicList',
@@ -107,15 +103,10 @@ const handleClick = async () => {
const res = await getListDetail(props.item.id); const res = await getListDetail(props.item.id);
songList.value = res.data.playlist.tracks; songList.value = res.data.playlist.tracks;
listInfo.value = res.data.playlist; listInfo.value = res.data.playlist;
// 保存数据到store // 保存数据到store
musicStore.setCurrentMusicList( musicStore.setCurrentMusicList(songList.value, props.item.name, listInfo.value, false);
songList.value,
props.item.name,
listInfo.value,
false
);
// 使用路由跳转 // 使用路由跳转
router.push({ router.push({
name: 'musicList', name: 'musicList',

View File

@@ -1,5 +1,5 @@
<template> <template>
<component <component
:is="renderComponent" :is="renderComponent"
:item="item" :item="item"
:favorite="favorite" :favorite="favorite"
@@ -16,12 +16,13 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed } from 'vue'; import { computed } from 'vue';
import type { SongResult } from '@/type/music'; 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 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( const props = withDefaults(
defineProps<{ defineProps<{

View File

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

View File

@@ -11,7 +11,7 @@
<slot name="image"></slot> <slot name="image"></slot>
<slot name="content"></slot> <slot name="content"></slot>
<slot name="operating"></slot> <slot name="operating"></slot>
<song-item-dropdown <song-item-dropdown
v-if="isElectron" v-if="isElectron"
:item="item" :item="item"
@@ -33,10 +33,11 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import SongItemDropdown from './SongItemDropdown.vue';
import { useSongItem } from '@/hooks/useSongItem'; import { useSongItem } from '@/hooks/useSongItem';
import { isElectron } from '@/utils';
import type { SongResult } from '@/type/music'; import type { SongResult } from '@/type/music';
import { isElectron } from '@/utils';
import SongItemDropdown from './SongItemDropdown.vue';
const props = defineProps<{ const props = defineProps<{
item: SongResult; item: SongResult;
@@ -115,4 +116,4 @@ defineExpose({
.text-ellipsis { .text-ellipsis {
width: 100%; width: 100%;
} }
</style> </style>

View File

@@ -14,7 +14,11 @@
> >
<!-- 索引插槽 --> <!-- 索引插槽 -->
<template #index> <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 }} {{ index + 1 }}
</div> </div>
</template> </template>
@@ -25,13 +29,17 @@
<n-checkbox :checked="selected" /> <n-checkbox :checked="selected" />
</div> </div>
</template> </template>
<!-- 内容插槽 --> <!-- 内容插槽 -->
<template #content> <template #content>
<div class="song-item-content-compact"> <div class="song-item-content-compact">
<div class="song-item-content-compact-wrapper"> <div class="song-item-content-compact-wrapper">
<div class="song-item-content-compact-title w-60 flex-shrink-0"> <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 }} {{ item.name }}
</n-ellipsis> </n-ellipsis>
</div> </div>
@@ -56,11 +64,15 @@
</div> </div>
</div> </div>
</template> </template>
<!-- 操作插槽 --> <!-- 操作插槽 -->
<template #operating> <template #operating>
<div class="song-item-operating-compact"> <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 <i
class="iconfont icon-likefill" class="iconfont icon-likefill"
:class="{ 'like-active': isFavorite }" :class="{ 'like-active': isFavorite }"
@@ -69,13 +81,21 @@
</div> </div>
<div <div
class="song-item-operating-play animate__animated" 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" @click="onPlayMusic"
> >
<i v-if="isPlaying && play" class="iconfont icon-stop"></i> <i v-if="isPlaying && play" class="iconfont icon-stop"></i>
<i v-else class="iconfont icon-playfill"></i> <i v-else class="iconfont icon-playfill"></i>
</div> </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> <i class="iconfont ri-more-fill"></i>
</div> </div>
</div> </div>
@@ -86,10 +106,12 @@
<script lang="ts" setup> <script lang="ts" setup>
import { NCheckbox, NEllipsis } from 'naive-ui'; import { NCheckbox, NEllipsis } from 'naive-ui';
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { usePlayerStore } from '@/store'; import { usePlayerStore } from '@/store';
import BaseSongItem from './BaseSongItem.vue';
import type { SongResult } from '@/type/music'; import type { SongResult } from '@/type/music';
import BaseSongItem from './BaseSongItem.vue';
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();
const props = withDefaults( const props = withDefaults(
@@ -249,4 +271,4 @@ const formatDuration = (ms: number): string => {
:deep(.text-ellipsis) { :deep(.text-ellipsis) {
width: 100%; width: 100%;
} }
</style> </style>

View File

@@ -18,7 +18,7 @@
<n-checkbox :checked="selected" /> <n-checkbox :checked="selected" />
</div> </div>
</template> </template>
<!-- 图片插槽 --> <!-- 图片插槽 -->
<template #image> <template #image>
<n-image <n-image
@@ -32,12 +32,16 @@
@load="onImageLoad" @load="onImageLoad"
/> />
</template> </template>
<!-- 内容插槽 --> <!-- 内容插槽 -->
<template #content> <template #content>
<div class="song-item-content"> <div class="song-item-content">
<div class="song-item-content-wrapper"> <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 }} {{ item.name }}
</n-ellipsis> </n-ellipsis>
<div class="song-item-content-divider">-</div> <div class="song-item-content-divider">-</div>
@@ -54,7 +58,7 @@
</div> </div>
</div> </div>
</template> </template>
<!-- 操作插槽 --> <!-- 操作插槽 -->
<template #operating> <template #operating>
<div class="song-item-operating song-item-operating-list"> <div class="song-item-operating song-item-operating-list">
@@ -67,7 +71,7 @@
</div> </div>
<div <div
class="song-item-operating-play bg-gray-300 dark:bg-gray-800 animate__animated" 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" @click="onPlayMusic"
> >
<i v-if="isPlaying && play" class="iconfont icon-stop"></i> <i v-if="isPlaying && play" class="iconfont icon-stop"></i>
@@ -81,11 +85,13 @@
<script lang="ts" setup> <script lang="ts" setup>
import { NCheckbox, NEllipsis, NImage } from 'naive-ui'; import { NCheckbox, NEllipsis, NImage } from 'naive-ui';
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { usePlayerStore } from '@/store'; import { usePlayerStore } from '@/store';
import BaseSongItem from './BaseSongItem.vue';
import type { SongResult } from '@/type/music'; import type { SongResult } from '@/type/music';
import { getImgUrl } from '@/utils'; import { getImgUrl } from '@/utils';
import BaseSongItem from './BaseSongItem.vue';
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();
const props = withDefaults( const props = withDefaults(
@@ -187,4 +193,4 @@ const onPlayMusic = () => {
} }
} }
} }
</style> </style>

View File

@@ -18,7 +18,7 @@
<n-checkbox :checked="selected" /> <n-checkbox :checked="selected" />
</div> </div>
</template> </template>
<!-- 图片插槽 --> <!-- 图片插槽 -->
<template #image> <template #image>
<n-image <n-image
@@ -32,7 +32,7 @@
@load="onImageLoad" @load="onImageLoad"
/> />
</template> </template>
<!-- 内容插槽 --> <!-- 内容插槽 -->
<template #content> <template #content>
<div class="song-item-content"> <div class="song-item-content">
@@ -55,7 +55,7 @@
</div> </div>
</div> </div>
</template> </template>
<!-- 操作插槽 --> <!-- 操作插槽 -->
<template #operating> <template #operating>
<div class="song-item-operating"> <div class="song-item-operating">
@@ -68,7 +68,7 @@
</div> </div>
<div <div
class="song-item-operating-play bg-gray-300 dark:bg-gray-800 animate__animated" 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" @click="onPlayMusic"
> >
<i v-if="isPlaying && play" class="iconfont icon-stop"></i> <i v-if="isPlaying && play" class="iconfont icon-stop"></i>
@@ -82,11 +82,13 @@
<script lang="ts" setup> <script lang="ts" setup>
import { NCheckbox, NEllipsis, NImage } from 'naive-ui'; import { NCheckbox, NEllipsis, NImage } from 'naive-ui';
import { computed, ref } from 'vue'; import { computed, ref } from 'vue';
import { usePlayerStore } from '@/store'; import { usePlayerStore } from '@/store';
import BaseSongItem from './BaseSongItem.vue';
import type { SongResult } from '@/type/music'; import type { SongResult } from '@/type/music';
import { getImgUrl } from '@/utils'; import { getImgUrl } from '@/utils';
import BaseSongItem from './BaseSongItem.vue';
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();
const props = withDefaults( const props = withDefaults(
@@ -169,11 +171,11 @@ const onPlayMusic = () => {
&-like { &-like {
@apply mr-1 ml-1 cursor-pointer; @apply mr-1 ml-1 cursor-pointer;
.icon-likefill { .icon-likefill {
@apply text-base transition text-gray-500 dark:text-gray-400 hover:text-red-500; @apply text-base transition text-gray-500 dark:text-gray-400 hover:text-red-500;
} }
.like-active { .like-active {
@apply text-red-500 dark:text-red-500; @apply text-red-500 dark:text-red-500;
} }
@@ -190,4 +192,4 @@ const onPlayMusic = () => {
} }
} }
} }
</style> </style>

View File

@@ -15,7 +15,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { MenuOption } from 'naive-ui'; 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 { computed, h, inject } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
@@ -35,12 +35,12 @@ const props = defineProps<{
}>(); }>();
const emits = defineEmits([ const emits = defineEmits([
'update:show', 'update:show',
'select', 'select',
'play', 'play',
'play-next', 'play-next',
'download', 'download',
'add-to-playlist', 'add-to-playlist',
'toggle-favorite', 'toggle-favorite',
'toggle-dislike', 'toggle-dislike',
'remove' 'remove'
@@ -104,7 +104,9 @@ const renderSongPreview = () => {
}, },
{ {
default: () => { 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 || '未知艺术家'; return artistNames || '未知艺术家';
} }
} }
@@ -164,8 +166,11 @@ const dropdownOptions = computed<MenuOption[]>(() => {
{ {
label: props.isDislike ? t('songItem.menu.undislike') : t('songItem.menu.dislike'), label: props.isDislike ? t('songItem.menu.undislike') : t('songItem.menu.dislike'),
key: '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) { if (props.canRemove) {
@@ -188,7 +193,7 @@ const dropdownOptions = computed<MenuOption[]>(() => {
// 处理选择 // 处理选择
const handleSelect = (key: string | number) => { const handleSelect = (key: string | number) => {
emits('update:show', false); emits('update:show', false);
switch (key) { switch (key) {
case 'download': case 'download':
emits('download'); emits('download');
@@ -249,4 +254,4 @@ const handleSelect = (key: string | number) => {
:deep(.n-dropdown-option-body--render) { :deep(.n-dropdown-option-body--render) {
@apply p-0; @apply p-0;
} }
</style> </style>

View File

@@ -18,7 +18,7 @@
<n-checkbox :checked="selected" /> <n-checkbox :checked="selected" />
</div> </div>
</template> </template>
<!-- 图片插槽 --> <!-- 图片插槽 -->
<template #image> <template #image>
<n-image <n-image
@@ -32,12 +32,17 @@
@load="onImageLoad" @load="onImageLoad"
/> />
</template> </template>
<!-- 内容插槽 --> <!-- 内容插槽 -->
<template #content> <template #content>
<div class="song-item-content"> <div class="song-item-content">
<div class="song-item-content-title"> <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>
<div class="song-item-content-name"> <div class="song-item-content-name">
<n-ellipsis class="text-ellipsis" line-clamp="1"> <n-ellipsis class="text-ellipsis" line-clamp="1">
@@ -53,7 +58,7 @@
</div> </div>
</div> </div>
</template> </template>
<!-- 操作插槽 --> <!-- 操作插槽 -->
<template #operating> <template #operating>
<div class="song-item-operating"> <div class="song-item-operating">
@@ -74,7 +79,7 @@
</n-tooltip> </n-tooltip>
<div <div
class="song-item-operating-play bg-gray-300 dark:bg-gray-800 animate__animated" 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" @click="onPlayMusic"
> >
<i v-if="isPlaying && play" class="iconfont icon-stop"></i> <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 { useI18n } from 'vue-i18n';
import { usePlayerStore } from '@/store'; import { usePlayerStore } from '@/store';
import BaseSongItem from './BaseSongItem.vue';
import type { SongResult } from '@/type/music'; import type { SongResult } from '@/type/music';
import { getImgUrl } from '@/utils'; import { getImgUrl } from '@/utils';
import BaseSongItem from './BaseSongItem.vue';
const { t } = useI18n(); const { t } = useI18n();
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();
@@ -185,7 +191,7 @@ const onPlayNext = () => {
&-next { &-next {
@apply mr-2 cursor-pointer transition-all; @apply mr-2 cursor-pointer transition-all;
.iconfont { .iconfont {
@apply text-xl transition text-gray-500 dark:text-gray-400 hover:text-green-500; @apply text-xl transition text-gray-500 dark:text-gray-400 hover:text-green-500;
} }
@@ -210,4 +216,4 @@ const onPlayNext = () => {
@apply mr-3 cursor-pointer; @apply mr-3 cursor-pointer;
} }
} }
</style> </style>

View File

@@ -32,9 +32,9 @@ import { useRouter } from 'vue-router';
import { getNewAlbum } from '@/api/home'; import { getNewAlbum } from '@/api/home';
import { getAlbum } from '@/api/list'; import { getAlbum } from '@/api/list';
import { getImgUrl, setAnimationClass, setAnimationDelay } from '@/utils';
import { navigateToMusicList } from '@/components/common/MusicListNavigator'; import { navigateToMusicList } from '@/components/common/MusicListNavigator';
import type { IAlbumNew } from '@/type/album'; import type { IAlbumNew } from '@/type/album';
import { getImgUrl, setAnimationClass, setAnimationDelay } from '@/utils';
const { t } = useI18n(); const { t } = useI18n();
const albumData = ref<IAlbumNew>(); const albumData = ref<IAlbumNew>();
@@ -51,17 +51,17 @@ const handleClick = async (item: any) => {
const openAlbum = async (album: any) => { const openAlbum = async (album: any) => {
if (!album) return; if (!album) return;
try { try {
const res = await getAlbum(album.id); const res = await getAlbum(album.id);
const { songs, album: albumInfo } = res.data; const { songs, album: albumInfo } = res.data;
const formattedSongs = songs.map((song: any) => { const formattedSongs = songs.map((song: any) => {
song.al.picUrl = song.al.picUrl || albumInfo.picUrl; song.al.picUrl = song.al.picUrl || albumInfo.picUrl;
song.picUrl = song.al.picUrl || albumInfo.picUrl || song.picUrl; song.picUrl = song.al.picUrl || albumInfo.picUrl || song.picUrl;
return song; return song;
}); });
navigateToMusicList(router, { navigateToMusicList(router, {
id: album.id, id: album.id,
type: 'album', type: 'album',

View File

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

View File

@@ -1,21 +1,19 @@
<script setup lang="ts"> <script setup lang="ts">
import { defineProps, defineEmits } from 'vue'; import { defineEmits, defineProps } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
const props = defineProps<{ const props = defineProps<{
correctionTime: number correctionTime: number;
}>(); }>();
const emit = defineEmits<{ const emit = defineEmits<{
(e: 'adjust', delta: number): void (e: 'adjust', delta: number): void;
}>(); }>();
const { t } = useI18n(); const { t } = useI18n();
</script> </script>
<template> <template>
<div <div class="lyric-correction">
class="lyric-correction"
>
<n-tooltip placement="right"> <n-tooltip placement="right">
<template #trigger> <template #trigger>
<div <div
@@ -28,7 +26,9 @@ const { t } = useI18n();
</template> </template>
<span>{{ t('player.subtractCorrection', { num: 0.2 }) }}</span> <span>{{ t('player.subtractCorrection', { num: 0.2 }) }}</span>
</n-tooltip> </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 {{ props.correctionTime > 0 ? '+' : '' }}{{ props.correctionTime.toFixed(1) }}s
</span> </span>
<n-tooltip placement="right"> <n-tooltip placement="right">
@@ -55,9 +55,9 @@ 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; @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 { .lyric-correction {
@apply opacity-100; @apply opacity-100;
} }
} }
</style> </style>

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -44,7 +44,11 @@
class="color-preview" class="color-preview"
:style="{ backgroundColor: currentColor }" :style="{ backgroundColor: currentColor }"
@click="showColorPicker = !showColorPicker" @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> <i class="ri-palette-line"></i>
</div> </div>
@@ -70,7 +74,7 @@
</div> </div>
</div> </div>
</div> </div>
<!-- 颜色选择器展开时显示 --> <!-- 颜色选择器展开时显示 -->
<div v-if="showColorPicker" class="color-picker-dropdown"> <div v-if="showColorPicker" class="color-picker-dropdown">
<n-color-picker <n-color-picker
@@ -86,16 +90,16 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { NColorPicker } from 'naive-ui';
import { ref, watch } from 'vue'; import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { NColorPicker } from 'naive-ui';
import { import {
getLyricThemeColors, getLyricThemeColors,
getPresetColorValue, getPresetColorValue,
validateColor, type LyricThemeColor,
optimizeColorForTheme, optimizeColorForTheme,
type LyricThemeColor validateColor
} from '@/utils/linearColor'; } from '@/utils/linearColor';
interface Props { interface Props {
@@ -105,7 +109,7 @@ interface Props {
} }
interface Emits { interface Emits {
(e: 'colorChange', color: string): void; (e: 'colorChange', _color: string): void;
(e: 'close'): void; (e: 'close'): void;
} }
@@ -160,7 +164,7 @@ const handlePresetColorSelect = (color: LyricThemeColor) => {
const colorValue = getColorValue(color); const colorValue = getColorValue(color);
const optimizedColor = optimizeColorForTheme(colorValue, props.theme); const optimizedColor = optimizeColorForTheme(colorValue, props.theme);
emit('colorChange', optimizedColor); emit('colorChange', optimizedColor);
// 更新输入框和选择器 // 更新输入框和选择器
colorInput.value = optimizedColor; colorInput.value = optimizedColor;
pickerColor.value = optimizedColor; pickerColor.value = optimizedColor;
@@ -253,31 +257,31 @@ watch(
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
z-index: 1000; z-index: 1000;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
&.hidden { &.hidden {
opacity: 0; opacity: 0;
visibility: hidden; visibility: hidden;
transform: translateX(-50%) translateY(-10px) scale(0.95); transform: translateX(-50%) translateY(-10px) scale(0.95);
pointer-events: none; pointer-events: none;
} }
&.visible { &.visible {
opacity: 1; opacity: 1;
visibility: visible; visibility: visible;
transform: translateX(-50%) translateY(0) scale(1); transform: translateX(-50%) translateY(0) scale(1);
pointer-events: auto; pointer-events: auto;
} }
// 小屏幕适配 // 小屏幕适配
@media (max-width: 520px) { @media (max-width: 520px) {
min-width: calc(100vw - 40px); min-width: calc(100vw - 40px);
left: 20px; left: 20px;
transform: none; transform: none;
&.hidden { &.hidden {
transform: translateY(-10px) scale(0.95); transform: translateY(-10px) scale(0.95);
} }
&.visible { &.visible {
transform: translateY(0) scale(1); transform: translateY(0) scale(1);
} }
@@ -289,14 +293,14 @@ watch(
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 12px; margin-bottom: 12px;
.panel-title { .panel-title {
font-size: 13px; font-size: 13px;
font-weight: 600; font-weight: 600;
color: var(--text-color); color: var(--text-color);
opacity: 0.9; opacity: 0.9;
} }
.close-button { .close-button {
width: 24px; width: 24px;
height: 24px; height: 24px;
@@ -307,12 +311,12 @@ watch(
border-radius: 6px; border-radius: 6px;
color: var(--text-color); color: var(--text-color);
transition: all 0.2s ease; transition: all 0.2s ease;
&:hover { &:hover {
background: rgba(255, 255, 255, 0.15); background: rgba(255, 255, 255, 0.15);
color: #ff6b6b; color: #ff6b6b;
} }
i { i {
font-size: 14px; font-size: 14px;
} }
@@ -325,7 +329,7 @@ watch(
align-items: center; align-items: center;
gap: 16px; gap: 16px;
} }
.section-label { .section-label {
font-size: 11px; font-size: 11px;
font-weight: 500; font-weight: 500;
@@ -334,7 +338,7 @@ watch(
margin-bottom: 6px; margin-bottom: 6px;
text-align: center; text-align: center;
} }
.divider { .divider {
width: 1px; width: 1px;
height: 40px; height: 40px;
@@ -347,7 +351,7 @@ watch(
.preset-colors { .preset-colors {
display: flex; display: flex;
gap: 6px; gap: 6px;
.color-dot { .color-dot {
width: 24px; width: 24px;
height: 24px; height: 24px;
@@ -358,17 +362,17 @@ watch(
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
&:hover { &:hover {
transform: scale(1.1); transform: scale(1.1);
border-color: rgba(255, 255, 255, 0.3); border-color: rgba(255, 255, 255, 0.3);
} }
&.active { &.active {
border-color: var(--text-color); border-color: var(--text-color);
box-shadow: 0 0 0 2px var(--control-bg); box-shadow: 0 0 0 2px var(--control-bg);
} }
i { i {
color: white; color: white;
font-size: 10px; font-size: 10px;
@@ -384,7 +388,7 @@ watch(
display: flex; display: flex;
gap: 8px; gap: 8px;
align-items: center; align-items: center;
.color-preview { .color-preview {
width: 24px; width: 24px;
height: 24px; height: 24px;
@@ -395,19 +399,19 @@ watch(
align-items: center; align-items: center;
justify-content: center; justify-content: center;
transition: all 0.2s ease; transition: all 0.2s ease;
&:hover { &:hover {
border-color: rgba(255, 255, 255, 0.4); border-color: rgba(255, 255, 255, 0.4);
transform: scale(1.05); transform: scale(1.05);
} }
i { i {
color: white; color: white;
font-size: 12px; font-size: 12px;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.8); text-shadow: 0 0 4px rgba(0, 0, 0, 0.8);
} }
} }
.color-input { .color-input {
width: 80px; width: 80px;
height: 24px; height: 24px;
@@ -420,12 +424,12 @@ watch(
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
outline: none; outline: none;
transition: all 0.2s ease; transition: all 0.2s ease;
&:focus { &:focus {
border-color: var(--highlight-color, rgba(255, 255, 255, 0.4)); border-color: var(--highlight-color, rgba(255, 255, 255, 0.4));
background: rgba(255, 255, 255, 0.12); background: rgba(255, 255, 255, 0.12);
} }
&::placeholder { &::placeholder {
color: rgba(255, 255, 255, 0.4); color: rgba(255, 255, 255, 0.4);
} }
@@ -441,7 +445,7 @@ watch(
line-height: 1.2; line-height: 1.2;
white-space: nowrap; white-space: nowrap;
transition: all 0.2s ease; transition: all 0.2s ease;
&:hover { &:hover {
transform: scale(1.02); transform: scale(1.02);
} }
@@ -455,7 +459,7 @@ watch(
background: rgba(0, 0, 0, 0.2); background: rgba(0, 0, 0, 0.2);
border-radius: 6px; border-radius: 6px;
border: 1px solid rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.1);
:deep(.n-color-picker) { :deep(.n-color-picker) {
width: 100%; width: 100%;
} }
@@ -466,15 +470,15 @@ watch(
.compact-layout { .compact-layout {
flex-direction: column; flex-direction: column;
gap: 12px; gap: 12px;
.divider { .divider {
width: 100%; width: 100%;
height: 1px; height: 1px;
} }
} }
.preset-section .preset-colors { .preset-section .preset-colors {
justify-content: center; justify-content: center;
} }
} }
</style> </style>

View File

@@ -1,18 +1,18 @@
<template> <template>
<n-dropdown <n-dropdown
:show="showDropdown" :show="showDropdown"
:options="dropdownOptions" :options="dropdownOptions"
trigger="hover" trigger="hover"
:z-index="9999999" :z-index="9999999"
@select="handleSelect" @select="handleSelect"
placement="top" placement="top"
@update:show="(show) => showDropdown = show" @update:show="(show) => (showDropdown = show)"
> >
<n-tooltip trigger="hover" :z-index="9999999"> <n-tooltip trigger="hover" :z-index="9999999">
<template #trigger> <template #trigger>
<div class="advanced-controls-btn"> <div class="advanced-controls-btn">
<i class="iconfont ri-settings-3-line"></i> <i class="iconfont ri-settings-3-line"></i>
<!-- 激活状态的小标记 --> <!-- 激活状态的小标记 -->
<div v-if="hasActiveSettings" class="active-indicator"> <div v-if="hasActiveSettings" class="active-indicator">
<span v-if="hasActiveSleepTimer" class="timer-badge"> <span v-if="hasActiveSleepTimer" class="timer-badge">
@@ -26,7 +26,12 @@
</n-dropdown> </n-dropdown>
<!-- EQ 均衡器弹窗 --> <!-- 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="eq-modal-content">
<div class="modal-close" @click="showEQModal = false"> <div class="modal-close" @click="showEQModal = false">
<i class="ri-close-line"></i> <i class="ri-close-line"></i>
@@ -36,7 +41,12 @@
</n-modal> </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="timer-modal-content">
<div class="modal-close" @click="playerStore.showSleepTimer = false"> <div class="modal-close" @click="playerStore.showSleepTimer = false">
<i class="ri-close-line"></i> <i class="ri-close-line"></i>
@@ -46,18 +56,23 @@
</n-modal> </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="speed-modal-content">
<div class="modal-close" @click="showSpeedModal = false"> <div class="modal-close" @click="showSpeedModal = false">
<i class="ri-close-line"></i> <i class="ri-close-line"></i>
</div> </div>
<h3>{{ t('player.playBar.playbackSpeed') }}</h3> <h3>{{ t('player.playBar.playbackSpeed') }}</h3>
<div class="speed-options"> <div class="speed-options">
<div <div
v-for="option in playbackRateOptions" v-for="option in playbackRateOptions"
:key="option.key" :key="option.key"
class="speed-option" class="speed-option"
:class="{ 'active': playbackRate === option.key }" :class="{ active: playbackRate === option.key }"
@click="selectSpeed(option.key)" @click="selectSpeed(option.key)"
> >
{{ option.label }} {{ option.label }}
@@ -68,12 +83,13 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { ref, computed, h, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { DropdownOption } from 'naive-ui'; 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 EqControl from '@/components/EQControl.vue';
import SleepTimer from '@/components/player/SleepTimer.vue'; import SleepTimer from '@/components/player/SleepTimer.vue';
import { usePlayerStore } from '@/store/modules/player';
const { t } = useI18n(); const { t } = useI18n();
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();
@@ -93,13 +109,16 @@ watch(showEQModal, (newValue) => {
} }
}); });
watch(() => playerStore.showSleepTimer, (newValue) => { watch(
if (newValue) { () => playerStore.showSleepTimer,
// 如果睡眠定时器弹窗打开,关闭其他弹窗 (newValue) => {
showEQModal.value = false; if (newValue) {
showSpeedModal.value = false; // 如果睡眠定时器弹窗打开,关闭其他弹窗
showEQModal.value = false;
showSpeedModal.value = false;
}
} }
}); );
watch(showSpeedModal, (newValue) => { watch(showSpeedModal, (newValue) => {
if (newValue) { if (newValue) {
@@ -142,14 +161,17 @@ const dropdownOptions = computed<DropdownOption[]>(() => [
key: 'timer', key: 'timer',
icon: () => h('i', { class: 'ri-timer-line' }), 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)`, label: t('player.playBar.playbackSpeed') + `(${playbackRate.value}x)`,
key: 'speed', key: 'speed',
icon: () => h('i', { class: 'ri-speed-line' }), icon: () => h('i', { class: 'ri-speed-line' }),
// 如果播放速度不是1.0,添加标记 // 如果播放速度不是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
} }
]); ]);
@@ -159,7 +181,7 @@ const handleSelect = (key: string) => {
showEQModal.value = false; showEQModal.value = false;
playerStore.showSleepTimer = false; playerStore.showSleepTimer = false;
showSpeedModal.value = false; showSpeedModal.value = false;
// 然后仅打开所选弹窗 // 然后仅打开所选弹窗
switch (key) { switch (key) {
case 'eq': case 'eq':
@@ -179,18 +201,17 @@ const selectSpeed = (speed: number) => {
playerStore.setPlaybackRate(speed); playerStore.setPlaybackRate(speed);
showSpeedModal.value = false; showSpeedModal.value = false;
}; };
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.sleep-timer-countdown { .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; @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; z-index: 9998;
min-width: 80px; min-width: 80px;
text-align: center; text-align: center;
animation: fadeInDown 0.3s ease-out; animation: fadeInDown 0.3s ease-out;
@keyframes fadeInDown { @keyframes fadeInDown {
from { from {
transform: translate(-50%, -100%); transform: translate(-50%, -100%);
@@ -201,7 +222,7 @@ const selectSpeed = (speed: number) => {
opacity: 1; opacity: 1;
} }
} }
span { span {
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
letter-spacing: 0.5px; letter-spacing: 0.5px;
@@ -211,28 +232,29 @@ const selectSpeed = (speed: number) => {
.advanced-controls-btn { .advanced-controls-btn {
@apply cursor-pointer mx-3 relative; @apply cursor-pointer mx-3 relative;
.iconfont { .iconfont {
@apply text-2xl transition; @apply text-2xl transition;
@apply hover:text-green-500; @apply hover:text-green-500;
} }
.active-indicator { .active-indicator {
@apply absolute -top-1 -right-1 flex; @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; @apply flex items-center justify-center text-xs bg-green-500 text-white rounded-full;
height: 16px; height: 16px;
min-width: 16px; min-width: 16px;
padding: 0 3px; padding: 0 3px;
font-weight: 600; font-weight: 600;
font-size: 10px; font-size: 10px;
i { i {
font-size: 10px; font-size: 10px;
} }
} }
.timer-badge + .speed-badge { .timer-badge + .speed-badge {
@apply -ml-2 z-10; @apply -ml-2 z-10;
} }
@@ -282,4 +304,4 @@ const selectSpeed = (speed: number) => {
@apply text-2xl; @apply text-2xl;
} }
} }
</style> </style>

View File

@@ -52,7 +52,13 @@
></i> ></i>
</div> </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> <template #trigger>
<div class="function-button" @click="mute" @wheel.prevent="handleVolumeWheel"> <div class="function-button" @click="mute" @wheel.prevent="handleVolumeWheel">
<i class="iconfont" :class="getVolumeIcon"></i> <i class="iconfont" :class="getVolumeIcon"></i>
@@ -196,16 +202,16 @@ const handleVolumeWheel = (e: WheelEvent) => {
const isFavorite = computed(() => { const isFavorite = computed(() => {
// 对于B站视频使用ID匹配函数 // 对于B站视频使用ID匹配函数
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) { 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 // 非B站视频直接比较ID
return playerStore.favoriteList.includes(playMusic.value.id); return playerStore.favoriteList.includes(playMusic.value.id);
}); });
const toggleFavorite = async (e: Event) => { const toggleFavorite = async (e: Event) => {
e.stopPropagation(); e.stopPropagation();
// 处理B站视频的收藏ID // 处理B站视频的收藏ID
let favoriteId = playMusic.value.id; let favoriteId = playMusic.value.id;
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) { if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) {
@@ -538,7 +544,7 @@ const setMusicFull = () => {
.volume-slider-wrapper { .volume-slider-wrapper {
@apply p-2 py-4 rounded-xl bg-white dark:bg-dark-100 shadow-lg bg-opacity-90 backdrop-blur; @apply p-2 py-4 rounded-xl bg-white dark:bg-dark-100 shadow-lg bg-opacity-90 backdrop-blur;
height: 160px; height: 160px;
:deep(.n-slider) { :deep(.n-slider) {
--n-rail-height: 4px; --n-rail-height: 4px;
--n-rail-color: theme('colors.gray.200'); --n-rail-color: theme('colors.gray.200');
@@ -642,7 +648,7 @@ const setMusicFull = () => {
} }
} }
:deep(.n-popover){ :deep(.n-popover) {
background-color: transparent !important; background-color: transparent !important;
} }
</style> </style>

View File

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

View File

@@ -60,9 +60,7 @@
<n-ellipsis class="text-ellipsis" line-clamp="1"> <n-ellipsis class="text-ellipsis" line-clamp="1">
{{ playMusic.name }} {{ playMusic.name }}
</n-ellipsis> </n-ellipsis>
<span v-if="playbackRate !== 1.0" class="playback-rate-badge"> <span v-if="playbackRate !== 1.0" class="playback-rate-badge"> {{ playbackRate }}x </span>
{{ playbackRate }}x
</span>
</div> </div>
<div class="music-content-name"> <div class="music-content-name">
<n-ellipsis <n-ellipsis
@@ -137,13 +135,16 @@
</template> </template>
{{ t('player.playBar.reparse') }} {{ t('player.playBar.reparse') }}
</n-tooltip> </n-tooltip>
<!-- 高级控制菜单按钮整合了 EQ定时关闭播放速度 --> <!-- 高级控制菜单按钮整合了 EQ定时关闭播放速度 -->
<advanced-controls-popover /> <advanced-controls-popover />
<n-tooltip trigger="hover" :z-index="9999999"> <n-tooltip trigger="hover" :z-index="9999999">
<template #trigger> <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> </template>
{{ t('player.playBar.playList') }} {{ t('player.playBar.playList') }}
</n-tooltip> </n-tooltip>
@@ -156,8 +157,12 @@
<script lang="ts" setup> <script lang="ts" setup>
import { useThrottleFn } from '@vueuse/core'; import { useThrottleFn } from '@vueuse/core';
import { useMessage } from 'naive-ui'; import { useMessage } from 'naive-ui';
import { storeToRefs } from 'pinia';
import { computed, ref, watch } from 'vue'; import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; 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 ReparsePopover from '@/components/player/ReparsePopover.vue';
import { import {
allTime, allTime,
@@ -169,16 +174,10 @@ import {
textColors textColors
} from '@/hooks/MusicHook'; } from '@/hooks/MusicHook';
import { useArtist } from '@/hooks/useArtist'; import { useArtist } from '@/hooks/useArtist';
import MusicFullWrapper from '@/components/lyric/MusicFullWrapper.vue';
import { audioService } from '@/services/audioService'; import { audioService } from '@/services/audioService';
import { import { isBilibiliIdMatch, usePlayerStore } from '@/store/modules/player';
isBilibiliIdMatch,
usePlayerStore
} from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings'; import { useSettingsStore } from '@/store/modules/settings';
import { getImgUrl, isElectron, isMobile, secondToMinute, setAnimationClass } from '@/utils'; import { getImgUrl, isElectron, isMobile, secondToMinute, setAnimationClass } from '@/utils';
import AdvancedControlsPopover from '@/components/player/AdvancedControlsPopover.vue';
import { storeToRefs } from 'pinia';
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();
const settingsStore = useSettingsStore(); const settingsStore = useSettingsStore();
@@ -313,7 +312,7 @@ const playModeText = computed(() => {
}); });
// 播放速度控制 // 播放速度控制
const {playbackRate} = storeToRefs(playerStore); const { playbackRate } = storeToRefs(playerStore);
// 切换播放模式 // 切换播放模式
const togglePlayMode = () => { const togglePlayMode = () => {
playerStore.togglePlayMode(); playerStore.togglePlayMode();
@@ -333,7 +332,7 @@ const showSliderTooltip = ref(false);
// 播放暂停按钮事件 // 播放暂停按钮事件
const playMusicEvent = async () => { const playMusicEvent = async () => {
try { try {
const result = await playerStore.setPlay({ ...playMusic.value}); const result = await playerStore.setPlay({ ...playMusic.value });
if (result) { if (result) {
playerStore.setPlayMusic(true); playerStore.setPlayMusic(true);
} }
@@ -348,7 +347,7 @@ const musicFullVisible = computed({
set: (value) => { set: (value) => {
playerStore.setMusicFull(value); playerStore.setMusicFull(value);
} }
}) });
// 设置musicFull // 设置musicFull
const setMusicFull = () => { const setMusicFull = () => {
@@ -362,9 +361,9 @@ const setMusicFull = () => {
const isFavorite = computed(() => { const isFavorite = computed(() => {
// 对于B站视频使用ID匹配函数 // 对于B站视频使用ID匹配函数
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) { 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 // 非B站视频直接比较ID
return playerStore.favoriteList.includes(playMusic.value.id); return playerStore.favoriteList.includes(playMusic.value.id);
}); });
@@ -372,7 +371,7 @@ const isFavorite = computed(() => {
const toggleFavorite = async (e: Event) => { const toggleFavorite = async (e: Event) => {
console.log('playMusic.value', playMusic.value); console.log('playMusic.value', playMusic.value);
e.stopPropagation(); e.stopPropagation();
// 处理B站视频的收藏ID // 处理B站视频的收藏ID
let favoriteId = playMusic.value.id; let favoriteId = playMusic.value.id;
if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) { if (playMusic.value.source === 'bilibili' && playMusic.value.bilibiliData?.bvid) {
@@ -381,7 +380,7 @@ const toggleFavorite = async (e: Event) => {
favoriteId = `${playMusic.value.bilibiliData.bvid}--${playMusic.value.song?.ar?.[0]?.id || 0}--${playMusic.value.bilibiliData.cid}`; favoriteId = `${playMusic.value.bilibiliData.bvid}--${playMusic.value.song?.ar?.[0]?.id || 0}--${playMusic.value.bilibiliData.cid}`;
} }
} }
if (isFavorite.value) { if (isFavorite.value) {
playerStore.removeFromFavorite(favoriteId); playerStore.removeFromFavorite(favoriteId);
} else { } else {
@@ -490,7 +489,7 @@ const openPlayListDrawer = () => {
@apply absolute opacity-0 invisible transition-all duration-300 bottom-[30px] left-1/2 -translate-x-1/2 h-[180px] px-2 py-4 rounded-xl; @apply absolute opacity-0 invisible transition-all duration-300 bottom-[30px] left-1/2 -translate-x-1/2 h-[180px] px-2 py-4 rounded-xl;
@apply bg-light dark:bg-dark-200; @apply bg-light dark:bg-dark-200;
@apply border border-gray-200 dark:border-gray-700; @apply border border-gray-200 dark:border-gray-700;
.volume-percentage { .volume-percentage {
@apply absolute -top-6 left-1/2 -translate-x-1/2 text-xs font-medium bg-light dark:bg-dark-200 px-2 py-1 rounded-md; @apply absolute -top-6 left-1/2 -translate-x-1/2 text-xs font-medium bg-light dark:bg-dark-200 px-2 py-1 rounded-md;
@apply border border-gray-200 dark:border-gray-700; @apply border border-gray-200 dark:border-gray-700;
@@ -728,7 +727,6 @@ const openPlayListDrawer = () => {
background: var(--hover-color-dark); background: var(--hover-color-dark);
} }
.playback-rate-badge { .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; @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; font-weight: 500;

View File

@@ -1,15 +1,20 @@
<template> <template>
<!-- 透明遮罩层点击任意位置关闭 --> <!-- 透明遮罩层点击任意位置关闭 -->
<div v-if="internalVisible" class="fixed-overlay" @click="closePanel"></div> <div v-if="internalVisible" class="fixed-overlay" @click="closePanel"></div>
<!-- 使用animate.css进行动画效果 --> <!-- 使用animate.css进行动画效果 -->
<div <div
v-if="internalVisible" v-if="internalVisible"
class="playlist-panel" class="playlist-panel"
:class="[ :class="[
'animate__animated', 'animate__animated',
closing ? (isMobile ? 'animate__slideOutDown' : 'animate__slideOutRight') : closing
(isMobile ? 'animate__slideInUp' : 'animate__slideInRight') ? isMobile
? 'animate__slideOutDown'
: 'animate__slideOutRight'
: isMobile
? 'animate__slideInUp'
: 'animate__slideInRight'
]" ]"
> >
<div class="playlist-panel-header"> <div class="playlist-panel-header">
@@ -21,7 +26,7 @@
<i class="iconfont ri-delete-bin-line"></i> <i class="iconfont ri-delete-bin-line"></i>
</div> </div>
</template> </template>
{{ t('player.playList.clearAll')}} {{ t('player.playList.clearAll') }}
</n-tooltip> </n-tooltip>
<div class="close-btn" @click="closePanel"> <div class="close-btn" @click="closePanel">
<i class="iconfont ri-close-line"></i> <i class="iconfont ri-close-line"></i>
@@ -31,7 +36,7 @@
<div class="playlist-panel-content"> <div class="playlist-panel-content">
<div v-if="playList.length === 0" class="empty-playlist"> <div v-if="playList.length === 0" class="empty-playlist">
<i class="iconfont ri-music-2-line"></i> <i class="iconfont ri-music-2-line"></i>
<p>{{ t('player.playList.empty')}}</p> <p>{{ t('player.playList.empty') }}</p>
</div> </div>
<n-virtual-list v-else ref="playListRef" :item-size="62" item-resizable :items="playList"> <n-virtual-list v-else ref="playListRef" :item-size="62" item-resizable :items="playList">
<template #default="{ item }"> <template #default="{ item }">
@@ -52,9 +57,10 @@
</template> </template>
<script setup lang="ts"> <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 { useI18n } from 'vue-i18n';
import { useMessage, useDialog } from 'naive-ui';
import SongItem from '@/components/common/SongItem.vue'; import SongItem from '@/components/common/SongItem.vue';
import { usePlayerStore } from '@/store/modules/player'; import { usePlayerStore } from '@/store/modules/player';
import type { SongResult } from '@/type/music'; import type { SongResult } from '@/type/music';
@@ -78,27 +84,31 @@ const show = computed({
}); });
// 监听外部可见性变化 // 监听外部可见性变化
watch(show, (newValue) => { watch(
if (newValue) { show,
// 打开面板 (newValue) => {
internalVisible.value = true; if (newValue) {
closing.value = false; // 打开面板
// 在下一个渲染周期后滚动到当前歌曲 internalVisible.value = true;
nextTick(() => { closing.value = false;
scrollToCurrentSong(); // 在下一个渲染周期后滚动到当前歌曲
}); nextTick(() => {
} else { scrollToCurrentSong();
// 如果已经是关闭状态,不需要处理 });
if (!internalVisible.value) return; } else {
// 如果已经是关闭状态,不需要处理
// 开始关闭动画 if (!internalVisible.value) return;
closing.value = true;
// 等待动画完成后再隐藏组件 // 开始关闭动画
setTimeout(() => { closing.value = true;
internalVisible.value = false; // 等待动画完成后再隐藏组件
}, 400); // 动画持续时间 setTimeout(() => {
} internalVisible.value = false;
}, { immediate: true }); }, 400); // 动画持续时间
}
},
{ immediate: true }
);
// 播放列表 // 播放列表
const playList = computed(() => playerStore.playList as SongResult[]); const playList = computed(() => playerStore.playList as SongResult[]);
@@ -118,10 +128,10 @@ const handleClearPlaylist = () => {
return; return;
} }
if(isMobile.value){ if (isMobile.value) {
closePanel(); closePanel();
} }
dialog.warning({ dialog.warning({
title: t('player.playList.clearConfirmTitle'), title: t('player.playList.clearConfirmTitle'),
content: t('player.playList.clearConfirmContent'), content: t('player.playList.clearConfirmContent'),
@@ -159,12 +169,12 @@ const scrollToCurrentSong = () => {
if (playListRef.value && playList.value.length > 0) { if (playListRef.value && playList.value.length > 0) {
const index = playerStore.playListIndex; const index = playerStore.playListIndex;
console.log('滚动到歌曲索引:', index); console.log('滚动到歌曲索引:', index);
playListRef.value.scrollTo({ playListRef.value.scrollTo({
top: (index > 3 ? (index - 3) : 0) * 62, top: (index > 3 ? index - 3 : 0) * 62
}); });
} }
}, 100); }, 100);
}; };
// 删除歌曲 // 删除歌曲
const handleDeleteSong = (song: SongResult) => { const handleDeleteSong = (song: SongResult) => {
@@ -185,36 +195,36 @@ const handleDeleteSong = (song: SongResult) => {
height: 70vh; height: 70vh;
top: 15vh; // 距离顶部15% top: 15vh; // 距离顶部15%
animation-duration: 0.4s !important; // 动画持续时间 animation-duration: 0.4s !important; // 动画持续时间
@apply bg-light dark:bg-dark shadow-2xl dark:border dark:border-gray-700; @apply bg-light dark:bg-dark shadow-2xl dark:border dark:border-gray-700;
&-header { &-header {
@apply flex items-center justify-between px-4 py-2 border-b border-gray-100 dark:border-gray-900; @apply flex items-center justify-between px-4 py-2 border-b border-gray-100 dark:border-gray-900;
backdrop-filter: blur(10px); backdrop-filter: blur(10px);
background-color: rgba(255, 255, 255, 0.7); background-color: rgba(255, 255, 255, 0.7);
.dark & { .dark & {
background-color: rgba(18, 18, 18, 0.7); background-color: rgba(18, 18, 18, 0.7);
} }
.title { .title {
@apply text-base font-medium text-gray-800 dark:text-gray-200; @apply text-base font-medium text-gray-800 dark:text-gray-200;
} }
.header-actions { .header-actions {
@apply flex items-center; @apply flex items-center;
} }
.action-btn, .action-btn,
.close-btn { .close-btn {
@apply w-8 h-8 flex items-center justify-center rounded-full cursor-pointer mx-1 text-gray-800 dark:text-gray-200; @apply w-8 h-8 flex items-center justify-center rounded-full cursor-pointer mx-1 text-gray-800 dark:text-gray-200;
@apply hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors; @apply hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors;
.iconfont { .iconfont {
@apply text-xl; @apply text-xl;
} }
} }
.action-btn { .action-btn {
@apply text-gray-500 dark:text-gray-400; @apply text-gray-500 dark:text-gray-400;
&:hover { &:hover {
@@ -222,7 +232,7 @@ const handleDeleteSong = (song: SongResult) => {
} }
} }
} }
&-content { &-content {
@apply h-[calc(70vh-60px)] overflow-hidden; @apply h-[calc(70vh-60px)] overflow-hidden;
} }
@@ -230,11 +240,11 @@ const handleDeleteSong = (song: SongResult) => {
.empty-playlist { .empty-playlist {
@apply flex flex-col items-center justify-center h-full text-gray-400 dark:text-gray-500; @apply flex flex-col items-center justify-center h-full text-gray-400 dark:text-gray-500;
.iconfont { .iconfont {
@apply text-5xl mb-4; @apply text-5xl mb-4;
} }
p { p {
@apply text-sm; @apply text-sm;
} }
@@ -267,10 +277,10 @@ const handleDeleteSong = (song: SongResult) => {
border-left: none; border-left: none;
border-top: 1px solid theme('colors.gray.200'); border-top: 1px solid theme('colors.gray.200');
box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.1); box-shadow: 0 -5px 20px rgba(0, 0, 0, 0.1);
&-header { &-header {
@apply text-center relative px-4; @apply text-center relative px-4;
&::before { &::before {
content: ''; content: '';
position: absolute; position: absolute;
@@ -283,14 +293,14 @@ const handleDeleteSong = (song: SongResult) => {
background-color: rgba(150, 150, 150, 0.3); background-color: rgba(150, 150, 150, 0.3);
} }
} }
&-content { &-content {
height: calc(80vh - 60px); height: calc(80vh - 60px);
@apply px-4; @apply px-4;
.delete-btn{ .delete-btn {
@apply visible; @apply visible;
} }
} }
} }
} }
</style> </style>

View File

@@ -11,9 +11,9 @@
<template #trigger> <template #trigger>
<n-tooltip trigger="hover" :z-index="9999999"> <n-tooltip trigger="hover" :z-index="9999999">
<template #trigger> <template #trigger>
<i <i
class="iconfont ri-refresh-line" class="iconfont ri-refresh-line"
:class="{ 'text-green-500': isReparse, 'animate-spin': isReparsing }" :class="{ 'text-green-500': isReparse, 'animate-spin': isReparsing }"
></i> ></i>
</template> </template>
{{ t('player.playBar.reparse') }} {{ t('player.playBar.reparse') }}
@@ -24,11 +24,11 @@
<div class="text-sm opacity-70 mb-3">{{ t('player.reparse.desc') }}</div> <div class="text-sm opacity-70 mb-3">{{ t('player.reparse.desc') }}</div>
<div class="mb-3"> <div class="mb-3">
<div class="flex flex-col space-y-2"> <div class="flex flex-col space-y-2">
<div <div
v-for="source in musicSourceOptions" v-for="source in musicSourceOptions"
:key="source.value" :key="source.value"
class="source-button flex items-center p-2 rounded-lg cursor-pointer transition-all duration-200 bg-light-200 dark:bg-dark-200 hover:bg-light-300 dark:hover:bg-dark-300" class="source-button flex items-center p-2 rounded-lg cursor-pointer transition-all duration-200 bg-light-200 dark:bg-dark-200 hover:bg-light-300 dark:hover:bg-dark-300"
:class="{ :class="{
'bg-green-50 dark:bg-green-900/20 text-green-500': isCurrentSource(source.value), 'bg-green-50 dark:bg-green-900/20 text-green-500': isCurrentSource(source.value),
'opacity-50 cursor-not-allowed': isReparsing || playMusic.source === 'bilibili' 'opacity-50 cursor-not-allowed': isReparsing || playMusic.source === 'bilibili'
}" }"
@@ -40,10 +40,16 @@
<div class="flex-1 text-sm whitespace-nowrap overflow-hidden text-ellipsis"> <div class="flex-1 text-sm whitespace-nowrap overflow-hidden text-ellipsis">
{{ source.label }} {{ source.label }}
</div> </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> <i class="ri-loader-4-line animate-spin"></i>
</div> </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> <i class="ri-check-line"></i>
</div> </div>
</div> </div>
@@ -53,7 +59,10 @@
{{ t('player.reparse.bilibiliNotSupported') }} {{ t('player.reparse.bilibiliNotSupported') }}
</div> </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"> <div class="flex items-center justify-center w-6 h-6 mr-3 text-lg">
<i class="ri-close-circle-line"></i> <i class="ri-close-circle-line"></i>
</div> </div>
@@ -66,13 +75,14 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { useMessage } from 'naive-ui';
import { ref, watch } from 'vue'; import { ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useMessage } from 'naive-ui';
import { playMusic } from '@/hooks/MusicHook'; import { playMusic } from '@/hooks/MusicHook';
import { audioService } from '@/services/audioService';
import { usePlayerStore } from '@/store/modules/player'; import { usePlayerStore } from '@/store/modules/player';
import type { Platform } from '@/types/music'; import type { Platform } from '@/types/music';
import { audioService } from '@/services/audioService';
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();
const { t } = useI18n(); const { t } = useI18n();
@@ -104,13 +114,13 @@ const isCurrentSource = (source: Platform) => {
// 获取音源图标 // 获取音源图标
const getSourceIcon = (source: Platform) => { const getSourceIcon = (source: Platform) => {
const iconMap: Record<Platform, string> = { const iconMap: Record<Platform, string> = {
'migu': 'ri-music-2-fill', migu: 'ri-music-2-fill',
'kugou': 'ri-music-fill', kugou: 'ri-music-fill',
'qq': 'ri-qq-fill', qq: 'ri-qq-fill',
'joox': 'ri-disc-fill', joox: 'ri-disc-fill',
'pyncmd': 'ri-netease-cloud-music-fill', pyncmd: 'ri-netease-cloud-music-fill',
'bilibili': 'ri-bilibili-fill', bilibili: 'ri-bilibili-fill',
'gdmusic': 'ri-google-fill' gdmusic: 'ri-google-fill'
}; };
return iconMap[source] || 'ri-music-2-fill'; return iconMap[source] || 'ri-music-2-fill';
@@ -120,11 +130,12 @@ const getSourceIcon = (source: Platform) => {
const initSelectedSources = () => { const initSelectedSources = () => {
const songId = String(playMusic.value.id); const songId = String(playMusic.value.id);
const savedSource = localStorage.getItem(`song_source_${songId}`); const savedSource = localStorage.getItem(`song_source_${songId}`);
if (savedSource) { if (savedSource) {
try { try {
selectedSourcesValue.value = JSON.parse(savedSource); selectedSourcesValue.value = JSON.parse(savedSource);
} catch (e) { } catch (e) {
console.error('解析保存的音源设置失败:', e);
selectedSourcesValue.value = []; selectedSourcesValue.value = [];
} }
} else { } else {
@@ -144,20 +155,20 @@ const directReparseMusic = async (source: Platform) => {
if (isReparsing.value || playMusic.value.source === 'bilibili') { if (isReparsing.value || playMusic.value.source === 'bilibili') {
return; return;
} }
try { try {
isReparsing.value = true; isReparsing.value = true;
currentReparsingSource.value = source; currentReparsingSource.value = source;
// 更新选中的音源值为当前点击的音源 // 更新选中的音源值为当前点击的音源
const songId = String(playMusic.value.id); const songId = String(playMusic.value.id);
selectedSourcesValue.value = [source]; selectedSourcesValue.value = [source];
// 保存到localStorage // 保存到localStorage
localStorage.setItem(`song_source_${songId}`, JSON.stringify(selectedSourcesValue.value)); localStorage.setItem(`song_source_${songId}`, JSON.stringify(selectedSourcesValue.value));
const success = await playerStore.reparseCurrentSong(source); const success = await playerStore.reparseCurrentSong(source);
if (success) { if (success) {
message.success(t('player.reparse.success')); message.success(t('player.reparse.success'));
} else { } else {
@@ -173,48 +184,55 @@ const directReparseMusic = async (source: Platform) => {
}; };
// 监听歌曲ID变化初始化音源设置 // 监听歌曲ID变化初始化音源设置
watch(() => playMusic.value.id, () => { watch(
if (playMusic.value.id) { () => playMusic.value.id,
initSelectedSources(); () => {
} if (playMusic.value.id) {
}, { immediate: true }); initSelectedSources();
}
},
{ immediate: true }
);
// 监听歌曲变化,检查是否有自定义音源 // 监听歌曲变化,检查是否有自定义音源
watch(() => playMusic.value.id, async (newId) => { watch(
if (newId) { () => playMusic.value.id,
const songId = String(newId); async (newId) => {
const savedSource = localStorage.getItem(`song_source_${songId}`); 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[]; if (savedSource && playMusic.value.source !== 'bilibili') {
console.log(`检测到歌曲ID ${songId} 有自定义音源设置:`, sources); try {
const sources = JSON.parse(savedSource) as Platform[];
// 当URL加载失败或过期时自动应用自定义音源重新加载 console.log(`检测到歌曲ID ${songId} 有自定义音源设置:`, sources);
audioService.on('url_expired', async (trackInfo) => {
if (trackInfo && trackInfo.id === playMusic.value.id) { // 当URL加载失败或过期时自动应用自定义音源重新加载
console.log('URL已过期自动应用自定义音源重新加载'); audioService.on('url_expired', async (trackInfo) => {
try { if (trackInfo && trackInfo.id === playMusic.value.id) {
isReparsing.value = true; console.log('URL已过期自动应用自定义音源重新加载');
const success = await playerStore.reparseCurrentSong(sources[0]); try {
if (!success) { 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')); 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) {
} catch (e) { console.error('解析保存的音源设置失败:', e);
console.error('解析保存的音源设置失败:', e); }
} }
} }
} }
}); );
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
@@ -223,8 +241,12 @@ watch(() => playMusic.value.id, async (newId) => {
} }
@keyframes spin { @keyframes spin {
0% { transform: rotate(0deg); } 0% {
100% { transform: rotate(360deg); } transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
} }
.animate-spin { .animate-spin {
@@ -240,4 +262,4 @@ watch(() => playMusic.value.id, async (newId) => {
.iconfont { .iconfont {
@apply text-2xl mx-3; @apply text-2xl mx-3;
} }
</style> </style>

View File

@@ -8,14 +8,14 @@
<div class="progress-track"></div> <div class="progress-track"></div>
<div class="progress-fill" :style="{ width: `${(nowTime / allTime) * 100}%` }"></div> <div class="progress-fill" :style="{ width: `${(nowTime / allTime) * 100}%` }"></div>
</div> </div>
<!-- 时间显示 --> <!-- 时间显示 -->
<div class="time-display"> <div class="time-display">
<span class="current-time">{{ formatTime(nowTime) }}</span> <span class="current-time">{{ formatTime(nowTime) }}</span>
<span class="total-time">{{ formatTime(allTime) }}</span> <span class="total-time">{{ formatTime(allTime) }}</span>
</div> </div>
</div> </div>
<!-- 主控制区域 --> <!-- 主控制区域 -->
<div class="controls-section"> <div class="controls-section">
<div class="left-controls"> <div class="left-controls">
@@ -23,24 +23,24 @@
<i class="iconfont" :class="playModeIcon"></i> <i class="iconfont" :class="playModeIcon"></i>
</button> </button>
</div> </div>
<div class="center-controls"> <div class="center-controls">
<!-- 上一首 --> <!-- 上一首 -->
<button class="control-btn" @click="handlePrev"> <button class="control-btn" @click="handlePrev">
<i class="iconfont icon-prev"></i> <i class="iconfont icon-prev"></i>
</button> </button>
<!-- 播放/暂停 --> <!-- 播放/暂停 -->
<button class="control-btn play-btn" @click="playMusicEvent"> <button class="control-btn play-btn" @click="playMusicEvent">
<i class="iconfont" :class="play ? 'icon-stop' : 'icon-play'"></i> <i class="iconfont" :class="play ? 'icon-stop' : 'icon-play'"></i>
</button> </button>
<!-- 下一首 --> <!-- 下一首 -->
<button class="control-btn" @click="handleNext"> <button class="control-btn" @click="handleNext">
<i class="iconfont icon-next"></i> <i class="iconfont icon-next"></i>
</button> </button>
</div> </div>
<div class="right-controls"> <div class="right-controls">
<!-- 播放列表按钮 --> <!-- 播放列表按钮 -->
<button class="control-btn small-btn" @click="openPlayListDrawer"> <button class="control-btn small-btn" @click="openPlayListDrawer">
@@ -48,7 +48,7 @@
</button> </button>
</div> </div>
</div> </div>
<!-- 底部控制区域 --> <!-- 底部控制区域 -->
<div class="bottom-section"> <div class="bottom-section">
<div class="spacer"></div> <div class="spacer"></div>
@@ -56,9 +56,9 @@
<div class="volume-control"> <div class="volume-control">
<i class="iconfont" :class="getVolumeIcon" @click="mute"></i> <i class="iconfont" :class="getVolumeIcon" @click="mute"></i>
<div class="volume-slider"> <div class="volume-slider">
<n-slider <n-slider
v-model:value="volumeSlider" v-model:value="volumeSlider"
:step="1" :step="1"
:tooltip="false" :tooltip="false"
@wheel.prevent="handleVolumeWheel" @wheel.prevent="handleVolumeWheel"
></n-slider> ></n-slider>
@@ -70,18 +70,22 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue'; import { computed, onMounted, ref, watch } from 'vue';
import { secondToMinute } from '@/utils';
import { allTime, nowTime, playMusic } from '@/hooks/MusicHook'; import { allTime, nowTime, playMusic } from '@/hooks/MusicHook';
import { audioService } from '@/services/audioService'; import { audioService } from '@/services/audioService';
import { usePlayerStore } from '@/store/modules/player'; import { usePlayerStore } from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings'; import { useSettingsStore } from '@/store/modules/settings';
import { secondToMinute } from '@/utils';
const props = withDefaults(defineProps<{ const props = withDefaults(
isDark: boolean; defineProps<{
}>(), { isDark: boolean;
isDark: false }>(),
}); {
isDark: false
}
);
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();
const settingsStore = useSettingsStore(); const settingsStore = useSettingsStore();
@@ -184,27 +188,28 @@ const isDarkMode = computed(() => settingsStore.theme === 'dark' || props.isDark
// 主题颜色应用函数 // 主题颜色应用函数
const applyThemeColor = (colorValue: string) => { const applyThemeColor = (colorValue: string) => {
if (!colorValue || !playBarRef.value) return; if (!colorValue || !playBarRef.value) return;
console.log('应用主题色:', colorValue); console.log('应用主题色:', colorValue);
const playBarElement = playBarRef.value; const playBarElement = playBarRef.value;
// 解析RGB值 // 解析RGB值
const rgbMatch = colorValue.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/); const rgbMatch = colorValue.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
if (rgbMatch) { if (rgbMatch) {
const [_, r, g, b] = rgbMatch.map(Number); const [_, r, g, b] = rgbMatch.map(Number);
// 计算颜色亮度 (0-255) // 计算颜色亮度 (0-255)
// 使用加权平均值公式: 0.299*R + 0.587*G + 0.114*B // 使用加权平均值公式: 0.299*R + 0.587*G + 0.114*B
const brightness = Math.round(0.299 * r + 0.587 * g + 0.114 * b); const brightness = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
console.log(`主题色亮度: ${brightness}/255`); console.log(`主题色亮度: ${brightness}/255`);
// 设置主色 // 设置主色
playBarElement.style.setProperty('--fill-color', colorValue); 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)})`; 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); playBarElement.style.setProperty('--fill-color-alt', darkenedColor);
@@ -213,7 +218,8 @@ const applyThemeColor = (colorValue: string) => {
playBarElement.style.setProperty('--high-contrast-color', '#000000'); // 高对比度颜色 playBarElement.style.setProperty('--high-contrast-color', '#000000'); // 高对比度颜色
playBarElement.classList.add('light-theme-color'); playBarElement.classList.add('light-theme-color');
playBarElement.classList.remove('dark-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)})`; 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); playBarElement.style.setProperty('--fill-color-alt', lightenedColor);
@@ -234,7 +240,7 @@ const applyThemeColor = (colorValue: string) => {
playBarElement.classList.remove('light-theme-color'); playBarElement.classList.remove('light-theme-color');
playBarElement.classList.remove('dark-theme-color'); playBarElement.classList.remove('dark-theme-color');
} }
// 设置亮色(用于高亮效果) // 设置亮色(用于高亮效果)
const lightenedColor = `rgb(${Math.min(255, r + 40)}, ${Math.min(255, g + 40)}, ${Math.min(255, b + 40)})`; const lightenedColor = `rgb(${Math.min(255, r + 40)}, ${Math.min(255, g + 40)}, ${Math.min(255, b + 40)})`;
playBarElement.style.setProperty('--fill-color-light', lightenedColor); playBarElement.style.setProperty('--fill-color-light', lightenedColor);
@@ -250,11 +256,14 @@ const applyThemeColor = (colorValue: string) => {
}; };
// 监听主题色变化 // 监听主题色变化
watch(() => playerStore.playMusic.primaryColor, (newVal) => { watch(
if (newVal) { () => playerStore.playMusic.primaryColor,
applyThemeColor(newVal); (newVal) => {
if (newVal) {
applyThemeColor(newVal);
}
} }
}); );
onMounted(() => { onMounted(() => {
if (playerStore.playMusic?.primaryColor) { if (playerStore.playMusic?.primaryColor) {
@@ -270,11 +279,11 @@ onMounted(() => {
@apply w-full; @apply w-full;
border-radius: 12px; border-radius: 12px;
transition: all 0.3s ease; transition: all 0.3s ease;
/* 默认变量 */ /* 默认变量 */
--text-on-fill: #ffffff; --text-on-fill: #ffffff;
--high-contrast-color: #ffffff; --high-contrast-color: #ffffff;
&.dark-theme { &.dark-theme {
--text-color: #333333; --text-color: #333333;
--muted-color: rgba(0, 0, 0, 0.6); --muted-color: rgba(0, 0, 0, 0.6);
@@ -287,7 +296,7 @@ onMounted(() => {
--button-bg: rgba(0, 0, 0, 0.1); --button-bg: rgba(0, 0, 0, 0.1);
--button-hover: rgba(0, 0, 0, 0.2); --button-hover: rgba(0, 0, 0, 0.2);
} }
&:not(.dark-theme) { &:not(.dark-theme) {
--text-color: #f1f1f1; --text-color: #f1f1f1;
--muted-color: rgba(255, 255, 255, 0.6); --muted-color: rgba(255, 255, 255, 0.6);
@@ -300,37 +309,45 @@ onMounted(() => {
--button-bg: rgba(255, 255, 255, 0.05); --button-bg: rgba(255, 255, 255, 0.05);
--button-hover: rgba(255, 255, 255, 0.1); --button-hover: rgba(255, 255, 255, 0.1);
} }
/* 极亮主题色适配 */ /* 极亮主题色适配 */
&.light-theme-color { &.light-theme-color {
.progress-fill { .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 { .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); color: var(--text-on-fill);
} }
.volume-control .iconfont:hover { .volume-control .iconfont:hover {
color: var(--fill-color-alt); color: var(--fill-color-alt);
} }
} }
/* 极暗主题色适配 */ /* 极暗主题色适配 */
&.dark-theme-color { &.dark-theme-color {
.progress-fill { .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 { .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 { .iconfont {
text-shadow: 0 1px 3px rgba(0,0,0,0.5); text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
} }
} }
.volume-control .iconfont:hover { .volume-control .iconfont:hover {
color: var(--fill-color-light); color: var(--fill-color-light);
} }
@@ -343,47 +360,48 @@ onMounted(() => {
.top-section { .top-section {
@apply mb-3; @apply mb-3;
.progress-bar { .progress-bar {
@apply relative cursor-pointer h-2 mb-2 w-full; @apply relative cursor-pointer h-2 mb-2 w-full;
.progress-track { .progress-track {
@apply absolute inset-0 rounded-full transition-all duration-150; @apply absolute inset-0 rounded-full transition-all duration-150;
background-color: var(--track-color); background-color: var(--track-color);
} }
.progress-fill { .progress-fill {
@apply absolute top-0 left-0 h-full rounded-full transition-all duration-150; @apply absolute top-0 left-0 h-full rounded-full transition-all duration-150;
background: linear-gradient(90deg, var(--fill-color), var(--fill-color-light)); background: linear-gradient(90deg, var(--fill-color), var(--fill-color-light));
box-shadow: 0 0 8px var(--fill-color-transparent); box-shadow: 0 0 8px var(--fill-color-transparent);
} }
&:hover { &:hover {
.progress-track{ .progress-track {
background-color: var(--track-color-hover); background-color: var(--track-color-hover);
} }
.progress-track, .progress-fill { .progress-track,
.progress-fill {
@apply h-full; @apply h-full;
} }
.progress-fill { .progress-fill {
box-shadow: 0 0 12px var(--fill-color-transparent); box-shadow: 0 0 12px var(--fill-color-transparent);
} }
} }
} }
.time-display { .time-display {
@apply flex justify-between text-base; @apply flex justify-between text-base;
color: var(--muted-color); color: var(--muted-color);
.time-separator { .time-separator {
@apply mx-1; @apply mx-1;
} }
.current-time { .current-time {
opacity: 0.8; opacity: 0.8;
transition: opacity 0.3s ease; transition: opacity 0.3s ease;
&:hover { &:hover {
opacity: 1; opacity: 1;
} }
@@ -393,11 +411,12 @@ onMounted(() => {
.controls-section { .controls-section {
@apply flex items-center justify-between mb-4; @apply flex items-center justify-between mb-4;
.left-controls, .right-controls { .left-controls,
.right-controls {
@apply flex items-center; @apply flex items-center;
} }
.center-controls { .center-controls {
@apply flex items-center justify-center space-x-6; @apply flex items-center justify-center space-x-6;
} }
@@ -414,39 +433,39 @@ onMounted(() => {
width: 32px; width: 32px;
height: 32px; height: 32px;
cursor: pointer; cursor: pointer;
&:hover { &:hover {
background-color: var(--button-bg); background-color: var(--button-bg);
transform: scale(1.05); transform: scale(1.05);
} }
&:active { &:active {
background-color: var(--button-hover); background-color: var(--button-hover);
transform: scale(0.95); transform: scale(0.95);
} }
&.play-btn { &.play-btn {
background: linear-gradient(145deg, var(--fill-color), var(--fill-color-alt)); background: linear-gradient(145deg, var(--fill-color), var(--fill-color-alt));
color: var(--text-on-fill); color: var(--text-on-fill);
width: 46px; width: 46px;
height: 46px; height: 46px;
box-shadow: 0 3px 8px var(--fill-color-transparent); box-shadow: 0 3px 8px var(--fill-color-transparent);
&:hover { &:hover {
box-shadow: 0 4px 12px var(--fill-color-transparent); box-shadow: 0 4px 12px var(--fill-color-transparent);
} }
.iconfont { .iconfont {
font-size: 1.25rem; font-size: 1.25rem;
} }
} }
&.small-btn { &.small-btn {
@apply text-2xl; @apply text-2xl;
width: 28px; width: 28px;
height: 28px; height: 28px;
} }
.iconfont { .iconfont {
@apply text-2xl; @apply text-2xl;
} }
@@ -455,42 +474,46 @@ onMounted(() => {
.volume-control { .volume-control {
@apply flex items-center space-x-2; @apply flex items-center space-x-2;
color: var(--text-color); color: var(--text-color);
.iconfont { .iconfont {
@apply cursor-pointer text-base; @apply cursor-pointer text-base;
transition: transform 0.2s ease, color 0.2s ease; transition:
transform 0.2s ease,
color 0.2s ease;
&:hover { &:hover {
transform: scale(1.1); transform: scale(1.1);
color: var(--fill-color); color: var(--fill-color);
} }
} }
.volume-slider { .volume-slider {
@apply w-24; @apply w-24;
:deep(.n-slider) { :deep(.n-slider) {
--n-rail-height: 3px; --n-rail-height: 3px;
--n-fill-color: var(--fill-color); --n-fill-color: var(--fill-color);
--n-rail-color: var(--track-color); --n-rail-color: var(--track-color);
--n-handle-size: 12px; --n-handle-size: 12px;
.n-slider-rail { .n-slider-rail {
@apply rounded-full; @apply rounded-full;
} }
.n-slider-rail__fill { .n-slider-rail__fill {
background: linear-gradient(90deg, var(--fill-color), var(--fill-color-light)); background: linear-gradient(90deg, var(--fill-color), var(--fill-color-light));
box-shadow: 0 0 6px var(--fill-color-transparent); box-shadow: 0 0 6px var(--fill-color-transparent);
} }
.n-slider-handle { .n-slider-handle {
@apply opacity-0 transition-opacity duration-200; @apply opacity-0 transition-opacity duration-200;
background: white; 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); border: 2px solid var(--fill-color);
} }
&:hover .n-slider-handle { &:hover .n-slider-handle {
@apply opacity-100; @apply opacity-100;
} }
@@ -506,4 +529,4 @@ onMounted(() => {
color: var(--fill-color); color: var(--fill-color);
text-shadow: 0 0 8px var(--fill-color-transparent); text-shadow: 0 0 8px var(--fill-color-transparent);
} }
</style> </style>

View File

@@ -1,7 +1,7 @@
<template> <template>
<div class="sleep-timer-content"> <div class="sleep-timer-content">
<h3 class="timer-title">{{ t('player.sleepTimer.title') }}</h3> <h3 class="timer-title">{{ t('player.sleepTimer.title') }}</h3>
<div v-if="hasTimerActive" class="sleep-timer-active"> <div v-if="hasTimerActive" class="sleep-timer-active">
<div class="timer-status"> <div class="timer-status">
<template v-if="timerType === 'time'"> <template v-if="timerType === 'time'">
@@ -9,19 +9,21 @@
</template> </template>
<template v-else-if="timerType === 'songs'"> <template v-else-if="timerType === 'songs'">
<div class="timer-value">{{ remainingSongs }}</div> <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>
<template v-else-if="timerType === 'end'"> <template v-else-if="timerType === 'end'">
<div class="timer-value">{{ t('player.sleepTimer.activeUntilEnd') }}</div> <div class="timer-value">{{ t('player.sleepTimer.activeUntilEnd') }}</div>
<div class="timer-label">{{ t('player.sleepTimer.afterPlaylist') }}</div> <div class="timer-label">{{ t('player.sleepTimer.afterPlaylist') }}</div>
</template> </template>
</div> </div>
<n-button type="error" class="cancel-timer-btn" @click="handleCancelTimer" round> <n-button type="error" class="cancel-timer-btn" @click="handleCancelTimer" round>
{{ t('player.sleepTimer.cancel') }} {{ t('player.sleepTimer.cancel') }}
</n-button> </n-button>
</div> </div>
<div v-else class="sleep-timer-options"> <div v-else class="sleep-timer-options">
<!-- 按时间定时 --> <!-- 按时间定时 -->
<div class="option-section"> <div class="option-section">
@@ -59,7 +61,7 @@
</div> </div>
</div> </div>
</div> </div>
<!-- 按歌曲数定时 --> <!-- 按歌曲数定时 -->
<div class="option-section"> <div class="option-section">
<h4 class="option-title">{{ t('player.sleepTimer.songsMode') }}</h4> <h4 class="option-title">{{ t('player.sleepTimer.songsMode') }}</h4>
@@ -96,7 +98,7 @@
</div> </div>
</div> </div>
</div> </div>
<!-- 播放完列表后关闭 --> <!-- 播放完列表后关闭 -->
<div class="option-section playlist-end-section"> <div class="option-section playlist-end-section">
<n-button block class="playlist-end-btn" @click="handleSetPlaylistEndTimer" round> <n-button block class="playlist-end-btn" @click="handleSetPlaylistEndTimer" round>
@@ -108,9 +110,10 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { computed, ref, onMounted, onUnmounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { usePlayerStore } from '@/store/modules/player'; import { usePlayerStore } from '@/store/modules/player';
const { t } = useI18n(); const { t } = useI18n();
@@ -163,22 +166,22 @@ function handleCancelTimer() {
const formattedRemainingTime = computed(() => { const formattedRemainingTime = computed(() => {
// 依赖刷新触发器强制更新 // 依赖刷新触发器强制更新
void refreshTrigger.value; void refreshTrigger.value;
if (timerType.value !== 'time' || !sleepTimer.value.endTime) { if (timerType.value !== 'time' || !sleepTimer.value.endTime) {
return '00:00:00'; return '00:00:00';
} }
const remaining = Math.max(0, sleepTimer.value.endTime - Date.now()); const remaining = Math.max(0, sleepTimer.value.endTime - Date.now());
const totalSeconds = Math.floor(remaining / 1000); const totalSeconds = Math.floor(remaining / 1000);
const hours = Math.floor(totalSeconds / 3600); const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60); const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = Math.floor(totalSeconds % 60); const seconds = Math.floor(totalSeconds % 60);
const formattedHours = hours.toString().padStart(2, '0'); const formattedHours = hours.toString().padStart(2, '0');
const formattedMinutes = minutes.toString().padStart(2, '0'); const formattedMinutes = minutes.toString().padStart(2, '0');
const formattedSeconds = seconds.toString().padStart(2, '0'); const formattedSeconds = seconds.toString().padStart(2, '0');
return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`; return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}); });
@@ -190,10 +193,10 @@ onMounted(() => {
if (hasTimerActive.value && timerType.value === 'time') { if (hasTimerActive.value && timerType.value === 'time') {
startTimerUpdate(); startTimerUpdate();
} }
// 监听定时器状态变化 // 监听定时器状态变化
watch( watch(
() => [hasTimerActive.value, timerType.value], () => [hasTimerActive.value, timerType.value],
([newHasTimer, newType]) => { ([newHasTimer, newType]) => {
if (newHasTimer && newType === 'time') { if (newHasTimer && newType === 'time') {
startTimerUpdate(); startTimerUpdate();
@@ -207,7 +210,7 @@ onMounted(() => {
// 启动定时器更新UI // 启动定时器更新UI
function startTimerUpdate() { function startTimerUpdate() {
stopTimerUpdate(); // 先停止之前的计时器 stopTimerUpdate(); // 先停止之前的计时器
// 每秒更新UI // 每秒更新UI
timerInterval = window.setInterval(() => { timerInterval = window.setInterval(() => {
// 更新刷新触发器,强制重新计算 // 更新刷新触发器,强制重新计算
@@ -244,13 +247,15 @@ onUnmounted(() => {
.timer-status { .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; @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); 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; transition: all 0.3s ease;
// 定时值显示 // 定时值显示
.timer-value { .timer-value {
@apply text-4xl font-semibold mb-2 text-green-500; @apply text-4xl font-semibold mb-2 text-green-500;
&.countdown-timer { &.countdown-timer {
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
letter-spacing: 2px; letter-spacing: 2px;
@@ -266,11 +271,11 @@ onUnmounted(() => {
// 取消按钮 // 取消按钮
.cancel-timer-btn { .cancel-timer-btn {
@apply w-full py-3 text-base rounded-full transition-all duration-200; @apply w-full py-3 text-base rounded-full transition-all duration-200;
&:hover { &:hover {
@apply transform scale-105 shadow-md; @apply transform scale-105 shadow-md;
} }
&:active { &:active {
@apply transform scale-95; @apply transform scale-95;
} }
@@ -292,37 +297,44 @@ onUnmounted(() => {
} }
// 时间/歌曲选项容器 // 时间/歌曲选项容器
.time-options, .songs-options { .time-options,
.songs-options {
@apply flex flex-wrap gap-2; @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; @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); 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; @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; @apply dark:shadow-gray-900/20;
&:hover { &:hover {
@apply transform scale-105 shadow-md; @apply transform scale-105 shadow-md;
} }
&:active { &:active {
@apply transform scale-95; @apply transform scale-95;
} }
} }
// 自定义输入区域 // 自定义输入区域
.custom-time, .custom-songs { .custom-time,
.custom-songs {
@apply flex items-center space-x-2 mt-4 w-full; @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; @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; @apply py-2 px-4 rounded-full transition-all duration-200;
} }
} }
@@ -339,4 +351,4 @@ onUnmounted(() => {
} }
} }
} }
</style> </style>

View File

@@ -9,8 +9,9 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { storeToRefs } from 'pinia'; import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import { usePlayerStore } from '@/store/modules/player'; import { usePlayerStore } from '@/store/modules/player';
const { t } = useI18n(); const { t } = useI18n();
@@ -28,19 +29,18 @@ const checkTimerExpired = () => {
playerStore.clearSleepTimer(); playerStore.clearSleepTimer();
} }
} }
} };
// 在组件挂载时检查定时器状态 // 在组件挂载时检查定时器状态
onMounted(() => { onMounted(() => {
checkTimerExpired(); checkTimerExpired();
}); });
// 倒计时显示 // 倒计时显示
const formattedRemainingTime = computed(() => { const formattedRemainingTime = computed(() => {
// 依赖刷新触发器强制更新 // 依赖刷新触发器强制更新
void refreshTrigger.value; void refreshTrigger.value;
if (sleepTimer.value.type !== 'time' || !sleepTimer.value.endTime) { if (sleepTimer.value.type !== 'time' || !sleepTimer.value.endTime) {
if (sleepTimer.value.type === 'songs' && sleepTimer.value.remainingSongs) { if (sleepTimer.value.type === 'songs' && sleepTimer.value.remainingSongs) {
return t('player.sleepTimer.songsRemaining', { count: sleepTimer.value.remainingSongs }); return t('player.sleepTimer.songsRemaining', { count: sleepTimer.value.remainingSongs });
@@ -50,14 +50,14 @@ const formattedRemainingTime = computed(() => {
} }
return ''; return '';
} }
const remaining = Math.max(0, sleepTimer.value.endTime - Date.now()); const remaining = Math.max(0, sleepTimer.value.endTime - Date.now());
const totalSeconds = Math.floor(remaining / 1000); const totalSeconds = Math.floor(remaining / 1000);
const hours = Math.floor(totalSeconds / 3600); const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60); const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = Math.floor(totalSeconds % 60); const seconds = Math.floor(totalSeconds % 60);
if (hours > 0) { if (hours > 0) {
return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
} else { } else {
@@ -83,7 +83,7 @@ watch(
// 启动定时器更新UI // 启动定时器更新UI
function startTimerUpdate() { function startTimerUpdate() {
stopTimerUpdate(); // 先停止之前的计时器 stopTimerUpdate(); // 先停止之前的计时器
// 每秒更新UI // 每秒更新UI
timerUpdateInterval = window.setInterval(() => { timerUpdateInterval = window.setInterval(() => {
// 更新刷新触发器,强制重新计算 // 更新刷新触发器,强制重新计算
@@ -110,16 +110,15 @@ onUnmounted(() => {
</script> </script>
<style lang="scss" scoped> <style lang="scss" scoped>
.sleep-timer-countdown { .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; @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; z-index: 9998;
min-width: 80px; min-width: 80px;
text-align: center; text-align: center;
animation: fadeInDown 0.3s ease-out; animation: fadeInDown 0.3s ease-out;
-webkit-app-region: no-drag; -webkit-app-region: no-drag;
@keyframes fadeInDown { @keyframes fadeInDown {
from { from {
transform: translate(-50%, -150%); transform: translate(-50%, -150%);
@@ -130,11 +129,11 @@ onUnmounted(() => {
opacity: 1; opacity: 1;
} }
} }
span { span {
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
letter-spacing: 0.5px; letter-spacing: 0.5px;
font-weight: 500; font-weight: 500;
} }
} }
</style> </style>

View File

@@ -34,7 +34,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch, defineProps, defineEmits } from 'vue'; import { defineEmits, defineProps, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
const props = defineProps({ const props = defineProps({
@@ -113,4 +113,4 @@ const handleCancel = () => {
selectedTypes.value = []; selectedTypes.value = [];
visible.value = false; visible.value = false;
}; };
</script> </script>

View File

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

View File

@@ -46,10 +46,10 @@
</template> </template>
<script setup lang="ts"> <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 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({ const props = defineProps({
show: { show: {
@@ -92,7 +92,8 @@ const proxyRules: FormRules = {
validator: (_rule, value) => { validator: (_rule, value) => {
if (!value) return false; if (!value) return false;
// 简单的IP或域名验证 // 简单的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); return ipRegex.test(value);
} }
}, },
@@ -142,6 +143,7 @@ const handleProxyConfirm = async () => {
visible.value = false; visible.value = false;
message.success(t('settings.network.messages.proxySuccess')); message.success(t('settings.network.messages.proxySuccess'));
} catch (err) { } catch (err) {
console.error('代理设置验证失败:', err);
message.error(t('settings.network.messages.proxyError')); message.error(t('settings.network.messages.proxyError'));
} }
}; };
@@ -149,4 +151,4 @@ const handleProxyConfirm = async () => {
const handleCancel = () => { const handleCancel = () => {
visible.value = false; visible.value = false;
}; };
</script> </script>

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
import { cloneDeep } from 'lodash'; import { cloneDeep } from 'lodash';
import { useMessage } from 'naive-ui';
import { ref } from 'vue'; import { ref } from 'vue';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
import { useMessage } from 'naive-ui';
import { getSongUrl } from '@/store/modules/player'; import { getSongUrl } from '@/store/modules/player';
import type { SongResult } from '@/type/music'; import type { SongResult } from '@/type/music';
@@ -13,23 +13,23 @@ const ipcRenderer = isElectron ? window.electron.ipcRenderer : null;
const createDownloadManager = () => { const createDownloadManager = () => {
// 正在下载的文件集合 // 正在下载的文件集合
const activeDownloads = new Set<string>(); const activeDownloads = new Set<string>();
// 已经发送了通知的文件集合(避免重复通知) // 已经发送了通知的文件集合(避免重复通知)
const notifiedDownloads = new Set<string>(); const notifiedDownloads = new Set<string>();
// 事件监听器是否已初始化 // 事件监听器是否已初始化
let isInitialized = false; let isInitialized = false;
// 监听器引用(用于清理) // 监听器引用(用于清理)
let completeListener: ((event: any, data: any) => void) | null = null; let completeListener: ((event: any, data: any) => void) | null = null;
let errorListener: ((event: any, data: any) => void) | null = null; let errorListener: ((event: any, data: any) => void) | null = null;
return { return {
// 添加下载 // 添加下载
addDownload: (filename: string) => { addDownload: (filename: string) => {
activeDownloads.add(filename); activeDownloads.add(filename);
}, },
// 移除下载 // 移除下载
removeDownload: (filename: string) => { removeDownload: (filename: string) => {
activeDownloads.delete(filename); activeDownloads.delete(filename);
@@ -38,98 +38,100 @@ const createDownloadManager = () => {
notifiedDownloads.delete(filename); notifiedDownloads.delete(filename);
}, 5000); }, 5000);
}, },
// 标记文件已通知 // 标记文件已通知
markNotified: (filename: string) => { markNotified: (filename: string) => {
notifiedDownloads.add(filename); notifiedDownloads.add(filename);
}, },
// 检查文件是否已通知 // 检查文件是否已通知
isNotified: (filename: string) => { isNotified: (filename: string) => {
return notifiedDownloads.has(filename); return notifiedDownloads.has(filename);
}, },
// 清理所有下载 // 清理所有下载
clearDownloads: () => { clearDownloads: () => {
activeDownloads.clear(); activeDownloads.clear();
notifiedDownloads.clear(); notifiedDownloads.clear();
}, },
// 初始化事件监听器 // 初始化事件监听器
initEventListeners: (message: any, t: any) => { initEventListeners: (message: any, t: any) => {
if (isInitialized) return; if (isInitialized) return;
// 移除可能存在的旧监听器 // 移除可能存在的旧监听器
if (completeListener) { if (completeListener) {
ipcRenderer?.removeListener('music-download-complete', completeListener); ipcRenderer?.removeListener('music-download-complete', completeListener);
} }
if (errorListener) { if (errorListener) {
ipcRenderer?.removeListener('music-download-error', errorListener); ipcRenderer?.removeListener('music-download-error', errorListener);
} }
// 创建新的监听器 // 创建新的监听器
completeListener = (_event, data) => { completeListener = (_event, data) => {
if (!data.filename || !activeDownloads.has(data.filename)) return; if (!data.filename || !activeDownloads.has(data.filename)) return;
// 如果该文件已经通知过,则跳过 // 如果该文件已经通知过,则跳过
if (notifiedDownloads.has(data.filename)) return; if (notifiedDownloads.has(data.filename)) return;
// 标记为已通知 // 标记为已通知
notifiedDownloads.add(data.filename); notifiedDownloads.add(data.filename);
// 从活动下载移除 // 从活动下载移除
activeDownloads.delete(data.filename); activeDownloads.delete(data.filename);
}; };
errorListener = (_event, data) => { errorListener = (_event, data) => {
if (!data.filename || !activeDownloads.has(data.filename)) return; if (!data.filename || !activeDownloads.has(data.filename)) return;
// 如果该文件已经通知过,则跳过 // 如果该文件已经通知过,则跳过
if (notifiedDownloads.has(data.filename)) return; if (notifiedDownloads.has(data.filename)) return;
// 标记为已通知 // 标记为已通知
notifiedDownloads.add(data.filename); notifiedDownloads.add(data.filename);
// 显示失败通知 // 显示失败通知
message.error(t('songItem.message.downloadFailed', { message.error(
filename: data.filename, t('songItem.message.downloadFailed', {
error: data.error || '未知错误' filename: data.filename,
})); error: data.error || '未知错误'
})
);
// 从活动下载移除 // 从活动下载移除
activeDownloads.delete(data.filename); activeDownloads.delete(data.filename);
}; };
// 添加监听器 // 添加监听器
ipcRenderer?.on('music-download-complete', completeListener); ipcRenderer?.on('music-download-complete', completeListener);
ipcRenderer?.on('music-download-error', errorListener); ipcRenderer?.on('music-download-error', errorListener);
isInitialized = true; isInitialized = true;
}, },
// 清理事件监听器 // 清理事件监听器
cleanupEventListeners: () => { cleanupEventListeners: () => {
if (!isInitialized) return; if (!isInitialized) return;
if (completeListener) { if (completeListener) {
ipcRenderer?.removeListener('music-download-complete', completeListener); ipcRenderer?.removeListener('music-download-complete', completeListener);
completeListener = null; completeListener = null;
} }
if (errorListener) { if (errorListener) {
ipcRenderer?.removeListener('music-download-error', errorListener); ipcRenderer?.removeListener('music-download-error', errorListener);
errorListener = null; errorListener = null;
} }
isInitialized = false; isInitialized = false;
}, },
// 获取活跃下载数量 // 获取活跃下载数量
getActiveDownloadCount: () => { getActiveDownloadCount: () => {
return activeDownloads.size; return activeDownloads.size;
}, },
// 检查是否有特定文件正在下载 // 检查是否有特定文件正在下载
hasDownload: (filename: string) => { hasDownload: (filename: string) => {
return activeDownloads.has(filename); return activeDownloads.has(filename);
@@ -170,7 +172,7 @@ export const useDownload = () => {
// 构建文件名 // 构建文件名
const artistNames = (song.ar || song.song?.artists)?.map((a) => a.name).join(','); const artistNames = (song.ar || song.song?.artists)?.map((a) => a.name).join(',');
const filename = `${song.name} - ${artistNames}`; const filename = `${song.name} - ${artistNames}`;
// 检查是否已在下载 // 检查是否已在下载
if (downloadManager.hasDownload(filename)) { if (downloadManager.hasDownload(filename)) {
isDownloading.value = false; isDownloading.value = false;
@@ -182,7 +184,7 @@ export const useDownload = () => {
const songData = cloneDeep(song); const songData = cloneDeep(song);
songData.ar = songData.ar || songData.song?.artists; songData.ar = songData.ar || songData.song?.artists;
// 发送下载请求 // 发送下载请求
ipcRenderer?.send('download-music', { ipcRenderer?.send('download-music', {
url: typeof musicUrl === 'string' ? musicUrl : musicUrl.url, url: typeof musicUrl === 'string' ? musicUrl : musicUrl.url,
@@ -195,7 +197,7 @@ export const useDownload = () => {
}); });
message.success(t('songItem.message.downloadQueued')); message.success(t('songItem.message.downloadQueued'));
// 简化的监听逻辑,基本通知由全局监听器处理 // 简化的监听逻辑,基本通知由全局监听器处理
setTimeout(() => { setTimeout(() => {
isDownloading.value = false; isDownloading.value = false;
@@ -230,7 +232,7 @@ export const useDownload = () => {
let successCount = 0; let successCount = 0;
let failCount = 0; let failCount = 0;
const totalCount = songs.length; const totalCount = songs.length;
// 下载进度追踪 // 下载进度追踪
const trackProgress = () => { const trackProgress = () => {
if (successCount + failCount === totalCount) { if (successCount + failCount === totalCount) {
@@ -260,36 +262,36 @@ export const useDownload = () => {
trackProgress(); trackProgress();
return; return;
} }
const songData = cloneDeep(song); const songData = cloneDeep(song);
const filename = `${song.name} - ${(song.ar || song.song?.artists)?.map((a) => a.name).join(',')}`; const filename = `${song.name} - ${(song.ar || song.song?.artists)?.map((a) => a.name).join(',')}`;
// 检查是否已在下载 // 检查是否已在下载
if (downloadManager.hasDownload(filename)) { if (downloadManager.hasDownload(filename)) {
failCount++; failCount++;
trackProgress(); trackProgress();
return; return;
} }
// 添加到活动下载集合 // 添加到活动下载集合
downloadManager.addDownload(filename); downloadManager.addDownload(filename);
const songInfo = { const songInfo = {
...songData, ...songData,
ar: songData.ar || songData.song?.artists, ar: songData.ar || songData.song?.artists,
downloadTime: Date.now() downloadTime: Date.now()
}; };
ipcRenderer?.send('download-music', { ipcRenderer?.send('download-music', {
url, url,
filename, filename,
songInfo, songInfo,
type type
}); });
successCount++; successCount++;
}); });
// 所有下载开始后,检查进度 // 所有下载开始后,检查进度
trackProgress(); trackProgress();
} catch (error) { } catch (error) {
@@ -305,4 +307,4 @@ export const useDownload = () => {
downloadMusic, downloadMusic,
batchDownloadMusic batchDownloadMusic
}; };
}; };

View File

@@ -1,30 +1,29 @@
import { useDialog, useMessage } from 'naive-ui';
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { usePlayerStore } from '@/store'; import { usePlayerStore } from '@/store';
import type { SongResult } from '@/type/music'; import type { SongResult } from '@/type/music';
import { computed, ref } from 'vue';
import { getImgUrl } from '@/utils'; import { getImgUrl } from '@/utils';
import { getImageBackground } from '@/utils/linearColor'; 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: { import { useArtist } from './useArtist';
item: SongResult; import { useDownload } from './useDownload';
canRemove?: boolean;
}) { export function useSongItem(props: { item: SongResult; canRemove?: boolean }) {
const { t } = useI18n(); const { t } = useI18n();
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();
const message = useMessage(); const message = useMessage();
const dialog = useDialog(); const dialog = useDialog();
const { downloadMusic } = useDownload(); const { downloadMusic } = useDownload();
const { navigateToArtist } = useArtist(); const { navigateToArtist } = useArtist();
// 状态变量 // 状态变量
const showDropdown = ref(false); const showDropdown = ref(false);
const dropdownX = ref(0); const dropdownX = ref(0);
const dropdownY = ref(0); const dropdownY = ref(0);
const isHovering = ref(false); const isHovering = ref(false);
// 计算属性 // 计算属性
const play = computed(() => playerStore.isPlay); const play = computed(() => playerStore.isPlay);
const playMusic = computed(() => playerStore.playMusic); const playMusic = computed(() => playerStore.playMusic);
@@ -32,18 +31,20 @@ export function useSongItem(props: {
() => playMusic.value.id === props.item.id && playMusic.value.playLoading () => playMusic.value.id === props.item.id && playMusic.value.playLoading
); );
const isPlaying = computed(() => playMusic.value.id === props.item.id); const isPlaying = computed(() => playMusic.value.id === props.item.id);
// 收藏与不喜欢状态 // 收藏与不喜欢状态
const isFavorite = computed(() => { 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); return playerStore.favoriteList.includes(numericId);
}); });
const isDislike = computed(() => { 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); return playerStore.dislikeList.includes(numericId);
}); });
// 获取艺术家列表 // 获取艺术家列表
const artists = computed(() => { const artists = computed(() => {
return (props.item.ar || props.item.song?.artists)?.slice(0, 4) || []; return (props.item.ar || props.item.song?.artists)?.slice(0, 4) || [];
@@ -52,12 +53,12 @@ export function useSongItem(props: {
// 处理图片加载 // 处理图片加载
const handleImageLoad = async (imageElement: HTMLImageElement) => { const handleImageLoad = async (imageElement: HTMLImageElement) => {
if (!imageElement) return; if (!imageElement) return;
const { backgroundColor, primaryColor } = await getImageBackground(imageElement); const { backgroundColor, primaryColor } = await getImageBackground(imageElement);
props.item.backgroundColor = backgroundColor; props.item.backgroundColor = backgroundColor;
props.item.primaryColor = primaryColor; props.item.primaryColor = primaryColor;
}; };
// 播放音乐 // 播放音乐
const playMusicEvent = async (item: SongResult) => { const playMusicEvent = async (item: SongResult) => {
try { try {
@@ -71,11 +72,12 @@ export function useSongItem(props: {
return false; return false;
} }
}; };
// 切换收藏状态 // 切换收藏状态
const toggleFavorite = async (e: Event) => { const toggleFavorite = async (e: Event) => {
e && e.stopPropagation(); 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) { if (isFavorite.value) {
playerStore.removeFromFavorite(numericId); playerStore.removeFromFavorite(numericId);
@@ -83,7 +85,7 @@ export function useSongItem(props: {
playerStore.addToFavorite(numericId); playerStore.addToFavorite(numericId);
} }
}; };
// 切换不喜欢状态 // 切换不喜欢状态
const toggleDislike = async (e: Event) => { const toggleDislike = async (e: Event) => {
e && e.stopPropagation(); e && e.stopPropagation();
@@ -91,7 +93,7 @@ export function useSongItem(props: {
playerStore.removeFromDislikeList(props.item.id); playerStore.removeFromDislikeList(props.item.id);
return; return;
} }
dialog.warning({ dialog.warning({
title: t('songItem.dialog.dislike.title'), title: t('songItem.dialog.dislike.title'),
content: t('songItem.dialog.dislike.content'), content: t('songItem.dialog.dislike.content'),
@@ -102,20 +104,20 @@ export function useSongItem(props: {
} }
}); });
}; };
// 添加到下一首播放 // 添加到下一首播放
const handlePlayNext = () => { const handlePlayNext = () => {
playerStore.addToNextPlay(props.item); playerStore.addToNextPlay(props.item);
message.success(t('songItem.message.addedToNextPlay')); message.success(t('songItem.message.addedToNextPlay'));
}; };
// 获取歌曲时长 // 获取歌曲时长
const getDuration = (item: SongResult): number => { const getDuration = (item: SongResult): number => {
if (item.duration) return item.duration; if (item.duration) return item.duration;
if (typeof item.dt === 'number') return item.dt; if (typeof item.dt === 'number') return item.dt;
return 0; return 0;
}; };
// 格式化时长 // 格式化时长
const formatDuration = (ms: number): string => { const formatDuration = (ms: number): string => {
if (!ms) return '--:--'; if (!ms) return '--:--';
@@ -124,7 +126,7 @@ export function useSongItem(props: {
const seconds = totalSeconds % 60; const seconds = totalSeconds % 60;
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`; return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}; };
// 处理右键菜单 // 处理右键菜单
const handleContextMenu = (e: MouseEvent) => { const handleContextMenu = (e: MouseEvent) => {
e.preventDefault(); e.preventDefault();
@@ -132,7 +134,7 @@ export function useSongItem(props: {
dropdownX.value = e.clientX; dropdownX.value = e.clientX;
dropdownY.value = e.clientY; dropdownY.value = e.clientY;
}; };
// 处理菜单点击 // 处理菜单点击
const handleMenuClick = (e: MouseEvent) => { const handleMenuClick = (e: MouseEvent) => {
e.preventDefault(); e.preventDefault();
@@ -140,17 +142,17 @@ export function useSongItem(props: {
dropdownX.value = e.clientX; dropdownX.value = e.clientX;
dropdownY.value = e.clientY; dropdownY.value = e.clientY;
}; };
// 处理艺术家点击 // 处理艺术家点击
const handleArtistClick = (id: number) => { const handleArtistClick = (id: number) => {
navigateToArtist(id); navigateToArtist(id);
}; };
// 鼠标悬停处理 // 鼠标悬停处理
const handleMouseEnter = () => { const handleMouseEnter = () => {
isHovering.value = true; isHovering.value = true;
}; };
const handleMouseLeave = () => { const handleMouseLeave = () => {
isHovering.value = false; isHovering.value = false;
}; };
@@ -165,7 +167,7 @@ export function useSongItem(props: {
isDislike, isDislike,
artists, artists,
showDropdown, showDropdown,
dropdownX, dropdownX,
dropdownY, dropdownY,
isHovering, isHovering,
playerStore, playerStore,
@@ -185,4 +187,4 @@ export function useSongItem(props: {
handleMouseLeave, handleMouseLeave,
downloadMusic downloadMusic
}; };
} }

View File

@@ -9,10 +9,10 @@ export function useZoom() {
const MIN_ZOOM = 0.5; const MIN_ZOOM = 0.5;
const MAX_ZOOM = 1.5; const MAX_ZOOM = 1.5;
const ZOOM_STEP = 0.05; // 5%的步长 const ZOOM_STEP = 0.05; // 5%的步长
// 当前缩放因子 // 当前缩放因子
const zoomFactor = ref(1); const zoomFactor = ref(1);
// 初始化获取当前缩放比例 // 初始化获取当前缩放比例
const initZoomFactor = async () => { const initZoomFactor = async () => {
try { try {
@@ -22,35 +22,35 @@ export function useZoom() {
console.error('获取缩放比例失败:', error); console.error('获取缩放比例失败:', error);
} }
}; };
// 增加缩放比例保证100%为节点 // 增加缩放比例保证100%为节点
const increaseZoom = () => { const increaseZoom = () => {
let newZoom; let newZoom;
// 如果当前缩放低于100%并且增加后会超过100%则直接设为100% // 如果当前缩放低于100%并且增加后会超过100%则直接设为100%
if (zoomFactor.value < 1.0 && zoomFactor.value + ZOOM_STEP > 1.0) { if (zoomFactor.value < 1.0 && zoomFactor.value + ZOOM_STEP > 1.0) {
newZoom = 1.0; // 精确设置为100% newZoom = 1.0; // 精确设置为100%
} else { } else {
newZoom = Math.min(MAX_ZOOM, Math.round((zoomFactor.value + ZOOM_STEP) * 20) / 20); newZoom = Math.min(MAX_ZOOM, Math.round((zoomFactor.value + ZOOM_STEP) * 20) / 20);
} }
setZoomFactor(newZoom); setZoomFactor(newZoom);
}; };
// 减少缩放比例保证100%为节点 // 减少缩放比例保证100%为节点
const decreaseZoom = () => { const decreaseZoom = () => {
let newZoom; let newZoom;
// 如果当前缩放大于100%并且减少后会低于100%则直接设为100% // 如果当前缩放大于100%并且减少后会低于100%则直接设为100%
if (zoomFactor.value > 1.0 && zoomFactor.value - ZOOM_STEP < 1.0) { if (zoomFactor.value > 1.0 && zoomFactor.value - ZOOM_STEP < 1.0) {
newZoom = 1.0; // 精确设置为100% newZoom = 1.0; // 精确设置为100%
} else { } else {
newZoom = Math.max(MIN_ZOOM, Math.round((zoomFactor.value - ZOOM_STEP) * 20) / 20); newZoom = Math.max(MIN_ZOOM, Math.round((zoomFactor.value - ZOOM_STEP) * 20) / 20);
} }
setZoomFactor(newZoom); setZoomFactor(newZoom);
}; };
// 重置缩放比例到系统建议值 // 重置缩放比例到系统建议值
const resetZoom = async () => { const resetZoom = async () => {
try { try {
@@ -59,18 +59,18 @@ export function useZoom() {
console.error('重置缩放比例失败:', error); console.error('重置缩放比例失败:', error);
} }
}; };
// 设置为100%标准缩放 // 设置为100%标准缩放
const setZoom100 = () => { const setZoom100 = () => {
setZoomFactor(1.0); setZoomFactor(1.0);
}; };
// 设置缩放比例 // 设置缩放比例
const setZoomFactor = (zoom: number) => { const setZoomFactor = (zoom: number) => {
window.ipcRenderer.send('set-content-zoom', zoom); window.ipcRenderer.send('set-content-zoom', zoom);
zoomFactor.value = zoom; zoomFactor.value = zoom;
}; };
// 检查是否为100%缩放 // 检查是否为100%缩放
const isZoom100 = () => { const isZoom100 = () => {
return Math.abs(zoomFactor.value - 1.0) < 0.001; return Math.abs(zoomFactor.value - 1.0) < 0.001;
@@ -89,4 +89,4 @@ export function useZoom() {
MAX_ZOOM, MAX_ZOOM,
ZOOM_STEP ZOOM_STEP
}; };
} }

View File

@@ -9,7 +9,11 @@
<!-- 搜索栏 --> <!-- 搜索栏 -->
<search-bar /> <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 <router-view
v-slot="{ Component }" v-slot="{ Component }"
class="main-page" class="main-page"
@@ -41,7 +45,7 @@
<install-app-modal v-if="!isElectron"></install-app-modal> <install-app-modal v-if="!isElectron"></install-app-modal>
<update-modal v-if="isElectron" /> <update-modal v-if="isElectron" />
<playlist-drawer v-model="showPlaylistDrawer" :song-id="currentSongId" /> <playlist-drawer v-model="showPlaylistDrawer" :song-id="currentSongId" />
<SleepTimerTop v-if="!isMobile"/> <sleep-timer-top v-if="!isMobile" />
<!-- 下载管理抽屉 --> <!-- 下载管理抽屉 -->
<download-drawer <download-drawer
v-if=" v-if="
@@ -64,24 +68,24 @@ import DownloadDrawer from '@/components/common/DownloadDrawer.vue';
import InstallAppModal from '@/components/common/InstallAppModal.vue'; import InstallAppModal from '@/components/common/InstallAppModal.vue';
import PlayBottom from '@/components/common/PlayBottom.vue'; import PlayBottom from '@/components/common/PlayBottom.vue';
import UpdateModal from '@/components/common/UpdateModal.vue'; import UpdateModal from '@/components/common/UpdateModal.vue';
import SleepTimerTop from '@/components/player/SleepTimerTop.vue';
import homeRouter from '@/router/home'; import homeRouter from '@/router/home';
import otherRouter from '@/router/other'; import otherRouter from '@/router/other';
import { useMenuStore } from '@/store/modules/menu'; import { useMenuStore } from '@/store/modules/menu';
import { usePlayerStore } from '@/store/modules/player'; import { usePlayerStore } from '@/store/modules/player';
import { useSettingsStore } from '@/store/modules/settings'; import { useSettingsStore } from '@/store/modules/settings';
import { isElectron, isMobile } from '@/utils'; import { isElectron, isMobile } from '@/utils';
import SleepTimerTop from '@/components/player/SleepTimerTop.vue';
const keepAliveInclude = computed(() => { const keepAliveInclude = computed(() => {
const allRoutes = [...homeRouter, ...otherRouter]; const allRoutes = [...homeRouter, ...otherRouter];
return allRoutes return allRoutes
.filter((item) => { .filter((item) => {
return item.meta?.keepAlive; return item.meta?.keepAlive;
}) })
.map((item) => { .map((item) => {
return typeof item.name === 'string' return typeof item.name === 'string'
? item.name.charAt(0).toUpperCase() + item.name.slice(1) ? item.name.charAt(0).toUpperCase() + item.name.slice(1)
: ''; : '';
}) })
.filter(Boolean); .filter(Boolean);
@@ -92,7 +96,9 @@ const PlayBar = defineAsyncComponent(() => import('@/components/player/PlayBar.v
const MobilePlayBar = defineAsyncComponent(() => import('@/components/player/MobilePlayBar.vue')); const MobilePlayBar = defineAsyncComponent(() => import('@/components/player/MobilePlayBar.vue'));
const SearchBar = defineAsyncComponent(() => import('./components/SearchBar.vue')); const SearchBar = defineAsyncComponent(() => import('./components/SearchBar.vue'));
const TitleBar = defineAsyncComponent(() => import('./components/TitleBar.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 PlaylistDrawer = defineAsyncComponent(() => import('@/components/common/PlaylistDrawer.vue'));
const playerStore = usePlayerStore(); const playerStore = usePlayerStore();

View File

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

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