【m】两页面合并

This commit is contained in:
2026-05-16 21:26:19 +08:00
parent d7264b9102
commit 71efb34795
5 changed files with 597 additions and 147 deletions

View File

@@ -3,112 +3,13 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VideoCall - 连接界面</title> <title>VideoCall - 重定向</title>
<script src="https://cdn.tailwindcss.com"></script> <script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet"> // 重定向到SPA入口页面index.html
<link rel="stylesheet" href="../css/style.css"> window.location.href = '../index.html';
</script>
</head> </head>
<body class="h-screen w-screen flex flex-col text-white bg-grid relative"> <body>
<!-- 用户设置区域 --> <p>正在跳转到视频通话界面...</p>
<div class="absolute top-4 right-4 z-10">
<button id="userSettingsBtn" class="flex items-center gap-2 glass px-3 py-2 rounded-full hover:bg-white/10 transition-colors">
<img id="userAvatar" src="/images/p1.png" class="w-8 h-8 rounded-full object-cover">
<span id="userName" class="text-sm font-medium"></span>
<i class="fas fa-chevron-down text-xs text-gray-400"></i>
</button>
<!-- 设置菜单 -->
<div id="settingsMenu" class="hidden absolute top-full right-0 mt-2 glass rounded-xl shadow-lg w-48 z-20">
<div class="p-4 border-b border-white/10">
<h3 class="text-sm font-medium mb-2">个人设置</h3>
<div class="space-y-3">
<div>
<label class="block text-xs text-gray-400 mb-1">昵称</label>
<input type="text" id="nicknameInput" class="w-full bg-transparent border border-white/20 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500" placeholder="输入昵称">
</div>
<div>
<label class="block text-xs text-gray-400 mb-1">头像</label>
<div class="flex items-center gap-3">
<img id="avatarPreview" src="/images/p1.png" class="w-10 h-10 rounded-full object-cover">
<input type="file" id="avatarInput" accept="image/*" class="hidden" onchange="handleAvatarUpload(event)">
<button onclick="document.getElementById('avatarInput').click()" class="text-xs text-indigo-400 hover:text-indigo-300 transition-colors">更换头像</button>
</div>
</div>
<div>
<label class="block text-xs text-gray-400 mb-1">用户ID</label>
<div class="flex items-center gap-2">
<input type="text" id="userIdInput" class="w-full bg-transparent border border-white/20 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500" readonly>
<button onclick="copyUserId()" class="text-xs text-indigo-400 hover:text-indigo-300 transition-colors">复制</button>
</div>
</div>
</div>
</div>
<div class="p-2">
<button onclick="saveSettings()" class="w-full px-4 py-2 text-sm text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg transition-colors">保存设置</button>
</div>
</div>
</div>
<!--
============================================================
初始连接界面
============================================================
-->
<div class="h-full w-full flex items-center justify-center bg-black/90">
<div class="text-center max-w-md px-8">
<div class="w-24 h-24 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-full flex items-center justify-center mx-auto mb-8 shadow-lg">
<i class="fas fa-video text-white text-4xl"></i>
</div>
<h1 class="text-3xl font-bold text-white mb-2">VideoCall</h1>
<p class="text-gray-400 mb-8">一对一视频通话</p>
<div class="space-y-4 mb-8">
<div class="glass rounded-xl p-4">
<label class="block text-sm font-medium text-gray-300 mb-2">连接ID</label>
<input type="text"
id="connectionIdInput"
placeholder="输入连接ID"
class="w-full bg-transparent border border-white/20 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
autocomplete="off">
</div>
<p class="text-xs text-gray-500">
连接ID是用于建立点对点通话的唯一标识由发起方生成并分享给接收方。
</p>
</div>
<div class="flex flex-col sm:flex-row gap-4 justify-center mb-6">
<button id="connectBtn" class="flex-1 px-6 py-3 bg-indigo-600 hover:bg-indigo-700 rounded-xl transition-colors flex items-center justify-center gap-2">
<i class="fas fa-phone"></i>
<span>加入通话</span>
</button>
<button id="createCallBtn" class="flex-1 px-6 py-3 glass hover:bg-white/10 rounded-xl transition-colors flex items-center justify-center gap-2">
<i class="fas fa-plus"></i>
<span>创建通话</span>
</button>
</div>
<!-- 浏览全部ID按钮 -->
<button id="browseIdsBtn" class="w-full px-6 py-3 glass hover:bg-white/10 rounded-xl transition-colors flex items-center justify-center gap-2 mb-4">
<i class="fas fa-list"></i>
<span>浏览全部ID</span>
</button>
<!-- 连接ID列表 -->
<div id="connectionIdsList" class="glass rounded-xl p-4 mb-6 hidden">
<h3 class="text-sm font-medium text-gray-300 mb-2">可用的连接ID</h3>
<div id="idsContainer" class="max-h-40 overflow-y-auto space-y-2">
<!-- 连接ID将在这里动态生成 -->
</div>
</div>
</div>
</div>
<!-- 通知组件 -->
<div id="notification" class="fixed top-20 left-1/2 transform -translate-x-1/2 glass px-6 py-3 rounded-full flex items-center gap-3 opacity-0 pointer-events-none transition-all duration-300 z-50 translate-y-[-20px]">
<i class="fas fa-info-circle text-indigo-400"></i>
<span class="text-sm" id="notificationText">通知内容</span>
</div>
<!-- 引入模块化JavaScript文件 -->
<script type="module" src="connect.js"></script>
</body> </body>
</html> </html>

