/** * 简化的 Viser 管理器 * 使用全局覆盖策略:iframe在全局容器中,通过absolute定位匹配目标容器 */ class ViserManagerSimple { constructor() { this.viserPort = null; this.sharedIframe = null; this.currentPlugin = null; this.isLoaded = false; this.plugins = new Map(); this.globalContainer = null; this.currentViewport = null; this.resizeObserver = null; this.currentResizeTarget = null; console.log('🔧 ViserManager 初始化完成 - 全局覆盖策略 (absolute定位)'); } detectBackendPort() { if (this.viserPort) { return this.viserPort; } // 从 URL 参数获取 const urlParams = new URLSearchParams(window.location.search); const backendParam = urlParams.get('backend'); if (backendParam) { this.viserPort = parseInt(backendParam); console.log(`🔍 从URL参数获取后端端口: ${this.viserPort}`); return this.viserPort; } // 从当前前端端口推断 const currentPort = parseInt(window.location.port) || 8080; this.viserPort = currentPort === 8084 ? 8082 : (currentPort === 8080 ? 8081 : currentPort + 1); console.log(`🔍 推断后端端口: ${this.viserPort}`); return this.viserPort; } async testPort(port) { // 快速端口测试 - 使用更轻量的方法 try { return new Promise((resolve) => { // 使用img标签测试,更快更轻量 const testImg = new Image(); let resolved = false; testImg.onload = () => { if (!resolved) { resolved = true; resolve(true); } }; testImg.onerror = () => { if (!resolved) { resolved = true; // 即使图片加载失败,只要有响应就说明端口可用 resolve(true); } }; // 快速超时 - 500ms setTimeout(() => { if (!resolved) { resolved = true; resolve(false); } }, 500); // 尝试加载一个小资源 testImg.src = `http://localhost:${port}/favicon.ico?t=${Date.now()}`; }); } catch (error) { return false; } } async findWorkingBackendPort() { // 自动查找可用的后端端口 // 首先尝试从URL参数或推断的端口 const initialPort = this.detectBackendPort(); console.log(`🔍 测试初始端口: ${initialPort}`); if (await this.testPort(initialPort)) { console.log(`✅ 端口 ${initialPort} 可用`); return initialPort; } // 如果初始端口不可用,尝试常用端口 const commonPorts = [8081, 8082, 8083, 8084]; console.log(`⚠️ 初始端口 ${initialPort} 不可用,尝试常用端口: ${commonPorts.join(', ')}`); for (const port of commonPorts) { // 注意:也要测试初始端口,因为iframe测试可能比直接检测更准确 if (await this.testPort(port)) { console.log(`✅ 找到可用端口: ${port}`); this.viserPort = port; return port; } } console.error(`❌ 无法找到可用的后端端口`); throw new Error('无法连接到Viser后端'); } async initializeSharedIframe() { if (this.sharedIframe && this.isLoaded) { return; } if (this.sharedIframe && !this.isLoaded) { // 等待加载完成 return new Promise((resolve) => { const checkLoaded = () => { if (this.isLoaded) { resolve(); } else { setTimeout(checkLoaded, 100); } }; checkLoaded(); }); } // 优先使用URL参数中的端口,这是最可靠的 let port = this.detectBackendPort(); console.log(`🎯 使用后端端口: ${port} (来源: URL参数或推断)`); // 跳过端口检测,直接使用配置的端口,加快启动速度 console.log(`🔄 初始化共享Viser iframe (端口: ${port})`); return new Promise((resolve, reject) => { this.sharedIframe = document.createElement('iframe'); this.sharedIframe.id = 'shared-viser-iframe'; this.sharedIframe.title = 'Viser 3D Visualization'; this.sharedIframe.style.cssText = ` width: 100%; height: 100%; border: none; background: #001122; display: block; `; // 尝试不同的加载检测策略 let isResolved = false; // 策略1: 传统的load事件 this.sharedIframe.addEventListener('load', () => { if (!isResolved) { this.isLoaded = true; isResolved = true; console.log(`✅ 共享Viser iframe已加载 (端口: ${port}) - load事件`); resolve(); } }); this.sharedIframe.addEventListener('error', (event) => { if (!isResolved) { isResolved = true; console.error(`❌ 共享Viser iframe加载失败 (端口: ${port})`, event); reject(new Error(`Viser连接失败,端口 ${port}`)); } }); // 策略2: 轮询检测iframe是否可访问 const pollForLoad = () => { try { // 检查iframe是否有内容 if (this.sharedIframe.contentDocument || this.sharedIframe.contentWindow) { if (!isResolved) { this.isLoaded = true; isResolved = true; console.log(`✅ 共享Viser iframe已加载 (端口: ${port}) - 轮询检测`); resolve(); return; } } } catch (e) { // CORS会导致访问异常,但这可能意味着iframe已经加载了外部内容 if (e.name === 'SecurityError' && !isResolved) { this.isLoaded = true; isResolved = true; console.log(`✅ 共享Viser iframe已加载 (端口: ${port}) - CORS检测`); resolve(); return; } } // 继续轮询 if (!isResolved) { setTimeout(pollForLoad, 200); } }; // 减少超时时间到2秒,加快响应 const timeoutId = setTimeout(() => { if (!isResolved) { isResolved = true; console.warn(`⏰ Viser iframe加载超时 (端口: ${port}),但继续使用`); // 超时后仍然继续,因为Viser可能仍在启动 this.isLoaded = true; resolve(); } }, 2000); // 设置src,这会触发加载 console.log(`🔗 设置iframe src: http://localhost:${port}`); this.sharedIframe.src = `http://localhost:${port}`; // 立即开始轮询,减少延迟 setTimeout(pollForLoad, 100); }); } registerPlugin(pluginId, pluginInstance) { this.plugins.set(pluginId, pluginInstance); console.log(`📝 插件 ${pluginId} 已注册到 ViserManager`); } unregisterPlugin(pluginId) { this.plugins.delete(pluginId); console.log(`🗑️ 插件 ${pluginId} 已从 ViserManager 注销`); } async attachToPlugin(pluginId, targetContainer, loadingElement) { try { console.log(`🔍 附加共享iframe到插件 ${pluginId}`); // 确保共享iframe已初始化 await this.initializeSharedIframe(); // 隐藏加载指示器 if (loadingElement) { loadingElement.style.display = 'none'; } if (!targetContainer) { console.error('⚠️ 目标容器不存在'); return false; } // 回到原来的全局覆盖策略,但使用absolute定位而不是fixed if (!this.globalContainer) { // 创建全局容器,但使用absolute定位 this.globalContainer = document.createElement('div'); this.globalContainer.id = 'viser-global-container'; this.globalContainer.style.cssText = ` position: absolute; width: 100%; height: 100%; pointer-events: none; z-index: -1; top: 0; left: 0; `; this.globalContainer.appendChild(this.sharedIframe); // 将全局容器添加到main-container const mainContainer = document.querySelector('.main-container') || document.body; // 确保主容器有relative定位(CSS中已设置,这里是保险) const computedStyle = window.getComputedStyle(mainContainer); if (computedStyle.position === 'static') { mainContainer.style.position = 'relative'; } mainContainer.appendChild(this.globalContainer); console.log(`🌍 创建了全局iframe容器,使用absolute定位`); } // 清空目标容器 Array.from(targetContainer.children).forEach(child => { if (child !== loadingElement) { child.remove(); } }); // 创建视口窗口 const viewportWindow = document.createElement('div'); viewportWindow.className = 'viser-viewport-window'; viewportWindow.style.cssText = ` width: 100%; height: 100%; position: relative; overflow: hidden; `; targetContainer.appendChild(viewportWindow); // 保存当前视口 this.currentViewport = viewportWindow; // 更新iframe位置 this.updateIframePosition(); // 监听窗口大小变化 if (!this.resizeObserver) { this.resizeObserver = new ResizeObserver(() => { this.updateIframePosition(); }); } if (this.currentResizeTarget) { this.resizeObserver.unobserve(this.currentResizeTarget); } this.resizeObserver.observe(viewportWindow); this.currentResizeTarget = viewportWindow; // 更新当前插件 const oldPlugin = this.currentPlugin; this.currentPlugin = pluginId; console.log(`✅ 插件 ${pluginId} 已激活 (从 ${oldPlugin || 'none'})`); console.log(`📊 使用全局覆盖策略,iframe跟随容器,状态完全保持`); return true; } catch (error) { console.error(`❌ 无法附加iframe到插件 ${pluginId}:`, error); // 显示错误信息 if (loadingElement) { loadingElement.innerHTML = `