first commit
This commit is contained in:
commit
cb12290ecc
11
.env
Normal file
11
.env
Normal file
@ -0,0 +1,11 @@
|
||||
# 聚合数据API
|
||||
JUHE_NEWS_KEY=edbc3b96f022b59141961e2137f69b4a
|
||||
|
||||
# 彩云天气API
|
||||
CAIYUN_API_KEY=29-CwtZrOXU1b3Cx
|
||||
|
||||
# 和风天气API
|
||||
QWEATHER_API_KEY=ecd25018448140f1a8d23675c235e5b7
|
||||
|
||||
# vite api配置
|
||||
VITE_API_BASE=http://localhost:${API_PORT}
|
29
.gitignore
vendored
Normal file
29
.gitignore
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# 排除dist、dist-electron、node_modules目录
|
||||
/dist
|
||||
/dist-electron
|
||||
/node_modules
|
54
README.md
Normal file
54
README.md
Normal file
@ -0,0 +1,54 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default tseslint.config({
|
||||
extends: [
|
||||
// Remove ...tseslint.configs.recommended and replace with this
|
||||
...tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
...tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
...tseslint.configs.stylisticTypeChecked,
|
||||
],
|
||||
languageOptions: {
|
||||
// other options...
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default tseslint.config({
|
||||
plugins: {
|
||||
// Add the react-x and react-dom plugins
|
||||
'react-x': reactX,
|
||||
'react-dom': reactDom,
|
||||
},
|
||||
rules: {
|
||||
// other rules...
|
||||
// Enable its recommended typescript rules
|
||||
...reactX.configs['recommended-typescript'].rules,
|
||||
...reactDom.configs.recommended.rules,
|
||||
},
|
||||
})
|
||||
```
|
20
electron-builder.js
Normal file
20
electron-builder.js
Normal file
@ -0,0 +1,20 @@
|
||||
const { build } = require('vite')
|
||||
|
||||
async function main() {
|
||||
await build({
|
||||
configFile: 'vite.config.ts',
|
||||
build: {
|
||||
outDir: 'dist'
|
||||
}
|
||||
})
|
||||
|
||||
require('esbuild').buildSync({
|
||||
entryPoints: ['electron/main.ts'],
|
||||
bundle: true,
|
||||
platform: 'node',
|
||||
outfile: 'dist-electron/main.js',
|
||||
external: ['electron']
|
||||
})
|
||||
}
|
||||
|
||||
main()
|
14
electron.tsconfig.json
Normal file
14
electron.tsconfig.json
Normal file
@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"module": "CommonJS",
|
||||
"rootDir": "electron",
|
||||
"outDir": "dist-electron",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["node"],
|
||||
"noEmit": false
|
||||
},
|
||||
"include": ["electron/**/*.ts"]
|
||||
}
|
294
electron/main.ts
Normal file
294
electron/main.ts
Normal file
@ -0,0 +1,294 @@
|
||||
// electron/main.ts
|
||||
import { app, BrowserWindow, Menu, globalShortcut, net, ipcMain } from 'electron';
|
||||
import path from 'path';
|
||||
import http from 'http';
|
||||
import { URL } from 'url';
|
||||
//import { apiRoutes } from './api'; // 导入API路由配置
|
||||
import dotenv from 'dotenv';
|
||||
dotenv.config({ path: path.join(__dirname, '../.env') }); // 根据实际路径调整
|
||||
|
||||
// 确保在news.ts中能读取到
|
||||
console.log('JUHE_KEY:', process.env.JUHE_NEWS_KEY?.substring(0, 3) + '***'); // 打印前3位验证
|
||||
console.log('CAIYUN_KEY:', process.env.CAIYUN_API_KEY?.substring(0, 3) + '***'); // 打印前3位验证
|
||||
|
||||
dotenv.config({ path: path.join(__dirname, '../.env') });
|
||||
|
||||
// 环境配置
|
||||
const isDev = process.env.NODE_ENV === 'development';
|
||||
|
||||
// 注册 IPC 处理器
|
||||
function registerIpcHandlers() {
|
||||
// 天气接口(需要修改)
|
||||
ipcMain.handle('get-weather', async (_, { lon, lat }) => {
|
||||
console.log('[IPC] 开始获取天气数据', { lon, lat });
|
||||
|
||||
// 检查缓存有效性
|
||||
const now = Date.now();
|
||||
if (now - apiCache.weather.timestamp < apiCache.weather.ttl) {
|
||||
console.log('[Cache] 返回缓存的天气数据');
|
||||
return apiCache.weather.data;
|
||||
}
|
||||
|
||||
try {
|
||||
const apiKey = process.env.CAIYUN_API_KEY!;
|
||||
const apiUrl = `https://api.caiyunapp.com/v2.6/${apiKey}/${lon},${lat}/weather`;
|
||||
|
||||
const response = await net.fetch(apiUrl);
|
||||
const jsonData = await response.json();
|
||||
|
||||
if (jsonData.status !== 'ok') {
|
||||
throw new Error(jsonData.message || '天气数据获取失败');
|
||||
}
|
||||
|
||||
// 详细数据格式化
|
||||
const formattedData = {
|
||||
realtime: formatRealtime(jsonData.result.realtime),
|
||||
forecast: formatDailyForecast(jsonData.result.daily)
|
||||
};
|
||||
|
||||
console.log('[IPC] 格式化天气数据:', formattedData);
|
||||
// 更新缓存
|
||||
apiCache.weather.data = formattedData;
|
||||
apiCache.weather.timestamp = now;
|
||||
|
||||
return formattedData;
|
||||
} catch (error: any) {
|
||||
console.error('[IPC] 天气请求失败:', error);
|
||||
return {
|
||||
error: true,
|
||||
message: error.message
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
// 实时天气格式化
|
||||
const formatRealtime = (data: any) => ({
|
||||
temperature: data.temperature.toFixed(1),
|
||||
humidity: (data.humidity * 100).toFixed(1) + '%',
|
||||
wind: {
|
||||
speed: (data.wind.speed * 3.6).toFixed(1) + 'km/h',
|
||||
direction: getWindDirection(data.wind.direction)
|
||||
},
|
||||
airQuality: {
|
||||
aqi: data.air_quality.aqi.chn,
|
||||
description: data.air_quality.description.chn
|
||||
},
|
||||
skycon: data.skycon,
|
||||
apparentTemperature: data.apparent_temperature.toFixed(1)
|
||||
});
|
||||
|
||||
// 天气预报格式化
|
||||
const formatDailyForecast = (data: any) => ({
|
||||
temperature: data.temperature.map((item: any) => ({
|
||||
date: item.date,
|
||||
max: item.max,
|
||||
min: item.min
|
||||
})),
|
||||
skycon: data.skycon,
|
||||
precipitation: data.precipitation
|
||||
});
|
||||
|
||||
// 风向转换
|
||||
const getWindDirection = (degrees: number) => {
|
||||
const directions = ['北风', '东北风', '东风', '东南风', '南风', '西南风', '西风', '西北风'];
|
||||
return directions[Math.round(degrees % 360 / 45) % 8];
|
||||
};
|
||||
|
||||
// 新闻接口
|
||||
ipcMain.handle('get-news', async () => {
|
||||
console.log('[IPC] 开始获取新闻数据');
|
||||
const now = Date.now();
|
||||
|
||||
if (now - apiCache.news.timestamp < apiCache.news.ttl) {
|
||||
console.log('[Cache] 返回缓存的新闻数据');
|
||||
return apiCache.news.data;
|
||||
}
|
||||
|
||||
try {
|
||||
const apiKey = process.env.JUHE_NEWS_KEY!;
|
||||
const response = await net.fetch(
|
||||
`https://v.juhe.cn/toutiao/index?type=top&key=${apiKey}`
|
||||
);
|
||||
const json = await response.json();
|
||||
console.log('[IPC] 新闻响应:', json); // 添加原始响应日志
|
||||
const formatted = formatNews(json.result?.data || []);
|
||||
// 更新缓存
|
||||
apiCache.news.data = formatted;
|
||||
apiCache.news.timestamp = now;
|
||||
return formatted;
|
||||
//return formatNews(json.result?.data || []);
|
||||
} catch (error) {
|
||||
console.error('[IPC] 新闻请求失败:', error);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const formatNews = (items: any[]) => items.map(item => ({
|
||||
uniquekey: item.uniquekey,
|
||||
title: item.title,
|
||||
date: item.date,
|
||||
category: item.category || "头条新闻",
|
||||
author_name: item.author_name || "未知作者",
|
||||
url: item.url,
|
||||
thumbnail_pic_s: item.thumbnail_pic_s,
|
||||
is_content: item.is_content
|
||||
}));
|
||||
|
||||
|
||||
// 添加缓存对象
|
||||
const apiCache = {
|
||||
weather: {
|
||||
data: null as any,
|
||||
timestamp: 0,
|
||||
//ttl: 1800000 // 30分钟缓存
|
||||
//6小时缓存
|
||||
ttl: 21600000
|
||||
},
|
||||
news: {
|
||||
data: null as any,
|
||||
timestamp: 0,
|
||||
//ttl: 3600000 // 1小时缓存
|
||||
//2小时缓存
|
||||
ttl: 7200000
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// 禁用默认菜单(提升安全性和专业性)
|
||||
Menu.setApplicationMenu(null);
|
||||
|
||||
/**
|
||||
* 创建主窗口
|
||||
*/
|
||||
async function createWindow() {
|
||||
const mainWindow = new BrowserWindow({
|
||||
width: 1200,
|
||||
height: 800,
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, 'preload.js'),
|
||||
contextIsolation: true, // 启用上下文隔离(安全必需)
|
||||
nodeIntegration: false, // 禁用Node集成(安全要求)
|
||||
webSecurity: !isDev, // 生产环境启用安全策略
|
||||
sandbox: true // 启用沙箱模式
|
||||
},
|
||||
show: false // 先隐藏窗口直到内容加载完成
|
||||
});
|
||||
|
||||
// 优化加载体验
|
||||
mainWindow.once('ready-to-show', () => {
|
||||
mainWindow.show();
|
||||
if (isDev) {
|
||||
//mainWindow.webContents.openDevTools({ mode: 'detach' }); // 打开开发者工具
|
||||
console.log('Developer tools opened in detached mode');
|
||||
}
|
||||
});
|
||||
|
||||
// 新增权限处理代码(必须在loadURL之前)
|
||||
const ses = mainWindow.webContents.session;
|
||||
|
||||
// 自动处理权限请求
|
||||
ses.setPermissionRequestHandler((webContents, permission, callback) => {
|
||||
const allowedPermissions = new Set(['media', 'microphone', 'audioCapture']);
|
||||
callback(allowedPermissions.has(permission));
|
||||
});
|
||||
|
||||
// 自动授予设备权限
|
||||
// 替换原来的setDevicePermissionHandler
|
||||
ses.setPermissionRequestHandler((webContents, permission, callback) => {
|
||||
// 统一允许所有媒体相关权限
|
||||
if (['microphone', 'audioCapture', 'media'].includes(permission)) {
|
||||
return callback(true);
|
||||
}
|
||||
callback(false);
|
||||
});
|
||||
|
||||
// 加载内容
|
||||
const loadURL = isDev
|
||||
? 'http://localhost:5173'
|
||||
: `file://${path.join(__dirname, '../dist/index.html')}`;
|
||||
|
||||
console.log(`Loading URL: ${loadURL}`);
|
||||
await mainWindow.loadURL(loadURL);
|
||||
|
||||
registerGlobalShortcuts(mainWindow);
|
||||
return mainWindow;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一响应格式(带安全头)
|
||||
*/
|
||||
function sendResponse(
|
||||
res: http.ServerResponse,
|
||||
status: number,
|
||||
data: unknown,
|
||||
headers: Record<string, string> = {}
|
||||
) {
|
||||
const securityHeaders = {
|
||||
'Content-Security-Policy': "default-src 'self'",
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'X-Frame-Options': 'DENY'
|
||||
};
|
||||
|
||||
const responseHeaders = {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
...securityHeaders,
|
||||
...headers
|
||||
};
|
||||
|
||||
res.writeHead(status, responseHeaders);
|
||||
res.end(JSON.stringify(data));
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册全局快捷键
|
||||
*/
|
||||
function registerGlobalShortcuts(win: BrowserWindow) {
|
||||
const shortcut = process.platform === 'darwin' ? 'Command+Q' : 'Ctrl+Q';
|
||||
|
||||
const ret = globalShortcut.register(shortcut, () => {
|
||||
console.log('Gracefully shutting down...');
|
||||
win.destroy();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
if (!ret) {
|
||||
console.error('Failed to register shortcut');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用启动流程
|
||||
*/
|
||||
app.whenReady()
|
||||
.then(() => {
|
||||
// 注册 IPC 处理器的代码
|
||||
registerIpcHandlers();
|
||||
console.log('Creating browser window...');
|
||||
return createWindow();
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('App initialization failed:', error);
|
||||
app.quit();
|
||||
});
|
||||
|
||||
/**
|
||||
* 生命周期管理
|
||||
*/
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
app.on('will-quit', () => {
|
||||
globalShortcut.unregisterAll();
|
||||
});
|
8
electron/preload.ts
Normal file
8
electron/preload.ts
Normal file
@ -0,0 +1,8 @@
|
||||
//electron\preload.ts
|
||||
import { contextBridge, ipcRenderer } from 'electron';
|
||||
|
||||
contextBridge.exposeInMainWorld('electronAPI', {
|
||||
getWeather: (params: { lon: number; lat: number }) =>
|
||||
ipcRenderer.invoke('get-weather', params),
|
||||
getNews: () => ipcRenderer.invoke('get-news')
|
||||
});
|
28
eslint.config.js
Normal file
28
eslint.config.js
Normal file
@ -0,0 +1,28 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import tseslint from 'typescript-eslint'
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist'] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
plugins: {
|
||||
'react-hooks': reactHooks,
|
||||
'react-refresh': reactRefresh,
|
||||
},
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
13
index.html
Normal file
13
index.html
Normal file
@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vite + React + TS</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
52
package.json
Normal file
52
package.json
Normal file
@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "my-vite-app",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"build:rpi": "vite build --emptyOutDir && tsc -p electron.tsconfig.json",
|
||||
"electron:start-pi": "cross-env NODE_ENV=production electron --arch=arm64 dist-electron/main.js",
|
||||
"dev": "concurrently -k \"vite\" \"npm run dev:electron\"",
|
||||
"dev:electron": "concurrently -k \"npm run watch:electron\" \"npm run start:electron\"",
|
||||
"watch:electron": "cross-env NODE_ENV=development tsc -p electron.tsconfig.json --watch --preserveWatchOutput",
|
||||
"start:electron": "cross-env NODE_ENV=development electron dist-electron/main.js",
|
||||
"vite": "vite",
|
||||
"build": "vite build && tsc -p electron.tsconfig.json",
|
||||
"electron:start": "cross-env NODE_ENV=production electron dist-electron/main.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.14.0",
|
||||
"@emotion/styled": "^11.14.0",
|
||||
"@mui/icons-material": "^6.4.5",
|
||||
"@mui/material": "^6.4.5",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-icons": "^5.5.0",
|
||||
"swr": "^2.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.21.0",
|
||||
"@types/node": "^22.13.8",
|
||||
"@types/react": "^19.0.10",
|
||||
"@types/react-dom": "^19.0.4",
|
||||
"@vitejs/plugin-react": "^4.3.4",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"concurrently": "^9.1.2",
|
||||
"cross-env": "^7.0.3",
|
||||
"dotenv": "^16.4.7",
|
||||
"electron": "33.2.0",
|
||||
"electron-devtools-installer": "^4.0.0",
|
||||
"eslint": "^9.21.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.19",
|
||||
"globals": "^15.15.0",
|
||||
"nan": "^2.22.2",
|
||||
"node-gyp": "^11.1.0",
|
||||
"nodemon": "^3.1.9",
|
||||
"postcss": "^8.5.3",
|
||||
"tailwindcss": "3.4.17",
|
||||
"typescript": "~5.7.2",
|
||||
"typescript-eslint": "^8.24.1",
|
||||
"vite": "^6.2.0"
|
||||
}
|
||||
}
|
4335
pnpm-lock.yaml
Normal file
4335
pnpm-lock.yaml
Normal file
File diff suppressed because it is too large
Load Diff
6
postcss.config.js
Normal file
6
postcss.config.js
Normal file
@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
BIN
public/Snowboy-wakeup.pmdl
Normal file
BIN
public/Snowboy-wakeup.pmdl
Normal file
Binary file not shown.
BIN
public/test-audio.mp3
Normal file
BIN
public/test-audio.mp3
Normal file
Binary file not shown.
1
public/vite.svg
Normal file
1
public/vite.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
After Width: | Height: | Size: 1.5 KiB |
42
src/App.css
Normal file
42
src/App.css
Normal file
@ -0,0 +1,42 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
99
src/App.tsx
Normal file
99
src/App.tsx
Normal file
@ -0,0 +1,99 @@
|
||||
//src\App.tsx
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import AnalogClock from "./components/AnalogClock";
|
||||
import CalendarGrid from "./components/CalendarGrid";
|
||||
import WeatherSection from "./components/WeatherSection";
|
||||
import NewsSection from "./components/NewsSection";
|
||||
import { generateCalendarDays } from "./utils/calendar";
|
||||
import { NewsItem } from "./types/magic-mirror";
|
||||
import VoiceAssistant from "./components/VoiceAssistant";
|
||||
import useSWR from "swr";
|
||||
|
||||
const MagicMirror = () => {
|
||||
const [time, setTime] = useState(new Date());
|
||||
const calendarDays = useMemo(() => generateCalendarDays(), []);
|
||||
|
||||
// 新闻数据
|
||||
const { data } = useSWR<NewsItem[]>(
|
||||
"news",
|
||||
async () => {
|
||||
try {
|
||||
return await window.electronAPI.getNews();
|
||||
} catch (error) {
|
||||
console.error("新闻加载失败:", error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
{
|
||||
refreshInterval: 600000,
|
||||
onErrorRetry: (error) => {
|
||||
if (error.message.includes("500")) return; // 服务器错误不重试
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// 天气数据
|
||||
|
||||
// 更新时间
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setTime(new Date()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
// 生成问候语
|
||||
const greeting = useMemo(() => {
|
||||
const hours = time.getHours();
|
||||
if (hours < 5) return "夜深了";
|
||||
if (hours < 12) return "早上好";
|
||||
if (hours < 18) return "下午好";
|
||||
return "晚上好";
|
||||
}, [time]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-black text-gray-100 font-sans antialiased overflow-hidden">
|
||||
{/* 时间模块 */}
|
||||
<div className="absolute top-8 left-8 flex items-start gap-8">
|
||||
<div className="space-y-1">
|
||||
<div className="text-2xl font-light">
|
||||
{time.toLocaleDateString("zh-CN", { weekday: "long" })}
|
||||
</div>
|
||||
<div className="text-gray-400 text-sm">
|
||||
{time.toLocaleDateString("zh-CN", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
})}
|
||||
</div>
|
||||
<div className="flex items-end gap-2">
|
||||
<div className="text-5xl font-light">
|
||||
{time.toLocaleTimeString("zh-CN", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
})}
|
||||
</div>
|
||||
<div className="text-gray-400 mb-5">
|
||||
{time.getSeconds().toString().padStart(2, "0")}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<AnalogClock time={time} />
|
||||
</div>
|
||||
|
||||
{/* 日历模块 */}
|
||||
<div className="absolute top-48 left-8 w-64">
|
||||
<div className="mb-4 text-gray-300 text-sm">
|
||||
{time.toLocaleDateString("zh-CN", { month: "long", year: "numeric" })}
|
||||
</div>
|
||||
<CalendarGrid days={calendarDays} />
|
||||
</div>
|
||||
|
||||
{/* 其他模块 */}
|
||||
<WeatherSection />
|
||||
<NewsSection items={data || []} />
|
||||
<VoiceAssistant greeting={greeting} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MagicMirror;
|
1
src/assets/react.svg
Normal file
1
src/assets/react.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
After Width: | Height: | Size: 4.0 KiB |
47
src/components/AnalogClock.tsx
Normal file
47
src/components/AnalogClock.tsx
Normal file
@ -0,0 +1,47 @@
|
||||
import { FC } from "react"
|
||||
|
||||
interface AnalogClockProps {
|
||||
time: Date
|
||||
}
|
||||
|
||||
const AnalogClock: FC<AnalogClockProps> = ({ time }) => {
|
||||
const hours = time.getHours() % 12
|
||||
const minutes = time.getMinutes()
|
||||
const seconds = time.getSeconds()
|
||||
|
||||
return (
|
||||
<div className="w-32 h-32 relative">
|
||||
{/* 刻度 */}
|
||||
{Array.from({ length: 60 }).map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={`absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 origin-center ${
|
||||
i % 5 === 0 ? "h-2 w-px bg-gray-300" : "h-1 w-px bg-gray-500"
|
||||
}`}
|
||||
style={{
|
||||
transform: `rotate(${i * 6}deg) translateY(-55px)`,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* 指针 */}
|
||||
<div
|
||||
className="absolute left-1/2 bottom-1/2 bg-gray-300 w-0.5 h-8 -ml-px origin-bottom"
|
||||
style={{ transform: `rotate(${hours * 30 + minutes * 0.5}deg)` }}
|
||||
/>
|
||||
<div
|
||||
className="absolute left-1/2 bottom-1/2 bg-gray-300 w-0.5 h-10 -ml-px origin-bottom"
|
||||
style={{ transform: `rotate(${minutes * 6}deg)` }}
|
||||
/>
|
||||
<div
|
||||
className="absolute left-1/2 bottom-1/2 bg-gray-400 w-px h-12 -ml-px origin-bottom"
|
||||
style={{ transform: `rotate(${seconds * 6}deg)` }}
|
||||
/>
|
||||
|
||||
{/* 中心点 */}
|
||||
<div className="absolute left-1/2 top-1/2 w-1.5 h-1.5 bg-gray-300 rounded-full -translate-x-1/2 -translate-y-1/2" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default AnalogClock
|
23
src/components/CalendarGrid.tsx
Normal file
23
src/components/CalendarGrid.tsx
Normal file
@ -0,0 +1,23 @@
|
||||
import { FC } from "react"
|
||||
import { CalendarDay } from "../types/magic-mirror"
|
||||
|
||||
interface CalendarGridProps {
|
||||
days: CalendarDay[]
|
||||
}
|
||||
|
||||
const CalendarGrid: FC<CalendarGridProps> = ({ days }) => (
|
||||
<div className="grid grid-cols-7 gap-1 text-sm">
|
||||
{days.map((day, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={`text-center p-1 rounded ${
|
||||
day.isCurrent ? "bg-white/20" : ""
|
||||
} ${day.isEmpty ? "opacity-20" : "text-gray-300"}`}
|
||||
>
|
||||
{!day.isEmpty && day.day}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
|
||||
export default CalendarGrid
|
90
src/components/NewsSection.tsx
Normal file
90
src/components/NewsSection.tsx
Normal file
@ -0,0 +1,90 @@
|
||||
//src\components\NewsSection.tsx
|
||||
import { FC, useState, useEffect } from "react"
|
||||
import { NewsItem } from "../types/magic-mirror"
|
||||
|
||||
const SCROLL_INTERVAL = 8000 //表示每8秒滚动一次
|
||||
|
||||
const NewsSection: FC<{ items: NewsItem[] }> = ({ items }) => {
|
||||
const [activeIndex, setActiveIndex] = useState(0)
|
||||
const [isHovered, setIsHovered] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (items.length <= 1) return
|
||||
|
||||
const timer = setInterval(() => {
|
||||
if (!isHovered) setActiveIndex(prev => (prev + 1) % items.length)
|
||||
}, SCROLL_INTERVAL)
|
||||
|
||||
return () => clearInterval(timer)
|
||||
}, [items.length, isHovered])
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="fixed bottom-8 left-1/2 -translate-x-1/2 w-[800px] h-20 flex items-center justify-center">
|
||||
<div className="text-gray-400 text-sm">正在加载最新新闻...</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="fixed bottom-8 left-1/2 -translate-x-1/2 w-[800px] h-20 overflow-hidden"
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
>
|
||||
<div className="relative h-full">
|
||||
{items.map((item, index) => (
|
||||
<div
|
||||
key={item.uniquekey}
|
||||
className="absolute inset-0 transition-all duration-500 ease-[cubic-bezier(0.4,0,0.2,1)]"
|
||||
style={{
|
||||
transform: `translateY(${(index - activeIndex) * 100}%)`,
|
||||
opacity: index === activeIndex ? 1 : 0,
|
||||
pointerEvents: index === activeIndex ? 'auto' : 'none'
|
||||
}}
|
||||
>
|
||||
<a
|
||||
href={item.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="h-full px-6 flex flex-col justify-center items-center text-center hover:bg-white/5 transition-colors group space-y-1.5"
|
||||
>
|
||||
<div className="flex items-center text-gray-400/80 text-sm space-x-2">
|
||||
<span>{formatNewsDate(item.date)}</span>
|
||||
<span className="text-gray-500">·</span>
|
||||
<span>{formatNewsTime(item.date)}</span>
|
||||
<span className="text-gray-500">·</span>
|
||||
<span>{item.category}</span>
|
||||
{item.author_name && (
|
||||
<>
|
||||
<span className="text-gray-500">·</span>
|
||||
<span>{item.author_name}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-gray-300 text-xl font-medium tracking-wide group-hover:text-white transition-colors max-w-[90%]">
|
||||
{item.title}
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const formatNewsDate = (datetime?: string) => {
|
||||
if (!datetime) return "";
|
||||
const [datePart] = datetime.split(" ");
|
||||
const [_year, month, day] = datePart.split("-"); // 正确拆分年月日
|
||||
return `${parseInt(month)}月${parseInt(day)}日`;
|
||||
}
|
||||
|
||||
const formatNewsTime = (datetime?: string) => {
|
||||
if (!datetime) return ""
|
||||
const timePart = datetime.split(" ")[1] || ""
|
||||
const [hours, minutes] = timePart.split(":")
|
||||
return `${hours}时${minutes}分`
|
||||
}
|
||||
|
||||
export default NewsSection
|
407
src/components/VoiceAssistant copy 2.tsx
Normal file
407
src/components/VoiceAssistant copy 2.tsx
Normal file
@ -0,0 +1,407 @@
|
||||
import { useState, useRef, useCallback } from "react";
|
||||
|
||||
// 新增音频源类型,playback表示音频播放,mic表示麦克风
|
||||
type AudioSourceType = "mic" | "playback";
|
||||
|
||||
interface ProcessState {
|
||||
recording: boolean;
|
||||
transcribing: boolean;
|
||||
generating: boolean;
|
||||
synthesizing: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
interface VoiceAssistantProps {
|
||||
greeting: string;
|
||||
}
|
||||
|
||||
const ANALYSER_FFT_SIZE = 128;
|
||||
const VOLUME_SENSITIVITY = 1.5;
|
||||
const SMOOTHING_FACTOR = 0.7;
|
||||
const BAR_COUNT = 12;
|
||||
|
||||
const VoiceAssistant = ({ greeting }: VoiceAssistantProps) => {
|
||||
const [isListening, setIsListening] = useState(false);
|
||||
const [processState, setProcessState] = useState<ProcessState>({
|
||||
recording: false,
|
||||
transcribing: false,
|
||||
generating: false,
|
||||
synthesizing: false,
|
||||
});
|
||||
const [asrText, setAsrText] = useState("");
|
||||
const [answerText, setAnswerText] = useState("");
|
||||
const mediaRecorder = useRef<MediaRecorder | null>(null);
|
||||
const audioChunks = useRef<Blob[]>([]);
|
||||
const audioElement = useRef<HTMLAudioElement>(null);
|
||||
|
||||
const barsRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const mediaStreamRef = useRef<MediaStream | null>(null);
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const analyserRef = useRef<AnalyserNode | null>(null);
|
||||
const animationFrameRef = useRef<number | null>(null);
|
||||
|
||||
const dataArrayRef = useRef<Uint8Array | null>(null);
|
||||
const lastValuesRef = useRef<number[]>(new Array(BAR_COUNT).fill(10));
|
||||
const [audioSourceType, setAudioSourceType] =
|
||||
useState<AudioSourceType>("mic");
|
||||
|
||||
const updateState = (newState: Partial<ProcessState>) => {
|
||||
setProcessState((prev) => ({ ...prev, ...newState }));
|
||||
};
|
||||
|
||||
const cleanupAudio = useCallback(async () => {
|
||||
mediaStreamRef.current?.getTracks().forEach((track) => track.stop());
|
||||
if (audioContextRef.current?.state !== "closed") {
|
||||
await audioContextRef.current?.close();
|
||||
}
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
animationFrameRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
const initializeAudioContext = useCallback(() => {
|
||||
const AudioContextClass =
|
||||
window.AudioContext || (window as any).webkitAudioContext;
|
||||
audioContextRef.current = new AudioContextClass();
|
||||
analyserRef.current = audioContextRef.current.createAnalyser();
|
||||
analyserRef.current.fftSize = ANALYSER_FFT_SIZE;
|
||||
analyserRef.current.smoothingTimeConstant = SMOOTHING_FACTOR;
|
||||
dataArrayRef.current = new Uint8Array(
|
||||
analyserRef.current.frequencyBinCount
|
||||
);
|
||||
}, []);
|
||||
|
||||
const startRecording = async () => {
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: { sampleRate: 16000, channelCount: 1, sampleSize: 16 },
|
||||
});
|
||||
|
||||
mediaRecorder.current = new MediaRecorder(stream);
|
||||
audioChunks.current = [];
|
||||
|
||||
mediaRecorder.current.ondataavailable = (e) => {
|
||||
audioChunks.current.push(e.data);
|
||||
};
|
||||
|
||||
mediaRecorder.current.start(500);
|
||||
updateState({ recording: true, error: undefined });
|
||||
} catch (err) {
|
||||
updateState({ error: "麦克风访问失败,请检查权限设置" });
|
||||
}
|
||||
};
|
||||
|
||||
// 新增切换音频源的函数
|
||||
const stopRecording = async () => {
|
||||
// 如果当前没有录音器,则返回
|
||||
if (!mediaRecorder.current) return;
|
||||
// 停止录音器
|
||||
mediaRecorder.current.stop();
|
||||
// 更新状态为未录音
|
||||
updateState({ recording: false });
|
||||
// 等待录音器停止录音
|
||||
mediaRecorder.current.onstop = async () => {
|
||||
try {
|
||||
// 停止录音器
|
||||
const audioBlob = new Blob(audioChunks.current, { type: "audio/wav" });
|
||||
await processAudio(audioBlob);
|
||||
} finally {
|
||||
audioChunks.current = [];
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
const processAudio = async (audioBlob: Blob) => {
|
||||
const formData = new FormData();
|
||||
formData.append("audio", audioBlob, "recording.wav");
|
||||
|
||||
try {
|
||||
updateState({ transcribing: true });
|
||||
// 发送请求到后端
|
||||
const asrResponse = await fetch("http://localhost:5000/asr", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
// 如果请求失败,则抛出错误
|
||||
if (!asrResponse.ok) throw new Error("语音识别失败");
|
||||
// 获取后端返回的文本
|
||||
const asrData = await asrResponse.json();
|
||||
setAsrText(asrData.asr_text);
|
||||
updateState({ transcribing: false, generating: true });
|
||||
|
||||
// 发送请求到后端,生成回答
|
||||
const generateResponse = await fetch("http://localhost:5000/generate", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ asr_text: asrData.asr_text }),
|
||||
});
|
||||
|
||||
if (!generateResponse.ok) throw new Error("生成回答失败");
|
||||
|
||||
const generateData = await generateResponse.json();
|
||||
setAnswerText(generateData.answer_text);
|
||||
updateState({ generating: false, synthesizing: true });
|
||||
|
||||
// 播放合成的音频,增加可视化效果
|
||||
if (audioElement.current) {
|
||||
startVisualization();
|
||||
// 播放合成的音频
|
||||
audioElement.current.src = `http://localhost:5000${generateData.audio_url}`;
|
||||
// 播放音频
|
||||
audioElement.current.play()
|
||||
.catch((err) => {
|
||||
console.error("播放失败:", err);
|
||||
updateState({ error: "音频播放失败" });
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
updateState({ error: err instanceof Error ? err.message : "未知错误" });
|
||||
} finally {
|
||||
updateState({
|
||||
transcribing: false,
|
||||
generating: false,
|
||||
synthesizing: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusText = () => {
|
||||
if (processState.error) return processState.error;
|
||||
if (processState.recording) return "录音中... 🎤";
|
||||
if (processState.transcribing) return "语音识别中... 🔍";
|
||||
if (processState.generating) return "生成回答中... 💡";
|
||||
if (processState.synthesizing) return "语音合成中... 🎵";
|
||||
return "点击开始对话";
|
||||
};
|
||||
|
||||
const startVisualization = useCallback(() => {
|
||||
if (!analyserRef.current || !dataArrayRef.current || !barsRef.current) {
|
||||
console.warn("可视化组件未就绪");
|
||||
return;
|
||||
}
|
||||
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
animationFrameRef.current = null;
|
||||
}
|
||||
|
||||
const bufferLength = analyserRef.current.frequencyBinCount;
|
||||
const updateBars = () => {
|
||||
try {
|
||||
analyserRef.current!.getByteFrequencyData(dataArrayRef.current!);
|
||||
|
||||
const bars = barsRef.current!.children;
|
||||
for (let i = 0; i < bars.length; i++) {
|
||||
const bar = bars[i] as HTMLElement;
|
||||
const dataIndex = Math.floor((i / BAR_COUNT) * (bufferLength / 2));
|
||||
const rawValue =
|
||||
(dataArrayRef.current![dataIndex] / 255) * 100 * VOLUME_SENSITIVITY;
|
||||
|
||||
const smoothValue = Math.min(
|
||||
100,
|
||||
Math.max(10, rawValue * 0.6 + lastValuesRef.current[i] * 0.4)
|
||||
);
|
||||
lastValuesRef.current[i] = smoothValue;
|
||||
|
||||
bar.style.cssText = `
|
||||
height: ${smoothValue}%;
|
||||
transform: scaleY(${0.8 + (smoothValue / 100) * 0.6});
|
||||
transition: ${i === 0 ? "none" : "height 50ms linear"};
|
||||
`;
|
||||
}
|
||||
|
||||
animationFrameRef.current = requestAnimationFrame(updateBars);
|
||||
} catch (err) {
|
||||
console.error("可视化更新失败:", err);
|
||||
}
|
||||
};
|
||||
|
||||
animationFrameRef.current = requestAnimationFrame(updateBars);
|
||||
}, [analyserRef, dataArrayRef, barsRef]);
|
||||
|
||||
// 切换监听状态
|
||||
const toggleListening = useCallback(async () => {
|
||||
if (isListening) { // 如果正在监听
|
||||
await cleanupAudio(); // 清理现有音频
|
||||
} else { // 否则
|
||||
try { // 尝试
|
||||
await cleanupAudio(); // 清理现有音频
|
||||
initializeAudioContext(); // 初始化音频上下文
|
||||
|
||||
if (audioSourceType === "mic") { // 如果音频源类型是麦克风
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ // 获取用户媒体
|
||||
audio: { noiseSuppression: true, echoCancellation: true }, // 音频配置
|
||||
}); // 等待获取用户媒体
|
||||
mediaStreamRef.current = stream; // 设置媒体流
|
||||
const source = // 创建音频源
|
||||
audioContextRef.current!.createMediaStreamSource(stream); // 创建音频源
|
||||
source.connect(analyserRef.current!); // 连接到分析器
|
||||
} else {
|
||||
const audio = new Audio("/test-audio.mp3"); // 创建音频元素
|
||||
const source = // 创建音频源
|
||||
audioContextRef.current!.createMediaElementSource(audio); // 创建音频源
|
||||
source.connect(analyserRef.current!); // 连接到分析器
|
||||
audio.play(); // 播放音频
|
||||
}
|
||||
|
||||
analyserRef.current!.connect(audioContextRef.current!.destination); // 连接到目标
|
||||
startVisualization(); // 开始可视化
|
||||
} catch (err) {
|
||||
console.error("初始化失败:", err);
|
||||
updateState({ error: "音频初始化失败" });
|
||||
}
|
||||
}
|
||||
setIsListening((prev) => !prev);
|
||||
}, [
|
||||
isListening,
|
||||
audioSourceType,
|
||||
cleanupAudio,
|
||||
initializeAudioContext,
|
||||
startVisualization,
|
||||
]);
|
||||
|
||||
// 示例音频播放
|
||||
const handlePlaySample = async () => {
|
||||
try {
|
||||
await cleanupAudio(); // 清理现有音频
|
||||
initializeAudioContext(); // 初始化音频上下文
|
||||
|
||||
const audio = new Audio("/test-audio.mp3"); // 创建音频元素
|
||||
const source = audioContextRef.current!.createMediaElementSource(audio); // 创建音频源
|
||||
source.connect(analyserRef.current!); // 连接到分析器
|
||||
analyserRef.current!.connect(audioContextRef.current!.destination); // 连接到目标
|
||||
|
||||
await audio.play(); // 播放音频
|
||||
startVisualization(); // 开始可视化
|
||||
|
||||
audio.onended = () => {
|
||||
setIsListening(false);
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
animationFrameRef.current = null;
|
||||
}
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("播放示例失败:", err);
|
||||
updateState({ error: "示例播放失败" });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center w-full px-4">
|
||||
{/* 问候语 */}
|
||||
<h1 className="text-6xl font-light mb-8 drop-shadow-glow">{greeting}</h1>
|
||||
{/* 较小较细的字体显示{asrText || "等待语音输入..."}*/}
|
||||
<h3 className="text-sm font-light mb-8">{asrText || "等待中..."}</h3>
|
||||
{/*较小较细的字体显示{answerText || "等待生成回答..."}*/}
|
||||
<h2 className="text-sm font-light mb-8">
|
||||
{answerText || "AI助手待命中"}
|
||||
</h2>
|
||||
|
||||
{/* 音频源切换 */}
|
||||
<div className="mb-4 flex justify-center gap-4">
|
||||
<button
|
||||
onClick={() => setAudioSourceType("mic")}
|
||||
className={`px-4 py-2 rounded-lg ${
|
||||
audioSourceType === "mic" ? "bg-blue-500 text-white" : "bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
麦克风
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setAudioSourceType("playback")}
|
||||
className={`px-4 py-2 rounded-lg ${
|
||||
audioSourceType === "playback"
|
||||
? "bg-blue-500 text-white"
|
||||
: "bg-gray-200"
|
||||
}`}
|
||||
>
|
||||
音频播放
|
||||
</button>
|
||||
</div>
|
||||
{/* 示例播放按钮 */}
|
||||
{audioSourceType === "playback" && (
|
||||
<button
|
||||
onClick={handlePlaySample}
|
||||
className="mt-4 px-6 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors"
|
||||
>
|
||||
播放示例音频
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* 优化后的音频波形可视化 */}
|
||||
<div className="relative inline-block">
|
||||
<button
|
||||
onClick={() => {
|
||||
toggleListening();
|
||||
processState.recording ? stopRecording() : startRecording();
|
||||
}}
|
||||
className={[
|
||||
"group relative flex h-20 items-end gap-1.5 rounded-3xl p-6",
|
||||
"bg-gradient-to-b from-black/80 to-gray-900/90",
|
||||
"shadow-[0_0_20px_0_rgba(34,211,238,0.2)] hover:shadow-[0_0_30px_0_rgba(109,213,237,0.3)]",
|
||||
"transition-shadow duration-300 ease-out",
|
||||
isListening ? "ring-2 ring-cyan-400/20" : "",
|
||||
].join(" ")}
|
||||
style={{
|
||||
// 禁用will-change优化(经测试反而降低性能)
|
||||
backdropFilter: "blur(12px)", // 直接使用CSS属性
|
||||
WebkitBackdropFilter: "blur(12px)",
|
||||
}}
|
||||
>
|
||||
{/* 优化后的柱状图容器 */}
|
||||
<div ref={barsRef} className="flex h-full w-full items-end gap-1.5">
|
||||
{[...Array(BAR_COUNT)].map((_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={[
|
||||
"w-2.5 rounded-full",
|
||||
"bg-gradient-to-t from-cyan-400/90 via-blue-400/90 to-purple-500/90",
|
||||
"transition-transform duration-150 ease-out",
|
||||
].join(" ")}
|
||||
style={{
|
||||
willChange: "height, transform", // 提示浏览器优化
|
||||
boxShadow: "0 0 8px -2px rgba(52,211,254,0.4)",
|
||||
height: "10%", // 初始高度
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 底部状态信息 */}
|
||||
<div className="mt-8 text-xs text-gray-500 space-y-1">
|
||||
<p>支持唤醒词:"魔镜魔镜"</p>
|
||||
<div className="flex items-center justify-center gap-1.5">
|
||||
<div className="relative flex items-center">
|
||||
{/* 呼吸圆点指示器 */}
|
||||
<div
|
||||
className={`w-2 h-2 rounded-full ${
|
||||
isListening ? "bg-green-400 animate-breath" : "bg-gray-400"
|
||||
}`}
|
||||
/>
|
||||
{/* 扩散波纹效果 */}
|
||||
{isListening && (
|
||||
<div className="absolute inset-0 rounded-full bg-green-400/20 animate-ping" />
|
||||
)}
|
||||
</div>
|
||||
<span>{getStatusText()}</span>
|
||||
</div>
|
||||
|
||||
{/* 音频播放 */}
|
||||
<audio
|
||||
ref={audioElement}
|
||||
controls={process.env.NODE_ENV === "development"} // 开发环境显示 controls
|
||||
onEnded={() => updateState({ synthesizing: false })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default VoiceAssistant;
|
239
src/components/VoiceAssistant copy.tsx
Normal file
239
src/components/VoiceAssistant copy.tsx
Normal file
@ -0,0 +1,239 @@
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
|
||||
interface VoiceAssistantProps {
|
||||
greeting: string;
|
||||
}
|
||||
|
||||
// 性能优化配置
|
||||
const ANALYSER_FFT_SIZE = 128; // 降低FFT大小提升性能
|
||||
const VOLUME_SENSITIVITY = 1.5;
|
||||
const SMOOTHING_FACTOR = 0.7; // 增加平滑系数减少突变
|
||||
const BAR_COUNT = 12; // 固定柱状图数量
|
||||
|
||||
const VoiceAssistant = ({ greeting }: VoiceAssistantProps) => {
|
||||
// 状态管理
|
||||
const [isListening, setIsListening] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// DOM元素引用
|
||||
const barsRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// 音频处理相关引用
|
||||
const mediaStreamRef = useRef<MediaStream | null>(null);
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const analyserRef = useRef<AnalyserNode | null>(null);
|
||||
const animationFrameRef = useRef<number | null>(null);
|
||||
|
||||
// 重用数据数组减少内存分配
|
||||
const dataArrayRef = useRef<Uint8Array | null>(null);
|
||||
const lastValuesRef = useRef<number[]>(new Array(BAR_COUNT).fill(10));
|
||||
|
||||
// 初始化音频处理(使用useCallback避免重复创建)
|
||||
const initAudioPipeline = useCallback(async () => {
|
||||
try {
|
||||
mediaStreamRef.current = await navigator.mediaDevices.getUserMedia({
|
||||
audio: {
|
||||
noiseSuppression: true,
|
||||
echoCancellation: true,
|
||||
autoGainControl: false,
|
||||
},
|
||||
});
|
||||
|
||||
const AudioContextClass =
|
||||
window.AudioContext || (window as any).webkitAudioContext;
|
||||
audioContextRef.current = new AudioContextClass({
|
||||
latencyHint: "balanced", // 平衡延迟和性能
|
||||
});
|
||||
|
||||
analyserRef.current = audioContextRef.current.createAnalyser();
|
||||
analyserRef.current.fftSize = ANALYSER_FFT_SIZE;
|
||||
analyserRef.current.smoothingTimeConstant = SMOOTHING_FACTOR;
|
||||
|
||||
// 初始化数据数组
|
||||
dataArrayRef.current = new Uint8Array(
|
||||
analyserRef.current.frequencyBinCount
|
||||
);
|
||||
|
||||
const source = audioContextRef.current.createMediaStreamSource(
|
||||
mediaStreamRef.current
|
||||
);
|
||||
source.connect(analyserRef.current);
|
||||
|
||||
startVisualization();
|
||||
} catch (err) {
|
||||
console.error("音频初始化失败:", err);
|
||||
setIsListening(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 优化后的可视化逻辑(直接操作DOM)
|
||||
const startVisualization = useCallback(() => {
|
||||
if (!analyserRef.current || !dataArrayRef.current) {
|
||||
console.error('Audio analyzer not initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取频率数据缓冲区长度
|
||||
const bufferLength = analyserRef.current.frequencyBinCount;
|
||||
|
||||
// 初始化时创建数据数组(安全校验)
|
||||
if (!dataArrayRef.current || dataArrayRef.current.length !== bufferLength) {
|
||||
dataArrayRef.current = new Uint8Array(bufferLength);
|
||||
}
|
||||
|
||||
// 定义动画帧回调
|
||||
const updateBars = () => {
|
||||
// 1. 获取最新频率数据
|
||||
analyserRef.current!.getByteFrequencyData(dataArrayRef.current!);
|
||||
|
||||
// 2. 性能优化:批量DOM操作
|
||||
const bars = barsRef.current?.children;
|
||||
if (!bars) return;
|
||||
|
||||
// 3. 使用现代循环代替Array.from提升性能
|
||||
for (let i = 0; i < bars.length; i++) {
|
||||
const bar = bars[i] as HTMLElement;
|
||||
|
||||
// 4. 优化数据采样策略(前1/2频谱)
|
||||
const dataIndex = Math.floor((i / BAR_COUNT) * (bufferLength / 2));
|
||||
const rawValue = (dataArrayRef.current![dataIndex] / 255) * 100 * VOLUME_SENSITIVITY;
|
||||
|
||||
// 5. 应用指数平滑滤波
|
||||
const smoothValue = Math.min(100, Math.max(10,
|
||||
rawValue * 0.6 + lastValuesRef.current[i] * 0.4
|
||||
));
|
||||
lastValuesRef.current[i] = smoothValue;
|
||||
|
||||
// 6. 复合样式更新(减少重排)
|
||||
bar.style.cssText = `
|
||||
height: ${smoothValue}%;
|
||||
transform: scaleY(${0.8 + (smoothValue / 100) * 0.6});
|
||||
animation-delay: ${i * 0.1}s;
|
||||
`;
|
||||
}
|
||||
|
||||
// 7. 使用绑定this的requestAnimationFrame
|
||||
animationFrameRef.current = requestAnimationFrame(updateBars.bind(this));
|
||||
};
|
||||
|
||||
// 8. 启动动画前取消已有帧
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
}
|
||||
animationFrameRef.current = requestAnimationFrame(updateBars);
|
||||
|
||||
// 9. 返回清理函数
|
||||
return () => {
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
}
|
||||
};
|
||||
}, []); // 10. 移除不必要的依赖项
|
||||
|
||||
// 切换监听状态
|
||||
const toggleListening = useCallback(async () => {
|
||||
if (isListening) {
|
||||
mediaStreamRef.current?.getTracks().forEach((track) => track.stop());
|
||||
audioContextRef.current?.close();
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
}
|
||||
} else {
|
||||
await initAudioPipeline();
|
||||
}
|
||||
setIsListening((prev) => !prev);
|
||||
}, [isListening, initAudioPipeline]);
|
||||
|
||||
// 清理资源
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (isListening) {
|
||||
mediaStreamRef.current?.getTracks().forEach((track) => track.stop());
|
||||
audioContextRef.current?.close();
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [isListening]);
|
||||
|
||||
return (
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center w-full px-4">
|
||||
{/* 问候语 */}
|
||||
<h1 className="text-6xl font-light mb-8 drop-shadow-glow">{greeting}</h1>
|
||||
|
||||
{/* 优化后的音频波形可视化 */}
|
||||
<div className="relative inline-block">
|
||||
<button
|
||||
onClick={toggleListening}
|
||||
className={[
|
||||
"group relative flex h-20 items-end gap-1.5 rounded-3xl p-6",
|
||||
"bg-gradient-to-b from-black/80 to-gray-900/90",
|
||||
"shadow-[0_0_20px_0_rgba(34,211,238,0.2)] hover:shadow-[0_0_30px_0_rgba(109,213,237,0.3)]",
|
||||
"transition-shadow duration-300 ease-out",
|
||||
isListening ? "ring-2 ring-cyan-400/20" : "",
|
||||
].join(" ")}
|
||||
style={{
|
||||
// 禁用will-change优化(经测试反而降低性能)
|
||||
backdropFilter: "blur(12px)", // 直接使用CSS属性
|
||||
WebkitBackdropFilter: "blur(12px)",
|
||||
}}
|
||||
>
|
||||
{/* 优化后的柱状图容器 */}
|
||||
<div ref={barsRef} className="flex h-full w-full items-end gap-1.5">
|
||||
{[...Array(BAR_COUNT)].map((_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={[
|
||||
"w-2.5 rounded-full",
|
||||
"bg-gradient-to-t from-cyan-400/90 via-blue-400/90 to-purple-500/90",
|
||||
"transition-transform duration-150 ease-out",
|
||||
].join(" ")}
|
||||
style={{
|
||||
willChange: "height, transform", // 提示浏览器优化
|
||||
boxShadow: "0 0 8px -2px rgba(52,211,254,0.4)",
|
||||
height: "10%", // 初始高度
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 底部状态信息 */}
|
||||
<div className="mt-8 text-xs text-gray-500 space-y-1">
|
||||
<p>支持唤醒词:"魔镜魔镜"</p>
|
||||
<div className="flex items-center justify-center gap-1.5">
|
||||
<div className="relative flex items-center">
|
||||
{/* 呼吸圆点指示器 */}
|
||||
<div
|
||||
className={`w-2 h-2 rounded-full ${
|
||||
isListening ? "bg-green-400 animate-breath" : "bg-gray-400"
|
||||
}`}
|
||||
/>
|
||||
{/* 扩散波纹效果 */}
|
||||
{isListening && (
|
||||
<div className="absolute inset-0 rounded-full bg-green-400/20 animate-ping" />
|
||||
)}
|
||||
</div>
|
||||
<span>音频状态: {isListening ? "监听中" : "待机"}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 错误提示 */}
|
||||
{error && (
|
||||
<div className="mt-6 text-red-400/90 text-lg animate-fade-in">
|
||||
{error}
|
||||
<button
|
||||
onClick={() => setError(null)}
|
||||
className="ml-3 text-gray-400 hover:text-gray-300 transition-colors"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default VoiceAssistant;
|
340
src/components/VoiceAssistant.tsx
Normal file
340
src/components/VoiceAssistant.tsx
Normal file
@ -0,0 +1,340 @@
|
||||
import { useState, useRef, useCallback } from "react";
|
||||
|
||||
interface ProcessState {
|
||||
recording: boolean;
|
||||
transcribing: boolean;
|
||||
generating: boolean;
|
||||
synthesizing: boolean;
|
||||
error?: string;
|
||||
thinking: boolean;
|
||||
speaking: boolean;
|
||||
}
|
||||
|
||||
interface VoiceAssistantProps {
|
||||
greeting: string;
|
||||
}
|
||||
|
||||
const ANALYSER_FFT_SIZE = 128;
|
||||
const VOLUME_SENSITIVITY = 1.5;
|
||||
const SMOOTHING_FACTOR = 0.7;
|
||||
const BAR_COUNT = 12;
|
||||
|
||||
const VoiceAssistant = ({ greeting }: VoiceAssistantProps) => {
|
||||
const [isListening, setIsListening] = useState(false);
|
||||
const [processState, setProcessState] = useState<ProcessState>({
|
||||
recording: false,
|
||||
transcribing: false,
|
||||
generating: false,
|
||||
synthesizing: false,
|
||||
error: undefined,
|
||||
thinking: false,
|
||||
speaking: false,
|
||||
});
|
||||
const [asrText, setAsrText] = useState("");
|
||||
const [answerText, setAnswerText] = useState("");
|
||||
const mediaRecorder = useRef<MediaRecorder | null>(null);
|
||||
const audioChunks = useRef<Blob[]>([]);
|
||||
const audioElement = useRef<HTMLAudioElement>(null);
|
||||
const barsRef = useRef<HTMLDivElement>(null);
|
||||
const mediaStreamRef = useRef<MediaStream | null>(null);
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const analyserRef = useRef<AnalyserNode | null>(null);
|
||||
const animationFrameRef = useRef<number | null>(null);
|
||||
const dataArrayRef = useRef<Uint8Array | null>(null);
|
||||
const lastValuesRef = useRef<number[]>(new Array(BAR_COUNT).fill(10));
|
||||
const updateState = (newState: Partial<ProcessState>) => {
|
||||
setProcessState((prev) => ({ ...prev, ...newState }));
|
||||
};
|
||||
|
||||
const cleanupAudio = useCallback(async () => {
|
||||
mediaStreamRef.current?.getTracks().forEach((track) => track.stop());
|
||||
if (audioContextRef.current?.state !== "closed") {
|
||||
await audioContextRef.current?.close();
|
||||
}
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
animationFrameRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
const initializeAudioContext = useCallback(() => {
|
||||
const AudioContextClass =
|
||||
window.AudioContext || (window as any).webkitAudioContext;
|
||||
audioContextRef.current = new AudioContextClass();
|
||||
analyserRef.current = audioContextRef.current.createAnalyser();
|
||||
analyserRef.current.fftSize = ANALYSER_FFT_SIZE;
|
||||
analyserRef.current.smoothingTimeConstant = SMOOTHING_FACTOR;
|
||||
dataArrayRef.current = new Uint8Array(
|
||||
analyserRef.current.frequencyBinCount
|
||||
);
|
||||
}, []);
|
||||
|
||||
const startRecording = async () => {
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: { sampleRate: 16000, channelCount: 1, sampleSize: 16 },
|
||||
});
|
||||
|
||||
mediaRecorder.current = new MediaRecorder(stream);
|
||||
audioChunks.current = [];
|
||||
|
||||
mediaRecorder.current.ondataavailable = (e) => {
|
||||
audioChunks.current.push(e.data);
|
||||
};
|
||||
|
||||
mediaRecorder.current.start(500);
|
||||
updateState({ recording: true, error: undefined });
|
||||
} catch (err) {
|
||||
updateState({ error: "麦克风访问失败,请检查权限设置" });
|
||||
}
|
||||
};
|
||||
|
||||
const stopRecording = async () => {
|
||||
if (!mediaRecorder.current) return;
|
||||
mediaRecorder.current.stop();
|
||||
// 更新状态为未录音
|
||||
updateState({ recording: false });
|
||||
mediaRecorder.current.onstop = async () => {
|
||||
try {
|
||||
const audioBlob = new Blob(audioChunks.current, { type: "audio/wav" });
|
||||
await processAudio(audioBlob);
|
||||
} finally {
|
||||
audioChunks.current = [];
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const processAudio = async (audioBlob: Blob) => {
|
||||
// 处理音频的函数
|
||||
const formData = new FormData();
|
||||
formData.append("audio", audioBlob, "recording.wav");
|
||||
try {
|
||||
updateState({ transcribing: true }); // 设置转录状态为true
|
||||
// 发送请求到后端
|
||||
const asrResponse = await fetch("http://localhost:5000/asr", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
// 如果请求失败,则抛出错误
|
||||
if (!asrResponse.ok) throw new Error("语音识别失败");
|
||||
// 获取后端返回的文本
|
||||
const asrData = await asrResponse.json();
|
||||
setAsrText(asrData.asr_text);
|
||||
updateState({ transcribing: false, thinking: true });
|
||||
|
||||
// 发送请求到后端,生成回答
|
||||
const generateResponse = await fetch("http://localhost:5000/generate", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ asr_text: asrData.asr_text }),
|
||||
});
|
||||
|
||||
if (!generateResponse.ok) throw new Error("生成回答失败");
|
||||
|
||||
const generateData = await generateResponse.json(); //获取生成的回答,设置为answerText
|
||||
setAnswerText(generateData.answer_text);
|
||||
updateState({ thinking: false, synthesizing: true });
|
||||
|
||||
// 播放合成的音频,增加可视化效果
|
||||
if (audioElement.current) {
|
||||
//设置说话状态
|
||||
updateState({ synthesizing: false, speaking: true }); // 替代setIsSpeaking(true)
|
||||
initializeAudioContext(); // 初始化音频上下文
|
||||
// 播放合成的音频
|
||||
//audioElement.current.src = `http://localhost:5000${generateData.audio_url}`;
|
||||
const audio = new Audio(
|
||||
`http://localhost:5000${generateData.audio_url}`
|
||||
); // 创建音频元素
|
||||
const source = audioContextRef.current!.createMediaElementSource(audio); // 创建音频源
|
||||
source.connect(analyserRef.current!); // 连接到分析器
|
||||
analyserRef.current!.connect(audioContextRef.current!.destination); // 连接到目标
|
||||
//播放结束设置说话状态为false
|
||||
audio.onended = () => {
|
||||
updateState({ speaking: false }); // 替代setIsSpeaking(false)
|
||||
};
|
||||
try {
|
||||
await audio.play(); // 播放音频
|
||||
startVisualization(); // 开始可视化效果
|
||||
} catch (err) {
|
||||
console.error("播放失败:", err);
|
||||
updateState({ error: "音频播放失败" });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
updateState({ error: err instanceof Error ? err.message : "未知错误" });
|
||||
} finally {
|
||||
updateState({
|
||||
transcribing: false,
|
||||
generating: false,
|
||||
synthesizing: false,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusText = () => {
|
||||
if (processState.error) return processState.error;
|
||||
if (processState.recording) return "请说... 🎤"; //录音
|
||||
if (processState.transcribing) return "识别音频中... 🔍"; //语音转文字
|
||||
if (processState.thinking) return "正在思考中... 💡"; // 等待AI回复
|
||||
if (processState.generating) return "生成回答中... 💡"; // AI以文字形式回复中//未使用
|
||||
if (processState.synthesizing) return "整理话语中... 🎶"; //收到AI回复,正在合成语音//未使用
|
||||
if (processState.speaking) return "说话中... 🗣📢"; // 播放合成后的语音
|
||||
return "对话未开始🎙️";
|
||||
};
|
||||
|
||||
const startVisualization = useCallback(() => {
|
||||
if (!analyserRef.current || !dataArrayRef.current || !barsRef.current) {
|
||||
console.warn("可视化组件未就绪");
|
||||
return;
|
||||
}
|
||||
|
||||
if (animationFrameRef.current) {
|
||||
cancelAnimationFrame(animationFrameRef.current);
|
||||
animationFrameRef.current = null;
|
||||
}
|
||||
|
||||
const bufferLength = analyserRef.current.frequencyBinCount;
|
||||
const updateBars = () => {
|
||||
try {
|
||||
analyserRef.current!.getByteFrequencyData(dataArrayRef.current!);
|
||||
|
||||
const bars = barsRef.current!.children;
|
||||
for (let i = 0; i < bars.length; i++) {
|
||||
const bar = bars[i] as HTMLElement;
|
||||
const dataIndex = Math.floor((i / BAR_COUNT) * (bufferLength / 2));
|
||||
const rawValue =
|
||||
(dataArrayRef.current![dataIndex] / 255) * 100 * VOLUME_SENSITIVITY;
|
||||
|
||||
const smoothValue = Math.min(
|
||||
100,
|
||||
Math.max(10, rawValue * 0.6 + lastValuesRef.current[i] * 0.4)
|
||||
);
|
||||
lastValuesRef.current[i] = smoothValue;
|
||||
|
||||
bar.style.cssText = `
|
||||
height: ${smoothValue}%;
|
||||
transform: scaleY(${0.8 + (smoothValue / 100) * 0.6});
|
||||
transition: ${i === 0 ? "none" : "height 50ms linear"};
|
||||
`;
|
||||
}
|
||||
|
||||
animationFrameRef.current = requestAnimationFrame(updateBars);
|
||||
} catch (err) {
|
||||
console.error("可视化更新失败:", err);
|
||||
}
|
||||
};
|
||||
|
||||
animationFrameRef.current = requestAnimationFrame(updateBars);
|
||||
}, [analyserRef, dataArrayRef, barsRef]);
|
||||
|
||||
// 切换监听状态
|
||||
const toggleListening = useCallback(async () => {
|
||||
if (isListening) {
|
||||
// 如果正在监听
|
||||
await cleanupAudio(); // 清理现有音频
|
||||
} else {
|
||||
// 否则
|
||||
try {
|
||||
// 尝试
|
||||
await cleanupAudio(); // 清理现有音频
|
||||
initializeAudioContext(); // 初始化音频上下文
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
audio: { noiseSuppression: true, echoCancellation: true },
|
||||
});
|
||||
mediaStreamRef.current = stream; // 设置媒体流
|
||||
const source = audioContextRef.current!.createMediaStreamSource(stream);
|
||||
source.connect(analyserRef.current!); // 只连接到分析器,不连接到目标
|
||||
//analyserRef.current!.connect(audioContextRef.current!.destination); // 连接到目标
|
||||
startVisualization(); // 开始可视化
|
||||
} catch (err) {
|
||||
console.error("初始化失败:", err);
|
||||
updateState({ error: "音频初始化失败" });
|
||||
}
|
||||
}
|
||||
setIsListening((prev) => !prev);
|
||||
}, [isListening, cleanupAudio, initializeAudioContext, startVisualization]);
|
||||
|
||||
return (
|
||||
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center w-full px-4">
|
||||
{/* 问候语 */}
|
||||
<h1 className="text-6xl font-light mb-8 drop-shadow-glow">{greeting}</h1>
|
||||
{/* 较小较细的字体显示{asrText || "等待语音输入..."}*/}
|
||||
<h3 className="text-sm font-light mb-8">{asrText || "等待中..."}</h3>
|
||||
{/*较小较细的字体显示{answerText || "等待生成回答..."}*/}
|
||||
<h2 className="text-sm font-light mb-8">
|
||||
{answerText || "AI助手待命中"}
|
||||
</h2>
|
||||
|
||||
{/* 音频波形可视化 */}
|
||||
<div className="relative inline-block">
|
||||
<button
|
||||
onClick={() => {
|
||||
toggleListening();
|
||||
processState.recording ? stopRecording() : startRecording();
|
||||
}}
|
||||
className={[
|
||||
"group relative flex h-20 items-end gap-1.5 rounded-[32px] p-6",
|
||||
"transition-all duration-300 ease-[cubic-bezier(0.68,-0.55,0.27,1.55)]",
|
||||
].join(" ")}
|
||||
style={{
|
||||
backdropFilter: "blur(16px)",
|
||||
WebkitBackdropFilter: "blur(16px)",
|
||||
}}
|
||||
>
|
||||
{/* 增强版音频波形 */}
|
||||
<div ref={barsRef} className="flex h-full w-full items-end gap-2.5">
|
||||
{[...Array(BAR_COUNT)].map((_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={[
|
||||
"w-2.5 rounded-lg",
|
||||
"bg-gradient-to-t from-cyan-400 via-blue-400/80 to-purple-500",
|
||||
"transition-all duration-200 ease-out",
|
||||
!processState.recording && !processState.speaking ? "animate-audio-wave" : "",
|
||||
].join(" ")}
|
||||
style={{
|
||||
height: "12%",
|
||||
animationDelay: `${index * 0.08}s`, // 保持原有延迟设置
|
||||
boxShadow: `
|
||||
0 0 12px -2px rgba(52,211,254,0.6),
|
||||
inset 0 2px 4px rgba(255,255,255,0.2)
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 底部状态信息 */}
|
||||
<div className="mt-8 text-xs text-gray-500 space-y-1">
|
||||
<p>支持唤醒词:"你好千问"</p>
|
||||
<div className="flex items-center justify-center gap-1.5">
|
||||
<div className="relative flex items-center">
|
||||
{/* 呼吸圆点指示器 */}
|
||||
<div
|
||||
className={`w-2 h-2 rounded-full ${
|
||||
isListening ? "bg-green-400 animate-breath" : "bg-gray-400"
|
||||
}`}
|
||||
/>
|
||||
{/* 扩散波纹效果 */}
|
||||
{isListening && (
|
||||
<div className="absolute inset-0 rounded-full bg-green-400/20 animate-ping" />
|
||||
)}
|
||||
</div>
|
||||
<span>{getStatusText()}</span>
|
||||
</div>
|
||||
|
||||
{/* 音频播放 */}
|
||||
<audio
|
||||
ref={audioElement}
|
||||
//controls={process.env.NODE_ENV === "development"} // 开发环境显示 controls
|
||||
//onEnded={() => updateState({ ,设置animate-audio-wave显示状态为true
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default VoiceAssistant;
|
53
src/components/WeatherIcons.tsx
Normal file
53
src/components/WeatherIcons.tsx
Normal file
@ -0,0 +1,53 @@
|
||||
// src/components/WeatherIcons.tsx
|
||||
import {
|
||||
WiDaySunny,
|
||||
WiNightClear,
|
||||
WiDayCloudy,
|
||||
WiNightAltCloudy,
|
||||
WiCloud,
|
||||
WiRain,
|
||||
WiSnow,
|
||||
WiStrongWind,
|
||||
WiFog,
|
||||
WiDust,
|
||||
} from "react-icons/wi";
|
||||
|
||||
interface WeatherIconProps {
|
||||
type: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const WeatherIcon = ({ type, className }: WeatherIconProps) => {
|
||||
const baseClass = "w-6 h-6 text-gray-100";
|
||||
|
||||
switch (type) {
|
||||
case "CLEAR_DAY":
|
||||
return (
|
||||
<WiDaySunny className={`${baseClass} text-yellow-400 ${className}`} />
|
||||
);
|
||||
case "CLEAR_NIGHT":
|
||||
return (
|
||||
<WiNightClear className={`${baseClass} text-blue-200 ${className}`} />
|
||||
);
|
||||
case "PARTLY_CLOUDY_DAY":
|
||||
return <WiDayCloudy className={`${baseClass} ${className}`} />;
|
||||
case "PARTLY_CLOUDY_NIGHT":
|
||||
return <WiNightAltCloudy className={`${baseClass} ${className}`} />;
|
||||
case "CLOUDY":
|
||||
return <WiCloud className={`${baseClass} ${className}`} />;
|
||||
case "RAIN":
|
||||
return <WiRain className={`${baseClass} text-blue-400 ${className}`} />;
|
||||
case "SNOW":
|
||||
return <WiSnow className={`${baseClass} text-blue-100 ${className}`} />;
|
||||
case "WIND":
|
||||
return <WiStrongWind className={`${baseClass} ${className}`} />;
|
||||
case "FOG":
|
||||
return <WiFog className={`${baseClass} ${className}`} />;
|
||||
case "HAZE":
|
||||
return <WiDust className={`${baseClass} text-yellow-600 ${className}`} />;
|
||||
default:
|
||||
return <WiDaySunny className={`${baseClass} ${className}`} />;
|
||||
}
|
||||
};
|
||||
|
||||
export default WeatherIcon;
|
134
src/components/WeatherSection.tsx
Normal file
134
src/components/WeatherSection.tsx
Normal file
@ -0,0 +1,134 @@
|
||||
// src/components/WeatherSection.tsx
|
||||
import { FC } from "react";
|
||||
import useSWR from "swr";
|
||||
import CircularProgress from "@mui/material/CircularProgress";
|
||||
import { WeatherData } from "../types/magic-mirror";
|
||||
import WeatherIcon from "./WeatherIcons";
|
||||
|
||||
const WeatherSection: FC = () => {
|
||||
const { data, error } = useSWR<WeatherData>(
|
||||
["weather", 116.3974, 39.9093],
|
||||
async ([, lon, lat]: [string, number, number]) => {
|
||||
const result = await window.electronAPI.getWeather({ lon, lat });
|
||||
if (result.error) throw new Error(result.message);
|
||||
return result;
|
||||
},
|
||||
{
|
||||
refreshInterval: 600000,
|
||||
onErrorRetry: (error) => {
|
||||
if (error.message.includes("超时")) return;
|
||||
},
|
||||
}
|
||||
);
|
||||
// 添加错误处理
|
||||
if (error) {
|
||||
return (
|
||||
<div className="absolute top-8 right-8 w-32 flex items-center justify-center">
|
||||
<span className="text-gray-400 text-sm">加载天气数据失败</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 优化加载状态
|
||||
if (!data)
|
||||
return (
|
||||
<div className="absolute top-8 right-8 w-64 flex items-center justify-center">
|
||||
<CircularProgress size={24} sx={{ color: "#9CA3AF" }} />
|
||||
<span className="ml-2 text-gray-400">天气加载中...</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 当前天气模块 */}
|
||||
<div className="absolute top-8 right-0 w-64 space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div className="space-y-1">
|
||||
<div className="text-gray-400">风速</div>
|
||||
<div className="text-gray-300">
|
||||
{data.realtime.wind.speed} {data.realtime.wind.direction}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<div className="text-gray-400">空气质量</div>
|
||||
<div className="text-gray-300">
|
||||
{data.realtime.airQuality.aqi} (
|
||||
{data.realtime.airQuality.description})
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
<WeatherIcon type={data.realtime.skycon} className="!w-16 h-16" />
|
||||
<div>
|
||||
<div className="text-3xl">{data.realtime.temperature}°C</div>
|
||||
<div className="text-gray-400 text-sm">
|
||||
体感 {data.realtime.apparentTemperature}°C
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 天气预报模块 */}
|
||||
{data.forecast && (
|
||||
<div className="absolute top-64 right-8 w-80 p-4">
|
||||
<div className="text-gray-200 text-sm font-medium mb-3">
|
||||
未来6天预报
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{data.forecast.temperature.slice(0, 6).map((day, index) => (
|
||||
<div
|
||||
key={day.date}
|
||||
className="grid grid-cols-4 items-center gap-4 group transition-all duration-200 hover:bg-white/5 px-3 py-2 rounded-lg"
|
||||
>
|
||||
{/* 日期 */}
|
||||
<div className="text-gray-300 text-sm w-14">
|
||||
{new Date(day.date).toLocaleDateString("zh-CN", {
|
||||
weekday: "short",
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 天气图标和降水概率 */}
|
||||
<div className="flex items-center gap-2">
|
||||
<WeatherIcon
|
||||
type={data.forecast.skycon[index].value}
|
||||
className="w-6 h-6"
|
||||
/>
|
||||
<div className=" text-xs font-medium">
|
||||
{data.forecast.precipitation[index].probability}%
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 温度条 */}
|
||||
<div className="flex-1">
|
||||
<div className="relative h-1.5 bg-gray-700 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="absolute inset-0 bg-gradient-to-r from-blue-400 to-red-400"
|
||||
style={{
|
||||
width: `${((day.max - day.min) / 30) * 100}%`,
|
||||
left: `${((day.min - 0) / 30) * 100}%`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 温度数值 */}
|
||||
<div className="flex items-center justify-between w-24">
|
||||
<span className="text-blue-300 text-sm">
|
||||
{Math.round(day.min)}°
|
||||
</span>
|
||||
<span className="text-gray-400 text-xs">→</span>
|
||||
<span className="text-red-300 text-sm">
|
||||
{Math.round(day.max)}°
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default WeatherSection;
|
68
src/index.css
Normal file
68
src/index.css
Normal file
@ -0,0 +1,68 @@
|
||||
:root {
|
||||
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
|
||||
color-scheme: light dark;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
background-color: #242424;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: 500;
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
place-items: center;
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 3.2em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
padding: 0.6em 1.2em;
|
||||
font-size: 1em;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
background-color: #1a1a1a;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.25s;
|
||||
}
|
||||
button:hover {
|
||||
border-color: #646cff;
|
||||
}
|
||||
button:focus,
|
||||
button:focus-visible {
|
||||
outline: 4px auto -webkit-focus-ring-color;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color: #213547;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
a:hover {
|
||||
color: #747bff;
|
||||
}
|
||||
button {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
}
|
11
src/main.tsx
Normal file
11
src/main.tsx
Normal file
@ -0,0 +1,11 @@
|
||||
//src\main.tsx
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App'
|
||||
import './styles/globals.css'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
)
|
24
src/styles/globals.css
Normal file
24
src/styles/globals.css
Normal file
@ -0,0 +1,24 @@
|
||||
/*src\styles\globals.css*/
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* src/styles/globals.css */
|
||||
/* 基础流动效果 */
|
||||
@keyframes wave-flow {
|
||||
0%, 100% {
|
||||
transform: scaleY(0.6) skewY(-3deg);
|
||||
opacity: 0.4;
|
||||
}
|
||||
50% {
|
||||
transform: scaleY(1.5) skewY(2deg);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
.animate-audio-wave {
|
||||
animation: wave-flow 1.1s cubic-bezier(0.4, 0, 0.2, 1) infinite;
|
||||
transition:
|
||||
opacity 0.3s ease,
|
||||
transform 0.3s ease;
|
||||
}
|
88
src/types/magic-mirror.d.ts
vendored
Normal file
88
src/types/magic-mirror.d.ts
vendored
Normal file
@ -0,0 +1,88 @@
|
||||
declare global {
|
||||
interface Window {
|
||||
electronAPI: {
|
||||
getWeather: (params: { lon: number; lat: number }) => Promise<WeatherData>;
|
||||
getNews: () => Promise<NewsItem[]>;
|
||||
};
|
||||
}
|
||||
}
|
||||
/*
|
||||
SunIcon,
|
||||
MoonIcon,
|
||||
CloudIcon,
|
||||
CloudSunIcon,
|
||||
CloudMoonIcon,
|
||||
UmbrellaIcon,
|
||||
SnowflakeIcon,
|
||||
WindIcon,
|
||||
FaceSmileIcon
|
||||
*/
|
||||
declare module '@heroicons/react/24/solid' {
|
||||
export const SunIcon: React.FC<React.SVGProps<SVGSVGElement>>;
|
||||
export const MoonIcon: React.FC<React.SVGProps<SVGSVGElement>>;
|
||||
export const CloudIcon: React.FC<React.SVGProps<SVGSVGElement>>;
|
||||
export const CloudSunIcon: React.FC<React.SVGProps<SVGSVGElement>>;
|
||||
export const CloudMoonIcon: React.FC<React.SVGProps<SVGSVGElement>>;
|
||||
export const UmbrellaIcon: React.FC<React.SVGProps<SVGSVGElement>>;
|
||||
export const SnowflakeIcon: React.FC<React.SVGProps<SVGSVGElement>>;
|
||||
export const WindIcon: React.FC<React.SVGProps<SVGSVGElement>>;
|
||||
export const FaceSmileIcon: React.FC<React.SVGProps<SVGSVGElement>>
|
||||
|
||||
}
|
||||
//src\types\magic-mirror.d.ts
|
||||
export interface WeatherData {
|
||||
error: any;
|
||||
realtime: {
|
||||
temperature: string;
|
||||
humidity: string;
|
||||
wind: {
|
||||
speed: string;
|
||||
direction: string;
|
||||
};
|
||||
airQuality: {
|
||||
aqi: number;
|
||||
description: string;
|
||||
};
|
||||
skycon: string;
|
||||
apparentTemperature: string;
|
||||
};
|
||||
forecast: {
|
||||
temperature: Array<{
|
||||
date: string;
|
||||
max: number;
|
||||
min: number;
|
||||
}>;
|
||||
skycon: Array<{
|
||||
date: string;
|
||||
value: string;
|
||||
}>;
|
||||
precipitation: Array<{
|
||||
date: string;
|
||||
probability: number;
|
||||
}>;
|
||||
};
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface SunData {
|
||||
date: string
|
||||
sunrise: string
|
||||
sunset: string
|
||||
}
|
||||
|
||||
export interface NewsItem {
|
||||
uniquekey: string
|
||||
title: string
|
||||
date: string
|
||||
category: string
|
||||
author_name: string
|
||||
url: string
|
||||
thumbnail_pic_s?: string
|
||||
is_content: string
|
||||
}
|
||||
|
||||
export type CalendarDay = {
|
||||
day: number
|
||||
isCurrent: boolean
|
||||
isEmpty: boolean
|
||||
}
|
18
src/utils/calendar.ts
Normal file
18
src/utils/calendar.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { CalendarDay } from "../types/magic-mirror"
|
||||
|
||||
export const generateCalendarDays = (): CalendarDay[] => {
|
||||
const date = new Date()
|
||||
const year = date.getFullYear()
|
||||
const month = date.getMonth()
|
||||
const firstDay = new Date(year, month, 1).getDay()
|
||||
const daysInMonth = new Date(year, month + 1, 0).getDate()
|
||||
|
||||
return Array.from({ length: 42 }, (_, i) => {
|
||||
const day = i - firstDay + 1
|
||||
return {
|
||||
day: day > 0 && day <= daysInMonth ? day : 0,
|
||||
isCurrent: day === date.getDate(),
|
||||
isEmpty: day <= 0 || day > daysInMonth,
|
||||
}
|
||||
})
|
||||
}
|
1
src/vite-env.d.ts
vendored
Normal file
1
src/vite-env.d.ts
vendored
Normal file
@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
18
tailwind.config.js
Normal file
18
tailwind.config.js
Normal file
@ -0,0 +1,18 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = {
|
||||
content: [
|
||||
'./src/**/*.{ts,tsx,js,jsx}', // 确保包含所有需要 Tailwind 处理的文件
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
gray: {
|
||||
300: '#D1D5DB',
|
||||
400: '#9CA3AF',
|
||||
500: '#6B7280',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
26
tsconfig.app.json
Normal file
26
tsconfig.app.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"isolatedModules": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
8
tsconfig.json
Normal file
8
tsconfig.json
Normal file
@ -0,0 +1,8 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" },
|
||||
{ "path": "./tsconfig.vite.json" }
|
||||
]
|
||||
}
|
30
tsconfig.node.json
Normal file
30
tsconfig.node.json
Normal file
@ -0,0 +1,30 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "CommonJS",
|
||||
"moduleResolution": "Node",
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "./dist-electron",
|
||||
"rootDir": "./electron",
|
||||
"noEmit": false, // 必须设置为 false 才能生成 JS 文件
|
||||
"typeRoots": [
|
||||
"./node_modules/@types",
|
||||
"./src/types" // 添加类型声明路径
|
||||
],
|
||||
"composite": true // 启用组合模式
|
||||
},
|
||||
"include": [
|
||||
"electron/**/*.ts",
|
||||
"src/types/**/*.d.ts" // 明确包含类型声明文件
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"dist",
|
||||
"src/**/*.tsx", // 排除渲染进程代码
|
||||
//"src/**/*.ts" // 排除渲染进程代码
|
||||
]
|
||||
}
|
4
tsconfig.vite.json
Normal file
4
tsconfig.vite.json
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "./tsconfig.app.json",
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
23
vite.config.ts
Normal file
23
vite.config.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { builtinModules } from 'module'
|
||||
import path from 'path'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
rollupOptions: {
|
||||
external: [
|
||||
...builtinModules,
|
||||
'electron' // 排除 Electron 原生模块
|
||||
]
|
||||
}
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': path.resolve(__dirname, './src'),
|
||||
'~electron': path.resolve(__dirname, './electron')
|
||||
}
|
||||
}
|
||||
})
|
Loading…
Reference in New Issue
Block a user