View File

@@ -0,0 +1,359 @@
/**
* connect视图逻辑
* 处理初始连接界面的UI、用户设置、WebSocket连接状态显示
*/
import { showNotification } from './utils.js';
import store from './store.js';
const MAX_AVATAR_SIZE = 2 * 1024 * 1024; // 2MB
// WebSocket连接状态更新回调
let onWsStatusChange = null;
/**
* 设置WebSocket状态变化回调
* @param {function} callback - 回调函数(connected: boolean)
*/
export function setWsStatusCallback(callback) {
onWsStatusChange = callback;
}
/**
* 更新WebSocket状态显示
* @param {boolean} connected - 是否已连接
*/
export function updateWsStatus(connected) {
const wsStatusDot = document.getElementById('wsStatusDot');
const wsStatusText = document.getElementById('wsStatusText');
if (wsStatusDot && wsStatusText) {
if (connected) {
wsStatusDot.className = 'w-2 h-2 bg-green-500 rounded-full animate-pulse';
wsStatusText.textContent = 'WebSocket已连接';
} else {
wsStatusDot.className = 'w-2 h-2 bg-gray-500 rounded-full';
wsStatusText.textContent = '未连接';
}
}
if (onWsStatusChange) {
onWsStatusChange(connected);
}
}
/**
* 初始化WebSocket连接页面加载时调用
*/
export async function initWebSocket() {
try {
await store.connectSignaling();
updateWsStatus(true);
console.log('WebSocket initialized from connectview');
} catch (error) {
console.error('Failed to initialize WebSocket:', error);
updateWsStatus(false);
showNotification('WebSocket连接失败请刷新页面重试', 'error');
}
}
/**
* 获取所有连接ID
*/
async function getAllConnectionIds() {
showNotification('正在获取连接ID列表...');
try {
const response = await fetch('/signaling/connection-ids');
if (!response.ok) {
throw new Error('Failed to fetch connection IDs');
}
const data = await response.json();
displayConnectionIds(data.connectionIds);
} catch (error) {
console.error('Error fetching connection IDs:', error);
showNotification('获取连接ID失败', 'error');
}
}
/**
* 显示连接ID列表
* @param {string[]} connectionIds - 连接ID数组
*/
function displayConnectionIds(connectionIds) {
const idsContainer = document.getElementById('idsContainer');
const connectionIdsList = document.getElementById('connectionIdsList');
if (idsContainer) {
idsContainer.innerHTML = '';
if (connectionIds.length === 0) {
idsContainer.innerHTML = '<p class="text-gray-500 text-sm">暂无可用的连接ID</p>';
} else {
connectionIds.forEach(id => {
const idElement = document.createElement('div');
idElement.className = 'flex items-center justify-between p-2 bg-white/5 rounded-lg hover:bg-white/10 cursor-pointer transition-colors';
idElement.innerHTML = `
<span class="text-sm">${id}</span>
<button class="text-xs bg-indigo-600 hover:bg-indigo-700 px-2 py-1 rounded" onclick="selectConnectionId('${id}')">选择</button>
`;
idsContainer.appendChild(idElement);
});
}
if (connectionIdsList) {
connectionIdsList.classList.remove('hidden');
}
showNotification(`找到 ${connectionIds.length} 个连接ID`);
}
}
/**
* 选择连接ID
* @param {string} id - 连接ID
*/
function selectConnectionId(id) {
const connectionIdInput = document.getElementById('connectionIdInput');
if (connectionIdInput) {
connectionIdInput.value = id;
showNotification(`已选择连接ID: ${id}`);
}
}
/**
* 生成8位用户ID
* @returns {string} 用户ID
*/
function generateUserId() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = 'user_';
for (let i = 0; i < 8; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
/**
* 加载用户设置
*/
export function loadUserSettings() {
const defaultAvatar = '/images/p1.png';
const userSettings = localStorage.getItem('userSettings');
if (userSettings) {
try {
const settings = JSON.parse(userSettings);
if (settings.userId) {
const userIdInput = document.getElementById('userIdInput');
if (userIdInput) userIdInput.value = settings.userId;
}
if (settings.name) {
const nicknameInput = document.getElementById('nicknameInput');
const userName = document.getElementById('userName');
if (nicknameInput) nicknameInput.value = settings.name;
if (userName) userName.textContent = settings.name;
}
const avatar = settings.avatar || defaultAvatar;
const userAvatar = document.getElementById('userAvatar');
const avatarPreview = document.getElementById('avatarPreview');
if (userAvatar) userAvatar.src = avatar;
if (avatarPreview) avatarPreview.src = avatar;
} catch (error) {
console.error('Error loading user settings:', error);
const userAvatar = document.getElementById('userAvatar');
const avatarPreview = document.getElementById('avatarPreview');
if (userAvatar) userAvatar.src = defaultAvatar;
if (avatarPreview) avatarPreview.src = defaultAvatar;
}
} else {
const newUserId = generateUserId();
const userIdInput = document.getElementById('userIdInput');
if (userIdInput) userIdInput.value = newUserId;
const userAvatar = document.getElementById('userAvatar');
const avatarPreview = document.getElementById('avatarPreview');
if (userAvatar) userAvatar.src = defaultAvatar;
if (avatarPreview) avatarPreview.src = defaultAvatar;
saveSettings();
}
}
/**
* 保存用户设置
*/
export function saveSettings() {
const defaultAvatar = '/images/p1.png';
const nicknameInput = document.getElementById('nicknameInput');
const userIdInput = document.getElementById('userIdInput');
const avatarPreview = document.getElementById('avatarPreview');
const userName = document.getElementById('userName');
const userAvatar = document.getElementById('userAvatar');
const settings = {
userId: userIdInput ? userIdInput.value : generateUserId(),
name: nicknameInput ? (nicknameInput.value || '我') : '我',
avatar: avatarPreview ? (avatarPreview.src || defaultAvatar) : defaultAvatar
};
localStorage.setItem('userSettings', JSON.stringify(settings));
if (userName) userName.textContent = settings.name;
if (userAvatar) userAvatar.src = settings.avatar;
showNotification('设置已保存', 'success');
}
/**
* 处理头像上传
* @param {Event} event - 文件选择事件
*/
export function handleAvatarUpload(event) {
const file = event.target.files[0];
if (!file) return;
if (!file.type.startsWith('image/')) {
showNotification('请选择图片文件', 'error');
return;
}
if (file.size > MAX_AVATAR_SIZE) {
showNotification('图片大小不能超过2MB', 'error');
return;
}
const formData = new FormData();
formData.append('avatar', file);
const userIdInput = document.getElementById('userIdInput');
if (userIdInput) {
formData.append('userId', userIdInput.value);
}
showNotification('正在上传头像...');
fetch('/api/upload/avatar', {
method: 'POST',
body: formData
})
.then(response => {
if (!response.ok) throw new Error('上传失败');
return response.json();
})
.then(data => {
if (data.success && data.avatarUrl) {
const avatarUrl = data.avatarUrl;
const avatarPreview = document.getElementById('avatarPreview');
const userAvatar = document.getElementById('userAvatar');
if (avatarPreview) avatarPreview.src = avatarUrl;
if (userAvatar) userAvatar.src = avatarUrl;
saveSettings();
showNotification('头像上传成功', 'success');
} else {
throw new Error('上传失败:' + (data.message || '未知错误'));
}
})
.catch(error => {
console.error('Error uploading avatar:', error);
showNotification('头像上传失败,请重试', 'error');
const defaultAvatar = '/images/p1.png';
const avatarPreview = document.getElementById('avatarPreview');
if (avatarPreview) avatarPreview.src = defaultAvatar;
});
}
/**
* 复制用户ID到剪贴板
*/
export function copyUserId() {
const userIdInput = document.getElementById('userIdInput');
if (userIdInput) {
userIdInput.select();
document.execCommand('copy');
showNotification('用户ID已复制到剪贴板', 'success');
}
}
/**
* 切换设置菜单
*/
export function toggleSettingsMenu() {
const settingsMenu = document.getElementById('settingsMenu');
if (settingsMenu) {
settingsMenu.classList.toggle('hidden');
}
}
/**
* 绑定connect视图事件
* @param {function} onJoinCall - 加入通话回调(connectionId: string)
* @param {function} onCreateCall - 创建通话回调()
*/
export function bindConnectViewEvents(onJoinCall, onCreateCall) {
// 加入通话按钮
const connectBtn = document.getElementById('connectBtn');
if (connectBtn) {
connectBtn.addEventListener('click', () => {
const connectionIdInput = document.getElementById('connectionIdInput');
const connectionId = connectionIdInput ? connectionIdInput.value.trim() : '';
if (connectionId) {
onJoinCall(connectionId);
} else {
showNotification('请输入连接ID', 'error');
}
});
}
// 创建通话按钮
const createCallBtn = document.getElementById('createCallBtn');
if (createCallBtn) {
createCallBtn.addEventListener('click', onCreateCall);
}
// 浏览全部ID按钮
const browseIdsBtn = document.getElementById('browseIdsBtn');
if (browseIdsBtn) {
browseIdsBtn.addEventListener('click', getAllConnectionIds);
}
// 输入框回车事件
const connectionIdInput = document.getElementById('connectionIdInput');
if (connectionIdInput) {
connectionIdInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
const connectionId = connectionIdInput.value.trim();
if (connectionId) {
onJoinCall(connectionId);
} else {
showNotification('请输入连接ID', 'error');
}
}
});
}
// 用户设置按钮
const userSettingsBtn = document.getElementById('userSettingsBtn');
if (userSettingsBtn) {
userSettingsBtn.addEventListener('click', toggleSettingsMenu);
}
}
// 点击外部关闭设置菜单
document.addEventListener('click', function(event) {
const settingsMenu = document.getElementById('settingsMenu');
const userSettingsBtn = document.getElementById('userSettingsBtn');
if (settingsMenu && userSettingsBtn &&
!settingsMenu.contains(event.target) &&
!userSettingsBtn.contains(event.target)) {
settingsMenu.classList.add('hidden');
}
});
// 导出全局函数供HTML onclick使用
window.selectConnectionId = selectConnectionId;
window.saveSettings = saveSettings;
window.handleAvatarUpload = handleAvatarUpload;
window.copyUserId = copyUserId;
window.toggleSettingsMenu = toggleSettingsMenu;

