import { context } from '@/common/context'; export function initializeNativeEnv() { let styleElement: HTMLStyleElement | null = null; let viewportMeta: HTMLMetaElement | null = null; const originalFetch = window.fetch; const createStyles = () => { // 创建并插入viewport meta标签 viewportMeta = document.createElement('meta'); viewportMeta.setAttribute('name', 'viewport'); viewportMeta.setAttribute( 'content', 'viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no' ); viewportMeta.setAttribute('data-jolibox-sdk', 'viewport-meta'); styleElement = document.createElement('style'); styleElement.setAttribute('data-jolibox-sdk', 'default-styles'); const styles = ` html[data-jolibox-root] { height: 100%; margin: 0; padding: 0; } html[data-jolibox-root] body { min-height: 100%; margin: 0; padding: 0; } @supports (height: 100dvh) { html[data-jolibox-root] body { min-height: 100dvh; } } `; styleElement.textContent = styles; const head = document.head || document.getElementsByTagName('head')[0]; // 插入viewport meta标签 head.insertBefore(viewportMeta, head.firstChild); head.insertBefore(styleElement, head.firstChild); document.documentElement.setAttribute('data-jolibox-root', ''); }; const setupSafeArea = () => { const { statusBarHeight, navigationBarHeight } = context.viewport; document.documentElement.style.setProperty('--status-bar-height', `${statusBarHeight}px`); document.documentElement.style.setProperty('--navigation-bar-height', `${navigationBarHeight}px`); }; const overrideFetch = () => { async function fetchWasm(input: string | URL) { const url = input instanceof URL ? input.href : input; const promise = new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.responseType = 'arraybuffer'; xhr.addEventListener('load', () => resolve(xhr.response)); xhr.addEventListener('error', reject); xhr.send(); }); try { const arrayBuffer = await promise; const response = new Response(arrayBuffer as BodyInit, { headers: new Headers([['Content-Type', 'application/wasm']]) }); return response.clone(); } catch (error) { console.error('Failed to load wasm:', error); throw error; } } const originalFetch = window.fetch; window.fetch = (input: RequestInfo | URL, options?: RequestInit) => { const url = input instanceof URL ? input.href : input.toString(); if (url.endsWith('.wasm')) { return fetchWasm(url); } return originalFetch(input, options); }; }; const cleanup = () => { if (styleElement?.parentNode) { styleElement.parentNode.removeChild(styleElement); styleElement = null; } // 清理viewport meta标签 if (viewportMeta?.parentNode) { viewportMeta.parentNode.removeChild(viewportMeta); viewportMeta = null; } document.documentElement.removeAttribute('data-jolibox-root'); document.documentElement.style.removeProperty('--status-bar-height'); window.fetch = originalFetch; }; createStyles(); overrideFetch(); setupSafeArea(); // 返回清理函数 return cleanup; }