euv-cli 0.50.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
Documentation
const QUICKAPP_VENDOR = '{{VENDOR}}';
const DESIGN_WIDTH = 750;

function createQuickAppBridge(services, wasmGlue) {
  const state = {
    page: null,
    canvas: null,
    ctx: null,
    imgData: null,
    imgW: 0,
    imgH: 0,
    wasmApi: null,
    wasmMemory: null,
    running: false,
    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(4.5, Math.max(0.75, 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 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.ctx || !state.canvas) 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 = new Uint8ClampedArray(state.wasmMemory.buffer, ptr, len);
    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 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 startLoop() {
    if (state.running || !state.canvas) return;
    state.running = true;
    let lastTs = 0;
    const tick = (ts) => {
      if (!state.running) return;
      const now = typeof ts === 'number' && ts > 0 ? ts : Date.now();
      const dt = lastTs > 0 ? Math.min(0.05, Math.max(0.002, (now - lastTs) / 1000)) : (1 / 60);
      lastTs = now;
      stepNow(dt, false);
      if (state.running) scheduleNextFrame(tick);
    };
    scheduleNextFrame(tick);
  }

  function stopLoop() {
    state.running = false;
    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.ctx = 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);
  }

  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);
    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);
  }

  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);
  }

  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]
    );
  }

  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();
    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.imgData = 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;