View File

@@ -13,10 +13,114 @@
<body class="h-screen w-screen flex flex-col text-white bg-grid relative"> <body class="h-screen w-screen flex flex-col text-white bg-grid relative">
<!-- <!--
============================================================ ============================================================
注意:此文件为视频通话界面 connect视图初始连接界面输入连接ID、创建/加入通话)
初始连接界面请访问 connect.html WebSocket在此视图建立连接
============================================================ ============================================================
--> -->
<div id="connectView" class="h-full w-full flex flex-col">
<!-- 用户设置区域 -->
<div class="absolute top-4 right-4 z-10">
<button id="userSettingsBtn" class="flex items-center gap-2 glass px-3 py-2 rounded-full hover:bg-white/10 transition-colors">
<img id="userAvatar" src="/images/p1.png" class="w-8 h-8 rounded-full object-cover">
<span id="userName" class="text-sm font-medium"></span>
<i class="fas fa-chevron-down text-xs text-gray-400"></i>
</button>
<!-- 设置菜单 -->
<div id="settingsMenu" class="hidden absolute top-full right-0 mt-2 glass rounded-xl shadow-lg w-48 z-20">
<div class="p-4 border-b border-white/10">
<h3 class="text-sm font-medium mb-2">个人设置</h3>
<div class="space-y-3">
<div>
<label class="block text-xs text-gray-400 mb-1">昵称</label>
<input type="text" id="nicknameInput" class="w-full bg-transparent border border-white/20 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500" placeholder="输入昵称">
</div>
<div>
<label class="block text-xs text-gray-400 mb-1">头像</label>
<div class="flex items-center gap-3">
<img id="avatarPreview" src="/images/p1.png" class="w-10 h-10 rounded-full object-cover">
<input type="file" id="avatarInput" accept="image/*" class="hidden" onchange="handleAvatarUpload(event)">
<button onclick="document.getElementById('avatarInput').click()" class="text-xs text-indigo-400 hover:text-indigo-300 transition-colors">更换头像</button>
</div>
</div>
<div>
<label class="block text-xs text-gray-400 mb-1">用户ID</label>
<div class="flex items-center gap-2">
<input type="text" id="userIdInput" class="w-full bg-transparent border border-white/20 rounded-lg px-3 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500" readonly>
<button onclick="copyUserId()" class="text-xs text-indigo-400 hover:text-indigo-300 transition-colors">复制</button>
</div>
</div>
</div>
</div>
<div class="p-2">
<button onclick="saveSettings()" class="w-full px-4 py-2 text-sm text-white bg-indigo-600 hover:bg-indigo-700 rounded-lg transition-colors">保存设置</button>
</div>
</div>
</div>
<!-- 连接表单 -->
<div class="h-full w-full flex items-center justify-center bg-black/90">
<div class="text-center max-w-md px-8">
<div class="w-24 h-24 bg-gradient-to-br from-indigo-500 to-purple-600 rounded-full flex items-center justify-center mx-auto mb-8 shadow-lg">
<i class="fas fa-video text-white text-4xl"></i>
</div>
<h1 class="text-3xl font-bold text-white mb-2">VideoCall</h1>
<p class="text-gray-400 mb-8">一对一视频通话</p>
<div class="space-y-4 mb-8">
<div class="glass rounded-xl p-4">
<label class="block text-sm font-medium text-gray-300 mb-2">连接ID</label>
<input type="text"
id="connectionIdInput"
placeholder="输入连接ID"
class="w-full bg-transparent border border-white/20 rounded-lg px-4 py-3 text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500"
autocomplete="off">
</div>
<p class="text-xs text-gray-500">
连接ID是用于建立点对点通话的唯一标识由发起方生成并分享给接收方。
</p>
</div>
<div class="flex flex-col sm:flex-row gap-4 justify-center mb-6">
<button id="connectBtn" class="flex-1 px-6 py-3 bg-indigo-600 hover:bg-indigo-700 rounded-xl transition-colors flex items-center justify-center gap-2">
<i class="fas fa-phone"></i>
<span>加入通话</span>
</button>
<button id="createCallBtn" class="flex-1 px-6 py-3 glass hover:bg-white/10 rounded-xl transition-colors flex items-center justify-center gap-2">
<i class="fas fa-plus"></i>
<span>创建通话</span>
</button>
</div>
<!-- 浏览全部ID按钮 -->
<button id="browseIdsBtn" class="w-full px-6 py-3 glass hover:bg-white/10 rounded-xl transition-colors flex items-center justify-center gap-2 mb-4">
<i class="fas fa-list"></i>
<span>浏览全部ID</span>
</button>
<!-- 连接ID列表 -->
<div id="connectionIdsList" class="glass rounded-xl p-4 mb-6 hidden">
<h3 class="text-sm font-medium text-gray-300 mb-2">可用的连接ID</h3>
<div id="idsContainer" class="max-h-40 overflow-y-auto space-y-2">
<!-- 连接ID将在这里动态生成 -->
</div>
</div>
<!-- WebSocket连接状态指示 -->
<div id="wsStatus" class="mt-4 flex items-center justify-center gap-2 text-xs text-gray-500">
<span id="wsStatusDot" class="w-2 h-2 bg-gray-500 rounded-full"></span>
<span id="wsStatusText">未连接</span>
</div>
</div>
</div>
</div>
<!--
============================================================
call视图视频通话界面创建/加入房间后显示)
============================================================
-->
<div id="callView" class="hidden h-full w-full flex flex-col">
<!-- <!--
============================================================ ============================================================
@@ -543,6 +647,8 @@
</footer> </footer>
</div><!-- /callView -->
<!-- 通知组件 --> <!-- 通知组件 -->
<div id="notification" <div id="notification"
class="fixed top-20 left-1/2 transform -translate-x-1/2 glass px-6 py-3 rounded-full flex items-center gap-3 opacity-0 pointer-events-none transition-all duration-300 z-50 translate-y-[-20px]"> class="fixed top-20 left-1/2 transform -translate-x-1/2 glass px-6 py-3 rounded-full flex items-center gap-3 opacity-0 pointer-events-none transition-all duration-300 z-50 translate-y-[-20px]">
@@ -606,6 +712,7 @@
</div> </div>
<!-- 引入模块化JavaScript文件 --> <!-- 引入模块化JavaScript文件 -->
<script type="module" src="connectview.js"></script>
<script type="module" src="main.js"></script> <script type="module" src="main.js"></script>

