const QUICKAPP_VENDOR = '{{VENDOR}}';
const DESIGN_WIDTH = 750;
function createQuickAppBridge(services, wasmGlue) {
const state = {
page: null,
canvas: null,
ctx: null,
gl: null,
glProgram: null,
glVao: null,
glTexture: null,
glTexW: 0,
glTexH: 0,
imgData: null,
imgW: 0,
imgH: 0,
rgbaBuf: null,
rgbaPtr: 0,
rgbaLen: 0,
rgbaView: null,
u8View: null,
wasmApi: null,
wasmMemory: null,
running: false,
rafArmed: false,
lastTickTs: 0,
rafId: 0,
rafIsTimeout: false,
metrics: {
screenWidthPx: 1080,
screenHeightPx: 2400,
density: 3.0,
logicalWidth: 360,
logicalHeight: 800,
statusBarDp: 36,
navBarDp: 24,
designWidth: DESIGN_WIDTH,
isDark: false
},
lastAccel: [0, 9.80665, 0],
lastGyro: [0, 0, 0]
};
function installOffscreenFontFactory() {
const g = typeof globalThis !== 'undefined' ? globalThis : null;
if (!g) return;
g.__EUV_HOST_MODE = 'quickapp';
if (typeof g.__euvCreateOffscreenCanvas !== 'function') {
g.__euvCreateOffscreenCanvas = function (width, height) {
const w = Math.max(1, Math.round(width || 128));
const h = Math.max(1, Math.round(height || 128));
if (typeof OffscreenCanvas !== 'undefined') {
try {
return new OffscreenCanvas(w, h);
} catch (_e) {}
}
if (typeof document !== 'undefined' && typeof document.createElement === 'function') {
const c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
}
return null;
};
}
}
function applyDeviceInfo(info) {
if (!info) return state.metrics;
const sw = Math.max(240, Math.round(Number(info.screenWidth || info.windowWidth || 1080)));
const sh = Math.max(240, Math.round(Number(info.screenHeight || info.windowHeight || 2400)));
const density = Math.min(16.0, Math.max(0.25, Number(info.screenDensity || info.pixelRatio || 3.0)));
const lw = Math.max(120, Math.round(sw / density));
const lh = Math.max(120, Math.round(sh / density));
const statusBarPx = Number(info.statusBarHeight || Math.round(36 * density));
const navBarPx = Number(info.navBarHeight || Math.round(24 * density));
state.metrics = {
screenWidthPx: sw,
screenHeightPx: sh,
density,
logicalWidth: lw,
logicalHeight: lh,
statusBarDp: Math.max(0, statusBarPx / density),
navBarDp: Math.max(0, navBarPx / density),
designWidth: DESIGN_WIDTH,
isDark: info.theme === 'dark' || info.themeMode === 1
};
return state.metrics;
}
function designPxToDp(designVal) {
const dw = Math.max(1, Number(state.metrics.designWidth || DESIGN_WIDTH));
return (Number(designVal || 0) * state.metrics.logicalWidth) / dw;
}
function executeHostCommand(cmd) {
if (!cmd) return;
const s = services || {};
switch (cmd.kind) {
case 'routerPush':
case 'navigateTo':
if (s.router && typeof s.router.push === 'function') s.router.push({ uri: cmd.uri || cmd.url || '' });
break;
case 'routerBack':
case 'navigateBack':
if (s.router && typeof s.router.back === 'function') s.router.back();
break;
case 'storageSet':
case 'setStorageSync':
if (s.storage && typeof s.storage.set === 'function') s.storage.set({ key: cmd.key, value: cmd.value });
break;
case 'storageDelete':
case 'removeStorageSync':
if (s.storage && typeof s.storage.delete === 'function') s.storage.delete({ key: cmd.key });
break;
case 'storageClear':
case 'clearStorageSync':
if (s.storage && typeof s.storage.clear === 'function') s.storage.clear();
break;
case 'clipboardSet':
case 'setClipboardData':
if (s.clipboard && typeof s.clipboard.set === 'function') s.clipboard.set({ text: cmd.text || cmd.value || '' });
break;
case 'setTitleBar':
case 'setTitle':
if (state.page && state.page.$page && typeof state.page.$page.setTitleBar === 'function') {
state.page.$page.setTitleBar({ text: cmd.value || '' });
}
break;
case 'vibrateShort':
if (s.vibrator && typeof s.vibrator.vibrate === 'function') s.vibrator.vibrate({ mode: 'short' });
break;
case 'showToast':
if (s.prompt && typeof s.prompt.showToast === 'function') s.prompt.showToast({ message: cmd.message || '' });
break;
case 'showKeyboard':
if (state.page && typeof state.page.setImeFocus === 'function') {
state.page.setImeFocus(Boolean(cmd.enabled));
}
break;
case 'openUrl':
if (s.router && typeof s.router.push === 'function') {
s.router.push({ uri: cmd.url || '' });
}
break;
default:
break;
}
}
function drainCommands() {
if (!state.wasmApi || typeof state.wasmApi.euv_host_drain_commands_json !== 'function') return [];
const raw = state.wasmApi.euv_host_drain_commands_json();
if (!raw || raw === '[]') return [];
try {
const list = JSON.parse(raw);
if (Array.isArray(list)) {
for (let i = 0; i < list.length; i += 1) {
executeHostCommand(list[i]);
}
return list;
}
} catch (_ignored) {}
return [];
}
function getCachedRgbaView(ptr, len) {
const buf = state.wasmMemory.buffer;
if (state.rgbaView && state.rgbaBuf === buf && state.rgbaPtr === ptr && state.rgbaLen === len) {
return state.rgbaView;
}
state.rgbaBuf = buf;
state.rgbaPtr = ptr;
state.rgbaLen = len;
state.rgbaView = new Uint8ClampedArray(buf, ptr, len);
state.u8View = new Uint8Array(buf, ptr, len);
return state.rgbaView;
}
function initWebGl2(canvas) {
if (!canvas || typeof canvas.getContext !== 'function') return false;
let gl = null;
try {
gl = canvas.getContext('webgl2', {
alpha: false,
antialias: false,
depth: false,
stencil: false,
preserveDrawingBuffer: false
});
} catch (_e) {
gl = null;
}
if (!gl || typeof gl.drawArraysInstanced !== 'function' || typeof gl.texStorage2D !== 'function') {
return false;
}
const vsSrc = '#version 300 es\nconst vec2 P[6]=vec2[6](vec2(-1.0,-1.0),vec2(1.0,-1.0),vec2(-1.0,1.0),vec2(1.0,-1.0),vec2(1.0,1.0),vec2(-1.0,1.0));\nout vec2 v_uv;\nvoid main(){vec2 p=P[gl_VertexID];v_uv=vec2(p.x*0.5+0.5,0.5-p.y*0.5);gl_Position=vec4(p,0.0,1.0);}';
const fsSrc = '#version 300 es\nprecision mediump float;\nin vec2 v_uv;\nuniform sampler2D u_tex;\nout vec4 o_col;\nvoid main(){o_col=texture(u_tex,v_uv);}';
const vs = gl.createShader(gl.VERTEX_SHADER);
const fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(vs, vsSrc);
gl.compileShader(vs);
gl.shaderSource(fs, fsSrc);
gl.compileShader(fs);
const prog = gl.createProgram();
gl.attachShader(prog, vs);
gl.attachShader(prog, fs);
gl.linkProgram(prog);
gl.deleteShader(vs);
gl.deleteShader(fs);
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) {
gl.deleteProgram(prog);
return false;
}
state.gl = gl;
state.glProgram = prog;
state.glVao = gl.createVertexArray();
state.glTexture = null;
state.glTexW = 0;
state.glTexH = 0;
return true;
}
function blitFrameWebGl2(pw, ph, dx, dy, dw, dh) {
const gl = state.gl;
if (!gl || !state.glProgram || !state.u8View) return false;
if (!state.glTexture || state.glTexW !== pw || state.glTexH !== ph) {
if (state.glTexture) gl.deleteTexture(state.glTexture);
state.glTexture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, state.glTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, pw, ph);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, pw, ph, gl.RGBA, gl.UNSIGNED_BYTE, state.u8View);
state.glTexW = pw;
state.glTexH = ph;
} else {
gl.bindTexture(gl.TEXTURE_2D, state.glTexture);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
if (dx === 0 && dy === 0 && dw === pw && dh === ph) {
gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, pw, ph, gl.RGBA, gl.UNSIGNED_BYTE, state.u8View);
} else {
gl.pixelStorei(gl.UNPACK_ROW_LENGTH, pw);
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, dx);
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, dy);
gl.texSubImage2D(gl.TEXTURE_2D, 0, dx, dy, dw, dh, gl.RGBA, gl.UNSIGNED_BYTE, state.u8View);
gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
}
}
gl.viewport(0, 0, pw, ph);
gl.useProgram(state.glProgram);
gl.bindVertexArray(state.glVao);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, state.glTexture);
gl.drawArraysInstanced(gl.TRIANGLES, 0, 6, 1);
return true;
}
function ensureImageData(pw, ph) {
if (state.imgData && state.imgW === pw && state.imgH === ph) return state.imgData;
if (state.ctx && typeof state.ctx.createImageData === 'function') {
state.imgData = state.ctx.createImageData(pw, ph);
} else if (typeof ImageData !== 'undefined') {
state.imgData = new ImageData(pw, ph);
} else {
state.imgData = { width: pw, height: ph, data: new Uint8ClampedArray(pw * ph * 4) };
}
state.imgW = pw;
state.imgH = ph;
return state.imgData;
}
function blitFrame(forceFull) {
if (!state.wasmApi || !state.wasmMemory || !state.canvas || (!state.gl && !state.ctx)) return false;
const ptr = state.wasmApi.euv_host_framebuffer_ptr();
const len = state.wasmApi.euv_host_framebuffer_len();
const pw = state.wasmApi.euv_host_framebuffer_width();
const ph = state.wasmApi.euv_host_framebuffer_height();
if (!ptr || !len || !pw || !ph) return false;
if (state.canvas.width !== pw) state.canvas.width = pw;
if (state.canvas.height !== ph) state.canvas.height = ph;
const dx = forceFull ? 0 : state.wasmApi.euv_host_dirty_x();
const dy = forceFull ? 0 : state.wasmApi.euv_host_dirty_y();
const dw = forceFull ? pw : state.wasmApi.euv_host_dirty_w();
const dh = forceFull ? ph : state.wasmApi.euv_host_dirty_h();
if (!dw || !dh) return false;
const rgba = getCachedRgbaView(ptr, len);
if (state.gl) {
return blitFrameWebGl2(pw, ph, dx, dy, dw, dh);
}
const imgData = ensureImageData(pw, ph);
if (dx === 0 && dy === 0 && dw === pw && dh === ph) {
imgData.data.set(rgba);
state.ctx.putImageData(imgData, 0, 0);
} else {
const dst = imgData.data;
const stride = pw * 4;
const rowBytes = dw * 4;
for (let row = 0; row < dh; row += 1) {
const off = (dy + row) * stride + dx * 4;
dst.set(rgba.subarray(off, off + rowBytes), off);
}
state.ctx.putImageData(imgData, 0, 0, dx, dy, dw, dh);
}
return true;
}
function hostNeedsFrame() {
if (!state.wasmApi) return false;
if (typeof state.wasmApi.euv_host_needs_frame === 'function') {
return Boolean(state.wasmApi.euv_host_needs_frame());
}
return false;
}
function stepNow(dtSecs, forceRender) {
if (!state.wasmApi) return false;
const rendered = state.wasmApi.euv_host_step(dtSecs, Boolean(forceRender));
drainCommands();
if (rendered) return blitFrame(Boolean(forceRender));
return false;
}
function scheduleNextFrame(cb) {
if (typeof requestAnimationFrame === 'function') {
state.rafIsTimeout = false;
state.rafId = requestAnimationFrame(cb);
} else {
state.rafIsTimeout = true;
state.rafId = setTimeout(() => cb(Date.now()), 16);
}
}
function frameTick(ts) {
state.rafArmed = false;
state.rafId = 0;
if (!state.running) return;
const now = typeof ts === 'number' && ts > 0 ? ts : Date.now();
const dt = state.lastTickTs > 0 ? Math.min(0.05, Math.max(0.002, (now - state.lastTickTs) / 1000)) : (1 / 60);
state.lastTickTs = now;
const rendered = stepNow(dt, false);
if (state.running && (rendered || hostNeedsFrame())) {
state.rafArmed = true;
scheduleNextFrame(frameTick);
} else {
state.lastTickTs = 0;
}
}
function wakeLoop() {
if (!state.running || !state.canvas || state.rafArmed) return;
state.rafArmed = true;
state.lastTickTs = 0;
scheduleNextFrame(frameTick);
}
function startLoop() {
if (!state.canvas) return;
state.running = true;
wakeLoop();
}
function stopLoop() {
state.running = false;
state.rafArmed = false;
state.lastTickTs = 0;
if (!state.rafId) return;
if (state.rafIsTimeout) clearTimeout(state.rafId);
else if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(state.rafId);
state.rafId = 0;
}
async function mount(page, canvas, deviceInfo) {
state.page = page;
state.canvas = canvas;
state.gl = null;
state.ctx = initWebGl2(canvas)
? null
: (canvas && typeof canvas.getContext === 'function' ? canvas.getContext('2d') : null);
applyDeviceInfo(deviceInfo);
installOffscreenFontFactory();
const glue = wasmGlue || (typeof globalThis !== 'undefined' && globalThis.__euvWasmBindgen) || null;
if (!glue || typeof glue.__euvInitHost !== 'function') return false;
const wasmSource = (typeof globalThis !== 'undefined' && globalThis.__EUV_WASM_SOURCE) || '/Common/euv_app.wasm';
const initialized = await glue.__euvInitHost(wasmSource);
state.wasmApi = initialized.api;
state.wasmMemory = initialized.memory;
state.wasmApi.euv_host_init(
2,
QUICKAPP_VENDOR,
state.metrics.logicalWidth,
state.metrics.logicalHeight,
state.metrics.density,
state.metrics.statusBarDp,
state.metrics.navBarDp
);
if (state.metrics.isDark) {
state.wasmApi.euv_host_theme(true);
state.wasmApi.euv_host_step(1 / 60, true);
}
blitFrame(true);
drainCommands();
startLoop();
return true;
}
function dispatchDesignTouch(phase, event) {
if (!state.wasmApi || typeof state.wasmApi.euv_host_touch !== 'function') return;
const touches = (event && (event.changedTouches || event.touches)) || [];
const phaseTag = phase === 'down' ? 0 : phase === 'move' ? 1 : phase === 'up' ? 2 : 3;
for (let i = 0; i < touches.length; i += 1) {
const t = touches[i];
const rawX = Number(typeof t.offsetX === 'number' ? t.offsetX : (typeof t.clientX === 'number' ? t.clientX : (t.x || 0)));
const rawY = Number(typeof t.offsetY === 'number' ? t.offsetY : (typeof t.clientY === 'number' ? t.clientY : (t.y || 0)));
state.wasmApi.euv_host_touch(phaseTag, Number(t.identifier || 0), designPxToDp(rawX), designPxToDp(rawY));
}
stepNow(1 / 60, false);
wakeLoop();
}
function dispatchLifecycle(tag, payload) {
if (tag === 3 || tag === 4) {
stopLoop();
} else if (tag === 2 && state.canvas && state.wasmApi) {
startLoop();
}
if (!state.wasmApi || typeof state.wasmApi.euv_host_lifecycle !== 'function') return false;
const consumed = Boolean(state.wasmApi.euv_host_lifecycle(tag, String(payload || '')));
if (tag === 2 || tag === 5) {
stepNow(1 / 60, tag === 2);
wakeLoop();
}
return consumed;
}
function dispatchIme(text, confirmed) {
if (!state.wasmApi || typeof state.wasmApi.euv_host_ime !== 'function') return;
state.wasmApi.euv_host_ime(String(text || ''), Boolean(confirmed));
stepNow(1 / 60, false);
wakeLoop();
}
function dispatchTheme(isDark) {
if (!state.wasmApi || typeof state.wasmApi.euv_host_theme !== 'function') return;
state.wasmApi.euv_host_theme(Boolean(isDark));
stepNow(1 / 60, true);
wakeLoop();
}
function dispatchNetwork(status) {
if (!state.wasmApi || typeof state.wasmApi.euv_host_network !== 'function') return;
state.wasmApi.euv_host_network(String(status || 'wifi'));
}
function dispatchSensor(accel, gyro) {
if (accel) state.lastAccel = accel;
if (gyro) state.lastGyro = gyro;
if (!state.wasmApi || typeof state.wasmApi.euv_host_device_motion !== 'function') return;
state.wasmApi.euv_host_device_motion(
state.lastAccel[0], state.lastAccel[1], state.lastAccel[2],
state.lastGyro[0], state.lastGyro[1], state.lastGyro[2]
);
if (hostNeedsFrame()) wakeLoop();
}
function navigate(route) {
if (!state.wasmApi || typeof state.wasmApi.euv_host_navigate !== 'function') return 0;
const hash = state.wasmApi.euv_host_navigate(String(route || '/'));
blitFrame(true);
drainCommands();
wakeLoop();
return hash;
}
function getStats() {
if (!state.wasmApi || typeof state.wasmApi.euv_host_stats_json !== 'function') return null;
try {
return JSON.parse(state.wasmApi.euv_host_stats_json());
} catch (_e) {
return null;
}
}
function destroy() {
stopLoop();
if (state.wasmApi && typeof state.wasmApi.euv_host_destroy === 'function') {
state.wasmApi.euv_host_destroy();
}
state.canvas = null;
state.ctx = null;
state.gl = null;
state.glProgram = null;
state.glVao = null;
state.glTexture = null;
state.glTexW = 0;
state.glTexH = 0;
state.imgData = null;
state.rgbaBuf = null;
state.rgbaView = null;
state.u8View = null;
}
return {
QUICKAPP_VENDOR,
DESIGN_WIDTH,
designPxToDp,
mount,
stepNow,
drainCommands,
executeHostCommand,
dispatchDesignTouch,
dispatchLifecycle,
dispatchIme,
dispatchTheme,
dispatchNetwork,
dispatchSensor,
navigate,
getStats,
destroy
};
}
export { QUICKAPP_VENDOR, DESIGN_WIDTH, createQuickAppBridge };
export default createQuickAppBridge;