Compare commits
14 Commits
feature_bu
...
feature_bu
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e3c408f13 | ||
|
|
9b4fafc0b0 | ||
|
|
9de4e10637 | ||
|
|
db7efeb1fe | ||
|
|
838e7d7272 | ||
|
|
21564ebf4d | ||
|
|
c593582006 | ||
|
|
e555d22499 | ||
|
|
8ced77c604 | ||
|
|
880c91e3de | ||
|
|
71f2e89072 | ||
|
|
9069a2be55 | ||
|
|
d5686fed9d | ||
|
|
891ea6d88e |
@@ -17,13 +17,13 @@ NODE_ENV=production
|
||||
REACT_APP_ENABLE_MOCK=false
|
||||
|
||||
# 🔧 调试模式(生产环境临时调试用)
|
||||
# 开启后会在全局暴露 window.__DEBUG__ 和 window.__TEST_NOTIFICATION__ 调试 API
|
||||
# 开启后会在全局暴露 window.__DEBUG__ 调试 API
|
||||
# ⚠️ 警告: 调试模式会记录所有 API 请求/响应,调试完成后请立即关闭!
|
||||
# 使用方法:
|
||||
# 1. 设置为 true 并重新构建
|
||||
# 2. 在浏览器控制台使用 window.__DEBUG__.help() 查看命令
|
||||
# 3. 调试完成后设置为 false 并重新构建
|
||||
REACT_APP_ENABLE_DEBUG=true
|
||||
REACT_APP_ENABLE_DEBUG=false
|
||||
|
||||
# 后端 API 地址(生产环境)
|
||||
REACT_APP_API_URL=http://49.232.185.254:5001
|
||||
@@ -49,18 +49,3 @@ TSC_COMPILE_ON_ERROR=true
|
||||
IMAGE_INLINE_SIZE_LIMIT=10000
|
||||
# Node.js 内存限制(适用于大型项目)
|
||||
NODE_OPTIONS=--max_old_space_size=4096
|
||||
|
||||
# ========================================
|
||||
# Bytedesk 客服系统配置
|
||||
# ========================================
|
||||
# Bytedesk 服务器地址
|
||||
REACT_APP_BYTEDESK_API_URL=http://43.143.189.195
|
||||
|
||||
# 组织 ID(从管理后台获取)
|
||||
REACT_APP_BYTEDESK_ORG=df_org_uid
|
||||
|
||||
# 工作组 ID(从管理后台获取)
|
||||
REACT_APP_BYTEDESK_SID=df_wg_aftersales
|
||||
|
||||
# 客服类型(2=人工客服, 1=机器人)
|
||||
REACT_APP_BYTEDESK_TYPE=2
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
# Bytedesk 客服系统集成文件
|
||||
|
||||
以下文件和目录属于客服系统集成功能,未提交到当前分支:
|
||||
|
||||
## 1. Dify 机器人控制逻辑
|
||||
**位置**: public/index.html
|
||||
**状态**: 已存入 stash
|
||||
**Stash ID**: stash@{0}
|
||||
**说明**: 根据路径控制 Dify 机器人显示(已设置为完全不显示,只使用 Bytedesk 客服)
|
||||
|
||||
## 2. Bytedesk 集成代码
|
||||
**位置**: src/bytedesk-integration/
|
||||
**状态**: 未跟踪文件(需要手动管理)
|
||||
**内容**:
|
||||
- .env.bytedesk.example - Bytedesk 环境变量配置示例
|
||||
- App.jsx.example - 集成 Bytedesk 的示例代码
|
||||
- components/ - Bytedesk 相关组件
|
||||
- config/ - Bytedesk 配置文件
|
||||
- 前端工程师集成手册.md - 详细集成文档
|
||||
|
||||
## 恢复方法
|
||||
|
||||
### 恢复 public/index.html 的改动:
|
||||
```bash
|
||||
git stash apply stash@{0}
|
||||
```
|
||||
|
||||
### 使用 Bytedesk 集成代码:
|
||||
```bash
|
||||
# 查看集成手册
|
||||
cat src/bytedesk-integration/前端工程师集成手册.md
|
||||
|
||||
# 复制示例配置
|
||||
cp src/bytedesk-integration/.env.bytedesk.example .env.bytedesk
|
||||
cp src/bytedesk-integration/App.jsx.example src/App.jsx
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
⚠️ **重要提示:**
|
||||
- `src/bytedesk-integration/` 目录中的文件是未跟踪的(untracked)
|
||||
- 如果需要提交客服功能,需要先添加到 git:
|
||||
```bash
|
||||
git add src/bytedesk-integration/
|
||||
git commit -m "feat: 集成 Bytedesk 客服系统"
|
||||
```
|
||||
|
||||
- 当前分支(feature_bugfix/251110_event)专注于非客服功能
|
||||
- 建议在单独的分支中开发客服功能
|
||||
@@ -65,9 +65,6 @@
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
<!-- ============================================
|
||||
Dify 机器人配置 - 只在 /home 页面显示
|
||||
============================================ -->
|
||||
<script>
|
||||
window.difyChatbotConfig = {
|
||||
token: 'DwN8qAKtYFQtWskM',
|
||||
@@ -87,45 +84,91 @@
|
||||
// name: 'YOU CAN DEFINE USER NAME HERE',
|
||||
},
|
||||
}
|
||||
|
||||
// 根据路径控制Dify机器人显示(只在首页/和home页/home显示)
|
||||
function controlDifyChatbot() {
|
||||
const path = window.location.pathname;
|
||||
const chatbotButton = document.getElementById('dify-chatbot-bubble-button');
|
||||
const chatbotWindow = document.getElementById('dify-chatbot-bubble-window');
|
||||
|
||||
// 只在首页(/)和home页(/home)显示Dify机器人
|
||||
// const shouldShowDify = (path === '/' || path === '/home');
|
||||
// 完全不显示Dify机器人(只使用Bytedesk客服)
|
||||
const shouldShowDify = false
|
||||
|
||||
if (chatbotButton) {
|
||||
chatbotButton.style.display = shouldShowDify ? 'block' : 'none';
|
||||
// 同时设置visibility确保完全隐藏
|
||||
chatbotButton.style.visibility = shouldShowDify ? 'visible' : 'hidden';
|
||||
}
|
||||
|
||||
if (chatbotWindow) {
|
||||
chatbotWindow.style.display = shouldShowDify ? '' : 'none';
|
||||
}
|
||||
|
||||
console.log('[Dify] Path:', path, 'Should show:', shouldShowDify, 'Button found:', !!chatbotButton);
|
||||
}
|
||||
|
||||
// 轮询检查Dify按钮(因为Dify脚本加载是异步的)
|
||||
let difyCheckCount = 0;
|
||||
const difyCheckInterval = setInterval(function() {
|
||||
const button = document.getElementById('dify-chatbot-bubble-button');
|
||||
if (button || difyCheckCount > 50) { // 最多检查5秒
|
||||
if (button) {
|
||||
console.log('[Dify] Button found, applying control');
|
||||
controlDifyChatbot();
|
||||
}
|
||||
clearInterval(difyCheckInterval);
|
||||
}
|
||||
difyCheckCount++;
|
||||
}, 100);
|
||||
|
||||
// 页面加载时执行
|
||||
window.addEventListener('load', function() {
|
||||
setTimeout(controlDifyChatbot, 1000);
|
||||
});
|
||||
|
||||
// 监听路由变化(React Router使用pushState)
|
||||
window.addEventListener('popstate', controlDifyChatbot);
|
||||
|
||||
// 监听pushState和replaceState(捕获React Router导航)
|
||||
const originalPushState = history.pushState;
|
||||
const originalReplaceState = history.replaceState;
|
||||
|
||||
history.pushState = function() {
|
||||
originalPushState.apply(history, arguments);
|
||||
setTimeout(controlDifyChatbot, 50);
|
||||
};
|
||||
|
||||
history.replaceState = function() {
|
||||
originalReplaceState.apply(history, arguments);
|
||||
setTimeout(controlDifyChatbot, 50);
|
||||
};
|
||||
|
||||
// 使用MutationObserver监听DOM变化(捕获Dify按钮插入)
|
||||
const observer = new MutationObserver(function(mutations) {
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.addedNodes.length > 0) {
|
||||
for (const node of mutation.addedNodes) {
|
||||
if (node.id && (node.id.includes('dify') || node.id.includes('chatbot'))) {
|
||||
console.log('[Dify] Detected chatbot element insertion:', node.id);
|
||||
setTimeout(controlDifyChatbot, 100);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 观察body的变化
|
||||
window.addEventListener('DOMContentLoaded', function() {
|
||||
observer.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: false
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- Dify 机器人显示控制脚本 -->
|
||||
<script>
|
||||
// 控制 Dify 机器人只在 /home 页面显示
|
||||
function controlDifyVisibility() {
|
||||
const currentPath = window.location.pathname;
|
||||
const difyChatButton = document.getElementById('dify-chatbot-bubble-button');
|
||||
|
||||
if (difyChatButton) {
|
||||
// 只在 /home 页面显示
|
||||
if (currentPath === '/home') {
|
||||
difyChatButton.style.display = 'flex';
|
||||
console.log('[Dify] 显示机器人(当前路径: /home)');
|
||||
} else {
|
||||
difyChatButton.style.display = 'none';
|
||||
console.log('[Dify] 隐藏机器人(当前路径:', currentPath, ')');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载完成后执行
|
||||
window.addEventListener('load', function() {
|
||||
console.log('[Dify] 初始化显示控制');
|
||||
|
||||
// 初始检查(延迟执行,等待 Dify 按钮渲染)
|
||||
setTimeout(controlDifyVisibility, 500);
|
||||
setTimeout(controlDifyVisibility, 1500);
|
||||
|
||||
// 监听路由变化(React Router 使用 pushState)
|
||||
const observer = setInterval(controlDifyVisibility, 1000);
|
||||
|
||||
// 清理函数(可选)
|
||||
window.addEventListener('beforeunload', function() {
|
||||
clearInterval(observer);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
<script
|
||||
src="https://app.valuefrontier.cn/embed.min.js"
|
||||
id="DwN8qAKtYFQtWskM"
|
||||
@@ -207,7 +250,7 @@
|
||||
bottom: 80px !important;
|
||||
left: 10px !important;
|
||||
}
|
||||
|
||||
|
||||
#dify-chatbot-bubble-button {
|
||||
width: 56px !important;
|
||||
height: 56px !important;
|
||||
|
||||
@@ -35,7 +35,7 @@ self.addEventListener('notificationclick', (event) => {
|
||||
.then((windowClients) => {
|
||||
// 查找是否已有打开的窗口
|
||||
for (let client of windowClients) {
|
||||
if (client.url.includes(self.location.origin) && 'focus' in client) {
|
||||
if (client.url.includes(window.location.origin) && 'focus' in client) {
|
||||
// 聚焦现有窗口并导航到目标页面
|
||||
return client.focus().then(client => {
|
||||
return client.navigate(urlToOpen);
|
||||
|
||||
@@ -82,28 +82,65 @@ const BytedeskWidget = ({
|
||||
return () => {
|
||||
console.log('[Bytedesk] 清理Widget');
|
||||
|
||||
// 移除脚本
|
||||
if (scriptRef.current && document.body.contains(scriptRef.current)) {
|
||||
document.body.removeChild(scriptRef.current);
|
||||
}
|
||||
|
||||
// 移除Widget DOM元素
|
||||
const widgetElements = document.querySelectorAll('[class*="bytedesk"], [id*="bytedesk"]');
|
||||
widgetElements.forEach(el => {
|
||||
if (el && el.parentNode) {
|
||||
el.parentNode.removeChild(el);
|
||||
try {
|
||||
// 调用Widget的destroy方法(如果存在)
|
||||
if (widgetRef.current && typeof widgetRef.current.destroy === 'function') {
|
||||
console.log('[Bytedesk] 调用Widget.destroy()');
|
||||
widgetRef.current.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
// 清理全局对象
|
||||
if (window.BytedeskWeb) {
|
||||
delete window.BytedeskWeb;
|
||||
} catch (error) {
|
||||
console.warn('[Bytedesk] Widget.destroy()失败:', error.message);
|
||||
}
|
||||
|
||||
try {
|
||||
// 移除脚本
|
||||
if (scriptRef.current) {
|
||||
if (document.body.contains(scriptRef.current)) {
|
||||
document.body.removeChild(scriptRef.current);
|
||||
}
|
||||
scriptRef.current = null;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[Bytedesk] 移除脚本失败:', error.message);
|
||||
}
|
||||
|
||||
try {
|
||||
// 移除Widget DOM元素(使用更安全的remove()方法)
|
||||
const widgetElements = document.querySelectorAll('[class*="bytedesk"], [id*="bytedesk"]');
|
||||
widgetElements.forEach(el => {
|
||||
try {
|
||||
if (el && el.parentNode) {
|
||||
// 优先使用remove()方法(更现代、更安全)
|
||||
if (typeof el.remove === 'function') {
|
||||
el.remove();
|
||||
} else {
|
||||
el.parentNode.removeChild(el);
|
||||
}
|
||||
}
|
||||
} catch (removeError) {
|
||||
console.warn('[Bytedesk] 移除DOM元素失败:', el, removeError.message);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('[Bytedesk] 清理DOM元素失败:', error.message);
|
||||
}
|
||||
|
||||
try {
|
||||
// 清理全局对象
|
||||
if (window.BytedeskWeb) {
|
||||
delete window.BytedeskWeb;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[Bytedesk] 清理全局对象失败:', error.message);
|
||||
}
|
||||
|
||||
console.log('[Bytedesk] Widget清理完成');
|
||||
};
|
||||
}, [config, autoLoad, onLoad, onError]);
|
||||
|
||||
// 不渲染任何可见元素(Widget会自动插入到body)
|
||||
return <div id="bytedesk-widget-container" style={{ display: 'none' }} />;
|
||||
// 不渲染任何元素(Widget会自动插入DOM到body)
|
||||
// 返回null避免React DOM管理冲突
|
||||
return null;
|
||||
};
|
||||
|
||||
BytedeskWidget.propTypes = {
|
||||
|
||||
@@ -64,16 +64,16 @@ export const bytedeskConfig = {
|
||||
* @returns {Object} Bytedesk配置对象
|
||||
*/
|
||||
export const getBytedeskConfig = () => {
|
||||
// 开发环境使用代理(绕过 X-Frame-Options 限制)
|
||||
// 开发环境使用代理(绕过X-Frame-Options限制)
|
||||
if (process.env.NODE_ENV === 'development') {
|
||||
return {
|
||||
...bytedeskConfig,
|
||||
apiUrl: '/bytedesk-api', // 使用 CRACO 代理路径
|
||||
htmlUrl: '/bytedesk-api/chat/', // 使用 CRACO 代理路径
|
||||
apiUrl: '/bytedesk-api',
|
||||
htmlUrl: '/bytedesk-api/chat/',
|
||||
};
|
||||
}
|
||||
|
||||
// 生产环境使用完整 URL
|
||||
// 生产环境使用完整URL
|
||||
return bytedeskConfig;
|
||||
};
|
||||
|
||||
@@ -118,33 +118,8 @@ export const getBytedeskConfigWithUser = (user) => {
|
||||
* @returns {boolean} 是否显示客服
|
||||
*/
|
||||
export const shouldShowCustomerService = (pathname) => {
|
||||
// 在以下页面隐藏客服(黑名单)
|
||||
const blockedPages = [
|
||||
'/home', // 登录页
|
||||
];
|
||||
|
||||
// 检查是否在黑名单
|
||||
if (blockedPages.some(page => pathname.startsWith(page))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 默认所有页面都显示客服
|
||||
// 所有页面都显示Bytedesk客服
|
||||
return true;
|
||||
|
||||
/* ============================================
|
||||
白名单模式(备用,需要时取消注释)
|
||||
============================================
|
||||
const allowedPages = [
|
||||
'/', // 首页
|
||||
'/home', // 主页
|
||||
'/products', // 产品页
|
||||
'/pricing', // 价格页
|
||||
'/contact', // 联系我们
|
||||
];
|
||||
|
||||
// 只在白名单页面显示客服
|
||||
return allowedPages.some(page => pathname.startsWith(page));
|
||||
============================================ */
|
||||
};
|
||||
|
||||
export default {
|
||||
|
||||
@@ -59,11 +59,6 @@ export const NotificationProvider = ({ children }) => {
|
||||
const MAX_PROCESSED_IDS = 1000; // 最多保留1000个ID,避免内存泄漏
|
||||
const notificationTimers = useRef(new Map()); // 跟踪所有通知的自动关闭定时器
|
||||
|
||||
// ⚡ 方案2: 使用 Ref 存储最新的回调函数引用(避免闭包陷阱)
|
||||
const addNotificationRef = useRef(null);
|
||||
const adaptEventToNotificationRef = useRef(null);
|
||||
const isFirstConnect = useRef(true); // 标记是否首次连接
|
||||
|
||||
// ⚡ 使用权限引导管理 Hook
|
||||
const { shouldShowGuide, markGuideAsShown } = usePermissionGuide();
|
||||
|
||||
@@ -600,42 +595,26 @@ export const NotificationProvider = ({ children }) => {
|
||||
return newNotification.id;
|
||||
}, [notifications, toast, sendBrowserNotification, addWebNotification, browserPermission, hasRequestedPermission, requestBrowserPermission]);
|
||||
|
||||
/**
|
||||
* ✅ 方案2: 同步最新的回调函数到 Ref
|
||||
* 确保 Socket 监听器始终使用最新的函数引用(避免闭包陷阱)
|
||||
*/
|
||||
useEffect(() => {
|
||||
addNotificationRef.current = addNotification;
|
||||
console.log('[NotificationContext] 📝 已更新 addNotificationRef');
|
||||
}, [addNotification]);
|
||||
|
||||
useEffect(() => {
|
||||
adaptEventToNotificationRef.current = adaptEventToNotification;
|
||||
console.log('[NotificationContext] 📝 已更新 adaptEventToNotificationRef');
|
||||
}, [adaptEventToNotification]);
|
||||
|
||||
|
||||
// ========== 连接到 Socket 服务(⚡ 方案2: 只执行一次) ==========
|
||||
// 连接到 Socket 服务
|
||||
useEffect(() => {
|
||||
logger.info('NotificationContext', 'Initializing socket connection...');
|
||||
console.log('%c[NotificationContext] 🚀 初始化 Socket 连接(方案2:只注册一次)', 'color: #673AB7; font-weight: bold;');
|
||||
console.log('%c[NotificationContext] Initializing socket connection', 'color: #673AB7; font-weight: bold;');
|
||||
|
||||
// ========== 监听连接成功(首次连接 + 重连) ==========
|
||||
// ✅ 第一步: 注册所有事件监听器
|
||||
console.log('%c[NotificationContext] Step 1: Registering event listeners...', 'color: #673AB7;');
|
||||
|
||||
// 监听连接状态
|
||||
socket.on('connect', () => {
|
||||
const wasDisconnected = connectionStatus !== CONNECTION_STATUS.CONNECTED;
|
||||
setIsConnected(true);
|
||||
setReconnectAttempt(0);
|
||||
logger.info('NotificationContext', 'Socket connected', { wasDisconnected });
|
||||
console.log('%c[NotificationContext] ✅ Received connect event, updating state to connected', 'color: #4CAF50; font-weight: bold;');
|
||||
|
||||
// 判断是首次连接还是重连
|
||||
if (isFirstConnect.current) {
|
||||
console.log('%c[NotificationContext] ✅ 首次连接成功', 'color: #4CAF50; font-weight: bold;');
|
||||
console.log('[NotificationContext] Socket ID:', socket.getSocketId?.());
|
||||
setConnectionStatus(CONNECTION_STATUS.CONNECTED);
|
||||
isFirstConnect.current = false;
|
||||
logger.info('NotificationContext', 'Socket connected (first time)');
|
||||
} else {
|
||||
console.log('%c[NotificationContext] 🔄 重连成功!', 'color: #FF9800; font-weight: bold;');
|
||||
// 如果之前断开过,显示 RECONNECTED 状态2秒后自动消失
|
||||
if (wasDisconnected) {
|
||||
setConnectionStatus(CONNECTION_STATUS.RECONNECTED);
|
||||
logger.info('NotificationContext', 'Socket reconnected');
|
||||
logger.info('NotificationContext', 'Reconnected, will auto-dismiss in 2s');
|
||||
|
||||
// 清除之前的定时器
|
||||
if (reconnectedTimerRef.current) {
|
||||
@@ -647,10 +626,12 @@ export const NotificationProvider = ({ children }) => {
|
||||
setConnectionStatus(CONNECTION_STATUS.CONNECTED);
|
||||
logger.info('NotificationContext', 'Auto-dismissed RECONNECTED status');
|
||||
}, 2000);
|
||||
} else {
|
||||
setConnectionStatus(CONNECTION_STATUS.CONNECTED);
|
||||
}
|
||||
|
||||
// ⚡ 重连后只需重新订阅,不需要重新注册监听器
|
||||
console.log('%c[NotificationContext] 🔔 重新订阅事件推送...', 'color: #FF9800; font-weight: bold;');
|
||||
// 订阅事件推送
|
||||
console.log('%c[NotificationContext] 🔔 订阅事件推送...', 'color: #FF9800; font-weight: bold;');
|
||||
|
||||
if (socket.subscribeToEvents) {
|
||||
socket.subscribeToEvents({
|
||||
@@ -661,47 +642,45 @@ export const NotificationProvider = ({ children }) => {
|
||||
console.log('[NotificationContext] 订阅确认:', data);
|
||||
logger.info('NotificationContext', 'Events subscribed', data);
|
||||
},
|
||||
// ⚠️ 不需要 onNewEvent 回调,因为 NotificationContext 已经通过 socket.on('new_event') 监听
|
||||
});
|
||||
} else {
|
||||
console.error('[NotificationContext] ❌ socket.subscribeToEvents 方法不可用');
|
||||
}
|
||||
});
|
||||
|
||||
// ========== 监听断开连接 ==========
|
||||
socket.on('disconnect', (reason) => {
|
||||
setIsConnected(false);
|
||||
setConnectionStatus(CONNECTION_STATUS.DISCONNECTED);
|
||||
logger.warn('NotificationContext', 'Socket disconnected', { reason });
|
||||
console.log('%c[NotificationContext] ⚠️ Socket 已断开', 'color: #FF5722;', { reason });
|
||||
});
|
||||
|
||||
// ========== 监听连接错误 ==========
|
||||
// 监听连接错误
|
||||
socket.on('connect_error', (error) => {
|
||||
logger.error('NotificationContext', 'Socket connect_error', error);
|
||||
setConnectionStatus(CONNECTION_STATUS.RECONNECTING);
|
||||
|
||||
// 获取重连次数
|
||||
const attempts = socket.getReconnectAttempts?.() || 0;
|
||||
setReconnectAttempt(attempts);
|
||||
logger.info('NotificationContext', 'Reconnection attempt', { attempts });
|
||||
console.log(`%c[NotificationContext] 🔄 重连中... (第 ${attempts} 次尝试)`, 'color: #FF9800;');
|
||||
});
|
||||
|
||||
// ========== 监听重连失败 ==========
|
||||
// 监听重连失败
|
||||
socket.on('reconnect_failed', () => {
|
||||
logger.error('NotificationContext', 'Socket reconnect_failed');
|
||||
setConnectionStatus(CONNECTION_STATUS.FAILED);
|
||||
console.error('[NotificationContext] ❌ 重连失败');
|
||||
|
||||
toast({
|
||||
title: '连接失败',
|
||||
description: '无法连接到服务器,请检查网络连接',
|
||||
status: 'error',
|
||||
duration: null,
|
||||
duration: null, // 不自动关闭
|
||||
isClosable: true,
|
||||
});
|
||||
});
|
||||
|
||||
// ========== 监听新事件推送(⚡ 只注册一次,使用 ref 访问最新函数) ==========
|
||||
// 监听新事件推送(统一事件名)
|
||||
socket.on('new_event', (data) => {
|
||||
console.log('\n%c════════════════════════════════════════', 'color: #FF9800; font-weight: bold;');
|
||||
console.log('%c[NotificationContext] 📨 收到 new_event 事件!', 'color: #FF9800; font-weight: bold;');
|
||||
@@ -714,24 +693,17 @@ export const NotificationProvider = ({ children }) => {
|
||||
|
||||
logger.info('NotificationContext', 'Received new event', data);
|
||||
|
||||
// ⚠️ 防御性检查:确保 ref 已初始化
|
||||
if (!addNotificationRef.current || !adaptEventToNotificationRef.current) {
|
||||
console.error('%c[NotificationContext] ❌ Ref 未初始化,跳过处理', 'color: #F44336; font-weight: bold;');
|
||||
logger.error('NotificationContext', 'Refs not initialized', {
|
||||
addNotificationRef: !!addNotificationRef.current,
|
||||
adaptEventToNotificationRef: !!adaptEventToNotificationRef.current,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// ========== Socket层去重检查 ==========
|
||||
const eventId = data.id || `${data.type || 'unknown'}_${data.publishTime || Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
// 生成更健壮的事件ID
|
||||
const eventId = data.id ||
|
||||
`${data.type || 'unknown'}_${data.publishTime || Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
|
||||
// 如果缺少原始ID,记录警告
|
||||
if (!data.id) {
|
||||
logger.warn('NotificationContext', 'Event missing ID, generated fallback', {
|
||||
eventId,
|
||||
eventType: data.type,
|
||||
title: data.title,
|
||||
title: data.title
|
||||
});
|
||||
}
|
||||
|
||||
@@ -739,61 +711,55 @@ export const NotificationProvider = ({ children }) => {
|
||||
logger.debug('NotificationContext', 'Duplicate event ignored at socket level', { eventId });
|
||||
console.warn('[NotificationContext] ⚠️ 重复事件,已忽略:', eventId);
|
||||
console.log('%c════════════════════════════════════════\n', 'color: #FF9800; font-weight: bold;');
|
||||
return;
|
||||
return; // 重复事件,直接忽略
|
||||
}
|
||||
|
||||
// 记录已处理的事件ID
|
||||
processedEventIds.current.add(eventId);
|
||||
console.log('[NotificationContext] ✓ 事件已记录,防止重复处理');
|
||||
|
||||
// 限制 Set 大小,避免内存泄漏
|
||||
// 限制Set大小,避免内存泄漏
|
||||
if (processedEventIds.current.size > MAX_PROCESSED_IDS) {
|
||||
const idsArray = Array.from(processedEventIds.current);
|
||||
processedEventIds.current = new Set(idsArray.slice(-MAX_PROCESSED_IDS));
|
||||
logger.debug('NotificationContext', 'Cleaned up old processed event IDs', {
|
||||
kept: MAX_PROCESSED_IDS,
|
||||
kept: MAX_PROCESSED_IDS
|
||||
});
|
||||
}
|
||||
// ========== Socket层去重检查结束 ==========
|
||||
|
||||
// ✅ 使用 ref.current 访问最新的适配器函数(避免闭包陷阱)
|
||||
// 使用适配器转换事件格式
|
||||
console.log('[NotificationContext] 正在转换事件格式...');
|
||||
const notification = adaptEventToNotificationRef.current(data);
|
||||
const notification = adaptEventToNotification(data);
|
||||
console.log('[NotificationContext] 转换后的通知对象:', notification);
|
||||
|
||||
// ✅ 使用 ref.current 访问最新的 addNotification 函数
|
||||
console.log('[NotificationContext] 准备添加通知到队列...');
|
||||
addNotificationRef.current(notification);
|
||||
addNotification(notification);
|
||||
console.log('[NotificationContext] ✅ 通知已添加到队列');
|
||||
console.log('%c════════════════════════════════════════\n', 'color: #FF9800; font-weight: bold;');
|
||||
});
|
||||
|
||||
// ========== 监听系统通知(兼容性) ==========
|
||||
// 保留系统通知监听(兼容性)
|
||||
socket.on('system_notification', (data) => {
|
||||
logger.info('NotificationContext', 'Received system notification', data);
|
||||
console.log('[NotificationContext] 📢 收到系统通知:', data);
|
||||
|
||||
if (addNotificationRef.current) {
|
||||
addNotificationRef.current(data);
|
||||
} else {
|
||||
console.error('[NotificationContext] ❌ addNotificationRef 未初始化');
|
||||
}
|
||||
addNotification(data);
|
||||
});
|
||||
|
||||
console.log('%c[NotificationContext] ✅ 所有监听器已注册(只注册一次)', 'color: #4CAF50; font-weight: bold;');
|
||||
console.log('%c[NotificationContext] ✅ All event listeners registered', 'color: #4CAF50; font-weight: bold;');
|
||||
|
||||
// ========== 获取最大重连次数 ==========
|
||||
// ✅ 第二步: 获取最大重连次数
|
||||
const maxAttempts = socket.getMaxReconnectAttempts?.() || Infinity;
|
||||
setMaxReconnectAttempts(maxAttempts);
|
||||
logger.info('NotificationContext', 'Max reconnect attempts', { maxAttempts });
|
||||
|
||||
// ========== 启动连接 ==========
|
||||
console.log('%c[NotificationContext] 🔌 调用 socket.connect()...', 'color: #673AB7; font-weight: bold;');
|
||||
// ✅ 第三步: 调用 socket.connect()
|
||||
console.log('%c[NotificationContext] Step 2: Calling socket.connect()...', 'color: #673AB7; font-weight: bold;');
|
||||
socket.connect();
|
||||
console.log('%c[NotificationContext] socket.connect() completed', 'color: #673AB7;');
|
||||
|
||||
// ========== 清理函数(组件卸载时) ==========
|
||||
// 清理函数
|
||||
return () => {
|
||||
logger.info('NotificationContext', 'Cleaning up socket connection');
|
||||
console.log('%c[NotificationContext] 🧹 清理 Socket 连接', 'color: #9E9E9E;');
|
||||
|
||||
// 清理 reconnected 状态定时器
|
||||
if (reconnectedTimerRef.current) {
|
||||
@@ -808,20 +774,15 @@ export const NotificationProvider = ({ children }) => {
|
||||
});
|
||||
notificationTimers.current.clear();
|
||||
|
||||
// 移除所有事件监听器
|
||||
socket.off('connect');
|
||||
socket.off('disconnect');
|
||||
socket.off('connect_error');
|
||||
socket.off('reconnect_failed');
|
||||
socket.off('new_event');
|
||||
socket.off('system_notification');
|
||||
|
||||
// 断开连接
|
||||
socket.disconnect();
|
||||
|
||||
console.log('%c[NotificationContext] ✅ 清理完成', 'color: #4CAF50;');
|
||||
};
|
||||
}, []); // ⚠️ 空依赖数组,确保只执行一次
|
||||
}, []); // ✅ 空依赖数组,确保只执行一次,避免 React 严格模式重复执行
|
||||
|
||||
// ==================== 智能自动重试 ====================
|
||||
|
||||
@@ -935,92 +896,6 @@ export const NotificationProvider = ({ children }) => {
|
||||
};
|
||||
}, [browserPermission, toast]);
|
||||
|
||||
// 🔧 开发环境调试:暴露方法到 window
|
||||
useEffect(() => {
|
||||
if (process.env.NODE_ENV === 'development' || process.env.REACT_APP_ENABLE_DEBUG === 'true') {
|
||||
if (typeof window !== 'undefined') {
|
||||
window.__TEST_NOTIFICATION__ = {
|
||||
// 手动触发网页通知
|
||||
testWebNotification: (type = 'event_alert', priority = 'normal') => {
|
||||
console.log('%c[Debug] 手动触发网页通知', 'color: #FF9800; font-weight: bold;');
|
||||
|
||||
const testData = {
|
||||
id: `test_${Date.now()}`,
|
||||
type: type,
|
||||
priority: priority,
|
||||
title: '🧪 测试网页通知',
|
||||
content: `这是一条测试${type === 'announcement' ? '公告' : type === 'stock_alert' ? '股票' : type === 'event_alert' ? '事件' : '分析'}通知 (优先级: ${priority})`,
|
||||
timestamp: Date.now(),
|
||||
clickable: true,
|
||||
link: '/home',
|
||||
};
|
||||
|
||||
console.log('测试数据:', testData);
|
||||
addNotification(testData);
|
||||
console.log('✅ 通知已添加到队列');
|
||||
},
|
||||
|
||||
// 测试所有类型
|
||||
testAllTypes: () => {
|
||||
console.log('%c[Debug] 测试所有通知类型', 'color: #FF9800; font-weight: bold;');
|
||||
const types = ['announcement', 'stock_alert', 'event_alert', 'analysis_report'];
|
||||
types.forEach((type, i) => {
|
||||
setTimeout(() => {
|
||||
window.__TEST_NOTIFICATION__.testWebNotification(type, 'normal');
|
||||
}, i * 2000); // 每 2 秒一个
|
||||
});
|
||||
},
|
||||
|
||||
// 测试所有优先级
|
||||
testAllPriorities: () => {
|
||||
console.log('%c[Debug] 测试所有优先级', 'color: #FF9800; font-weight: bold;');
|
||||
const priorities = ['normal', 'important', 'urgent'];
|
||||
priorities.forEach((priority, i) => {
|
||||
setTimeout(() => {
|
||||
window.__TEST_NOTIFICATION__.testWebNotification('event_alert', priority);
|
||||
}, i * 2000);
|
||||
});
|
||||
},
|
||||
|
||||
// 帮助
|
||||
help: () => {
|
||||
console.log('\n%c=== 网页通知测试 API ===', 'color: #FF9800; font-weight: bold; font-size: 16px;');
|
||||
console.log('\n%c基础用法:', 'color: #2196F3; font-weight: bold;');
|
||||
console.log(' window.__TEST_NOTIFICATION__.testWebNotification(type, priority)');
|
||||
console.log('\n%c参数说明:', 'color: #2196F3; font-weight: bold;');
|
||||
console.log(' type (通知类型):');
|
||||
console.log(' - "announcement" 公告通知(蓝色)');
|
||||
console.log(' - "stock_alert" 股票动向(红色/绿色)');
|
||||
console.log(' - "event_alert" 事件动向(橙色)');
|
||||
console.log(' - "analysis_report" 分析报告(紫色)');
|
||||
console.log('\n priority (优先级):');
|
||||
console.log(' - "normal" 普通(15秒自动关闭)');
|
||||
console.log(' - "important" 重要(30秒自动关闭)');
|
||||
console.log(' - "urgent" 紧急(不自动关闭)');
|
||||
console.log('\n%c示例:', 'color: #4CAF50; font-weight: bold;');
|
||||
console.log(' // 测试紧急事件通知');
|
||||
console.log(' window.__TEST_NOTIFICATION__.testWebNotification("event_alert", "urgent")');
|
||||
console.log('\n // 测试所有类型');
|
||||
console.log(' window.__TEST_NOTIFICATION__.testAllTypes()');
|
||||
console.log('\n // 测试所有优先级');
|
||||
console.log(' window.__TEST_NOTIFICATION__.testAllPriorities()');
|
||||
console.log('\n');
|
||||
}
|
||||
};
|
||||
|
||||
console.log('[NotificationContext] 🔧 调试 API 已加载: window.__TEST_NOTIFICATION__');
|
||||
console.log('[NotificationContext] 💡 使用 window.__TEST_NOTIFICATION__.help() 查看帮助');
|
||||
}
|
||||
}
|
||||
|
||||
// 清理函数
|
||||
return () => {
|
||||
if (typeof window !== 'undefined' && window.__TEST_NOTIFICATION__) {
|
||||
delete window.__TEST_NOTIFICATION__;
|
||||
}
|
||||
};
|
||||
}, [addNotification]); // 依赖 addNotification 函数
|
||||
|
||||
const value = {
|
||||
notifications,
|
||||
isConnected,
|
||||
|
||||
@@ -71,10 +71,7 @@ class DebugToolkit {
|
||||
console.log('');
|
||||
console.log('%c2️⃣ 通知调试:', 'color: #9C27B0; font-weight: bold;');
|
||||
console.log(' __DEBUG__.notification.getLogs() - 获取所有通知日志');
|
||||
console.log(' __DEBUG__.notification.forceNotification() - 发送测试浏览器通知');
|
||||
console.log(' __DEBUG__.notification.testWebNotification(type, priority) - 测试网页通知 🆕');
|
||||
console.log(' __DEBUG__.notification.testAllNotificationTypes() - 测试所有类型 🆕');
|
||||
console.log(' __DEBUG__.notification.testAllNotificationPriorities() - 测试所有优先级 🆕');
|
||||
console.log(' __DEBUG__.notification.forceNotification() - 发送测试通知');
|
||||
console.log(' __DEBUG__.notification.checkPermission() - 检查通知权限');
|
||||
console.log(' __DEBUG__.notification.exportLogs() - 导出通知日志');
|
||||
console.log('');
|
||||
|
||||
@@ -159,44 +159,6 @@ class NotificationDebugger {
|
||||
getRecentEvents(count = 10) {
|
||||
return this.eventLog.slice(0, count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试网页通知(需要 window.__TEST_NOTIFICATION__ 可用)
|
||||
*/
|
||||
testWebNotification(type = 'event_alert', priority = 'normal') {
|
||||
if (typeof window !== 'undefined' && window.__TEST_NOTIFICATION__) {
|
||||
console.log('[Notification Debugger] 调用测试 API');
|
||||
window.__TEST_NOTIFICATION__.testWebNotification(type, priority);
|
||||
} else {
|
||||
console.error('[Notification Debugger] ❌ window.__TEST_NOTIFICATION__ 不可用');
|
||||
console.error('💡 请确保:');
|
||||
console.error(' 1. REACT_APP_ENABLE_DEBUG=true');
|
||||
console.error(' 2. NotificationContext 已加载');
|
||||
console.error(' 3. 页面已刷新');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试所有通知类型
|
||||
*/
|
||||
testAllNotificationTypes() {
|
||||
if (typeof window !== 'undefined' && window.__TEST_NOTIFICATION__) {
|
||||
window.__TEST_NOTIFICATION__.testAllTypes();
|
||||
} else {
|
||||
console.error('[Notification Debugger] ❌ window.__TEST_NOTIFICATION__ 不可用');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试所有优先级
|
||||
*/
|
||||
testAllNotificationPriorities() {
|
||||
if (typeof window !== 'undefined' && window.__TEST_NOTIFICATION__) {
|
||||
window.__TEST_NOTIFICATION__.testAllPriorities();
|
||||
} else {
|
||||
console.error('[Notification Debugger] ❌ window.__TEST_NOTIFICATION__ 不可用');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 导出单例
|
||||
|
||||
50
src/index.js
50
src/index.js
@@ -44,64 +44,24 @@ function registerServiceWorker() {
|
||||
navigator.serviceWorker
|
||||
.register('/service-worker.js')
|
||||
.then((registration) => {
|
||||
console.log('[App] ✅ Service Worker 注册成功');
|
||||
console.log('[App] Scope:', registration.scope);
|
||||
console.log('[App] Service Worker registered successfully:', registration.scope);
|
||||
|
||||
// 检查当前激活状态
|
||||
if (navigator.serviceWorker.controller) {
|
||||
console.log('[App] ✅ Service Worker 已激活并控制页面');
|
||||
} else {
|
||||
console.log('[App] ⏳ Service Worker 已注册,等待激活...');
|
||||
console.log('[App] 💡 刷新页面以激活 Service Worker');
|
||||
|
||||
// 监听 controller 变化(Service Worker 激活后触发)
|
||||
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
||||
console.log('[App] ✅ Service Worker 控制器已更新');
|
||||
});
|
||||
}
|
||||
|
||||
// 监听 Service Worker 更新
|
||||
// 监听更新
|
||||
registration.addEventListener('updatefound', () => {
|
||||
const newWorker = registration.installing;
|
||||
console.log('[App] 🔄 发现 Service Worker 更新');
|
||||
console.log('[App] Service Worker update found');
|
||||
|
||||
if (newWorker) {
|
||||
newWorker.addEventListener('statechange', () => {
|
||||
console.log(`[App] Service Worker 状态: ${newWorker.state}`);
|
||||
if (newWorker.state === 'activated') {
|
||||
console.log('[App] ✅ Service Worker 已激活');
|
||||
|
||||
// 如果有旧的 Service Worker 在控制页面,提示用户刷新
|
||||
if (navigator.serviceWorker.controller) {
|
||||
console.log('[App] 💡 Service Worker 已更新,建议刷新页面');
|
||||
}
|
||||
console.log('[App] Service Worker activated');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('[App] ❌ Service Worker 注册失败');
|
||||
console.error('[App] 错误类型:', error.name);
|
||||
console.error('[App] 错误信息:', error.message);
|
||||
console.error('[App] 完整错误:', error);
|
||||
|
||||
// 额外检查:验证文件是否可访问
|
||||
fetch('/service-worker.js', { method: 'HEAD' })
|
||||
.then(response => {
|
||||
if (response.ok) {
|
||||
console.error('[App] Service Worker 文件存在但注册失败');
|
||||
console.error('[App] 💡 可能的原因:');
|
||||
console.error('[App] 1. Service Worker 文件有语法错误');
|
||||
console.error('[App] 2. 浏览器不支持某些 Service Worker 特性');
|
||||
console.error('[App] 3. HTTPS 证书问题(Service Worker 需要 HTTPS)');
|
||||
} else {
|
||||
console.error('[App] Service Worker 文件不存在(HTTP', response.status, ')');
|
||||
}
|
||||
})
|
||||
.catch(fetchError => {
|
||||
console.error('[App] 无法访问 Service Worker 文件:', fetchError.message);
|
||||
});
|
||||
console.error('[App] Service Worker registration failed:', error);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -10,21 +10,6 @@ import { socketService } from '../socketService';
|
||||
export const socket = socketService;
|
||||
export { socketService };
|
||||
|
||||
// ⚡ 新增:暴露 Socket 实例到 window(用于调试和验证)
|
||||
if (typeof window !== 'undefined') {
|
||||
window.socket = socketService;
|
||||
window.socketService = socketService;
|
||||
|
||||
console.log(
|
||||
'%c[Socket Service] ✅ Socket instance exposed to window',
|
||||
'color: #4CAF50; font-weight: bold; font-size: 14px;'
|
||||
);
|
||||
console.log(' 📍 window.socket:', window.socket);
|
||||
console.log(' 📍 window.socketService:', window.socketService);
|
||||
console.log(' 📍 Socket.IO instance:', window.socket?.socket);
|
||||
console.log(' 📍 Connection status:', window.socket?.connected ? '✅ Connected' : '❌ Disconnected');
|
||||
}
|
||||
|
||||
// 打印当前使用的服务类型
|
||||
console.log(
|
||||
'%c[Socket Service] Using REAL Socket Service',
|
||||
|
||||
@@ -51,21 +51,13 @@ class SocketService {
|
||||
...options,
|
||||
});
|
||||
|
||||
// 注册所有暂存的事件监听器(保留 pendingListeners,不清空)
|
||||
// 注册所有暂存的事件监听器
|
||||
if (this.pendingListeners.length > 0) {
|
||||
console.log(`[socketService] 📦 注册 ${this.pendingListeners.length} 个暂存的事件监听器`);
|
||||
this.pendingListeners.forEach(({ event, callback }) => {
|
||||
// 直接在 Socket.IO 实例上注册(避免递归调用 this.on())
|
||||
const wrappedCallback = (...args) => {
|
||||
console.log(`%c[socketService] 🔔 收到原始事件: ${event}`, 'color: #2196F3; font-weight: bold;');
|
||||
console.log(`[socketService] 事件数据 (${event}):`, ...args);
|
||||
callback(...args);
|
||||
};
|
||||
|
||||
this.socket.on(event, wrappedCallback);
|
||||
console.log(`[socketService] ✓ 已注册事件监听器: ${event}`);
|
||||
this.on(event, callback);
|
||||
});
|
||||
// ⚠️ 重要:不清空 pendingListeners,保留用于重连
|
||||
this.pendingListeners = []; // 清空暂存队列
|
||||
}
|
||||
|
||||
// 监听连接成功
|
||||
@@ -165,18 +157,10 @@ class SocketService {
|
||||
*/
|
||||
on(event, callback) {
|
||||
if (!this.socket) {
|
||||
// Socket 未初始化,暂存监听器(检查是否已存在,避免重复)
|
||||
const exists = this.pendingListeners.some(
|
||||
(listener) => listener.event === event && listener.callback === callback
|
||||
);
|
||||
|
||||
if (!exists) {
|
||||
logger.info('socketService', 'Socket not ready, queuing listener', { event });
|
||||
console.log(`[socketService] 📦 Socket 未初始化,暂存事件监听器: ${event}`);
|
||||
this.pendingListeners.push({ event, callback });
|
||||
} else {
|
||||
console.log(`[socketService] ⚠️ 监听器已存在,跳过: ${event}`);
|
||||
}
|
||||
// Socket 未初始化,暂存监听器
|
||||
logger.info('socketService', 'Socket not ready, queuing listener', { event });
|
||||
console.log(`[socketService] 📦 Socket 未初始化,暂存事件监听器: ${event}`);
|
||||
this.pendingListeners.push({ event, callback });
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user