View File

@@ -1,18 +1,82 @@
/** /**
* 主入口文件 * 主入口文件
* 初始化应用,连接各个模块 * 初始化应用,连接各个模块
* SPA架构connect视图和call视图在同一页面切换
*/ */
import store from './store.js'; import store from './store.js';
import UIRenderer from './renderer.js'; import UIRenderer from './renderer.js';
import { showNotification } from './utils.js'; import { showNotification } from './utils.js';
import chatMessage from './chatmessage.js'; import chatMessage from './chatmessage.js';
import {
bindConnectViewEvents,
initWebSocket,
loadUserSettings
} from './connectview.js';
// 全局变量 // 全局变量
let connectionId = ""; let connectionId = "";
// 当前视图状态:'connect' 或 'call'(可用于未来扩展)
let currentView = 'connect';
/** /**
* 绑定DOM事件 * 切换到call视图创建/加入通话后)
* @param {string} connectionId - 连接ID
*/ */
function bindDomEvents() { async function switchToCallView(connectionId) {
const connectView = document.getElementById('connectView');
const callView = document.getElementById('callView');
if (connectView) connectView.classList.add('hidden');
if (callView) callView.classList.remove('hidden');
currentView = 'call';
try {
// 初始化渲染器
const renderer = new UIRenderer(store);
// 加入通话
await store.joinCall(connectionId);
// 设置WebRTC连接
await store.setUp(connectionId);
renderer.renderHeaderTitle();
// 绑定DOM事件
bindCallViewDomEvents();
console.log('Video call app initialized successfully');
} catch (error) {
console.error('Error initializing app:', error);
showNotification('初始化失败,请刷新页面重试', 'error');
}
}
/**
* 处理加入通话
* @param {string} connectionId - 连接ID
*/
async function handleJoinCall(connectionId) {
showNotification(`正在加入通话 (${connectionId})`);
localStorage.setItem('connectionId', connectionId);
await switchToCallView(connectionId);
}
/**
* 处理创建通话
*/
async function handleCreateCall() {
showNotification('正在创建通话...');
const connectionId = 'conn_' + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
localStorage.setItem('connectionId', connectionId);
await switchToCallView(connectionId);
}
/**
* 绑定call视图DOM事件
*/
function bindCallViewDomEvents() {
// 切换侧边栏 // 切换侧边栏
window.toggleSidebar = function () { window.toggleSidebar = function () {
chatMessage.toggleSidebar(); chatMessage.toggleSidebar();
@@ -145,8 +209,10 @@ function bindDomEvents() {
}); });
// 绑定对话框事件 // 绑定对话框事件
document.getElementById('cancelEndCall').addEventListener('click', window.cancelEndCall); const cancelEndCall = document.getElementById('cancelEndCall');
document.getElementById('confirmEndCall').addEventListener('click', window.confirmEndCall); const confirmEndCall = document.getElementById('confirmEndCall');
if (cancelEndCall) cancelEndCall.addEventListener('click', window.cancelEndCall);
if (confirmEndCall) confirmEndCall.addEventListener('click', window.confirmEndCall);
// 更多选项按钮事件 // 更多选项按钮事件
const moreOptionsBtn = document.getElementById('moreOptionsBtn'); const moreOptionsBtn = document.getElementById('moreOptionsBtn');
@@ -166,47 +232,41 @@ function bindDomEvents() {
}); });
// 绑定通话请求对话框事件 // 绑定通话请求对话框事件
if (document.getElementById('rejectCall')) { const rejectCall = document.getElementById('rejectCall');
document.getElementById('rejectCall').addEventListener('click', window.rejectCall); const acceptCall = document.getElementById('acceptCall');
} if (rejectCall) rejectCall.addEventListener('click', window.rejectCall);
if (document.getElementById('acceptCall')) { if (acceptCall) acceptCall.addEventListener('click', window.acceptCall);
document.getElementById('acceptCall').addEventListener('click', window.acceptCall);
}
} }
// 页面加载完成后初始化SPA入口
// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', async () => { window.addEventListener('DOMContentLoaded', async () => {
try { try {
// 检查本地存储中是否有连接ID // 显示connect视图隐藏call视图
const connectionId = localStorage.getItem('connectionId'); const connectView = document.getElementById('connectView');
const callView = document.getElementById('callView');
if (connectView) connectView.classList.remove('hidden');
if (callView) callView.classList.add('hidden');
currentView = 'connect';
if (!connectionId) { // 加载用户设置
// 如果没有连接ID跳转到连接界面 loadUserSettings();
window.location.href = './connect/connect.html';
return; // 初始化WebSocket连接在connect视图就建立WebSocket
await initWebSocket();
// 绑定connect视图事件加入通话、创建通话等
bindConnectViewEvents(handleJoinCall, handleCreateCall);
// 检查是否有保存的连接ID填入输入框
const savedConnectionId = localStorage.getItem('connectionId');
if (savedConnectionId) {
const connectionIdInput = document.getElementById('connectionIdInput');
if (connectionIdInput) connectionIdInput.value = savedConnectionId;
} }
// 初始化 store console.log('SPA initialized, showing connect view');
//await store.init();
// 初始化渲染器
const renderer = new UIRenderer(store);
// 加入通话
await store.joinCall(connectionId);
// 设置WebRTC连接
await store.setUp(connectionId);
renderer.renderHeaderTitle();
// 绑定DOM事件
bindDomEvents();
console.log('Video call app initialized successfully');
} catch (error) { } catch (error) {
console.error('Error initializing app:', error); console.error('Error initializing SPA:', error);
showNotification('初始化失败,请刷新页面重试', 'error'); showNotification('初始化失败,请刷新页面重试', 'error');
} }
}); });

View File

@@ -321,6 +321,28 @@ class CallStateManager {
} }
/**
* 早期连接WebSocket信令在connect视图调用
* 仅建立WebSocket连接不创建/加入房间
* @async
* @returns {Promise<WebSocketSignaling|Signaling>} 信令实例
*/
async connectSignaling() {
// 先获取配置
await this.setupConfig();
if (this._signaling) {
console.log('Signaling already connected, reusing existing instance');
return this._signaling;
}
// 创建信令实例
this._signaling = this.useWebSocket ? new WebSocketSignaling() : new Signaling();
await this._signaling.start();
console.log('Signaling connected (WebSocket only, no room yet)');
return this._signaling;
}
/** /**
* 创建信令和RTC实例 * 创建信令和RTC实例
* @async * @async
@@ -349,10 +371,11 @@ class CallStateManager {
}); });
} }
// 创建信令实例 // 复用已有信令实例connectSignaling()已建立WebSocket或创建新实例
const signaling = this.useWebSocket ? new WebSocketSignaling() : new Signaling(); const signaling = this._signaling || (this.useWebSocket ? new WebSocketSignaling() : new Signaling());
const config = getRTCConfiguration(); // 获取RTC配置 const config = getRTCConfiguration(); // 获取RTC配置
this.renderstreaming = new RenderStreaming(signaling, config); this.renderstreaming = new RenderStreaming(signaling, config);
this._signaling = null; // RenderStreaming 已接管信令,清除引用
} }
/** /**