PrelearnBridgeDemo.tsx 14.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { Dispatch, SetStateAction } from 'react';

type BridgeStatus = 'idle' | 'waiting' | 'ready' | 'error';

type BridgeMessage = {
  type: string;
  requestId: string;
  params?: Record<string, string>;
};

type BrowserBridgeMessage = {
  source: 'prelearn-app';
  type: 'PRELEARN_SESSION_INIT' | 'PRELEARN_APP_BACK_PRESSED';
  requestId?: string;
  payload?: TicketPayload;
  reason?: string;
};

type TicketPayload = {
  ok: boolean;
  ticket?: string;
  expiresIn?: number;
  context?: PrelearnContext;
  errorMessage?: string;
};

type PrelearnContext = {
  activityId: string;
  packageId: string;
  caseId: string;
};

type PendingRequest = {
  resolve: (payload: TicketPayload) => void;
  reject: (error: Error) => void;
  timer: number;
};

declare global {
  interface Window {
    uni?: {
      postMessage?: (options: { data: BridgeMessage }) => void;
      webView?: {
        postMessage?: (options: { data: BridgeMessage }) => void;
        navigateBack?: (options?: { delta?: number }) => void;
      };
    };
    __PRELEARN_BRIDGE_CALLBACK__?: (requestId: string, payload: TicketPayload) => void;
    initPrelearningSession?: (payload: TicketPayload) => void;
    onPrelearnAppBackPressed?: (payload?: { requestId?: string; reason?: string }) => void;
  }
}

const pendingRequests = new Map<string, PendingRequest>();

function appendLog(setLogs: Dispatch<SetStateAction<string[]>>, message: string) {
  const time = new Date().toLocaleTimeString();
  setLogs((logs) => [`${time} ${message}`, ...logs].slice(0, 12));
}

function loadUniWebviewSdk() {
  if (window.uni?.webView?.postMessage || window.uni?.postMessage) {
    return Promise.resolve();
  }

  return new Promise<void>((resolve) => {
    const existingScript = document.querySelector<HTMLScriptElement>('script[data-uni-webview-sdk]');
    if (existingScript) {
      document.addEventListener('UniAppJSBridgeReady', () => resolve(), { once: true });
      return;
    }

    const script = document.createElement('script');
    script.src = `${import.meta.env.BASE_URL}uni.webview.1.5.5.js`;
    script.async = true;
    script.dataset.uniWebviewSdk = 'true';
    const timer = window.setTimeout(() => resolve(), 300);
    script.onload = () => {
      window.clearTimeout(timer);
      resolve();
    };
    script.onerror = () => {
      window.clearTimeout(timer);
      resolve();
    };
    document.head.appendChild(script);
  });
}

function waitForBridgeReady(timeout = 1800) {
  return new Promise<boolean>((resolve) => {
    if (window.uni?.webView?.postMessage || window.uni?.postMessage || window.parent !== window) {
      resolve(true);
      return;
    }

    let settled = false;
    const done = (ready: boolean) => {
      if (settled) return;
      settled = true;
      resolve(ready);
    };

    document.addEventListener(
      'UniAppJSBridgeReady',
      () => {
        done(Boolean(window.uni?.webView?.postMessage || window.uni?.postMessage));
      },
      { once: true },
    );
    window.setTimeout(
      () => done(Boolean(window.uni?.webView?.postMessage || window.uni?.postMessage || window.parent !== window)),
      timeout,
    );
  });
}

function postMessageToApp(message: BridgeMessage) {
  if (window.parent && window.parent !== window) {
    window.parent.postMessage({
      source: 'prelearn-h5',
      ...message,
    }, '*');
    return true;
  }

  if (window.uni?.webView?.postMessage) {
    window.uni.webView.postMessage({ data: message });
    return true;
  }

  if (window.uni?.postMessage) {
    window.uni.postMessage({ data: message });
    return true;
  }

  return false;
}

function resolvePendingRequest(requestId: string | undefined, payload: TicketPayload) {
  if (!requestId) return;

  const pending = pendingRequests.get(requestId);
  if (!pending) return;

  window.clearTimeout(pending.timer);
  pendingRequests.delete(requestId);
  if (payload.ok) {
    pending.resolve(payload);
  } else {
    pending.reject(new Error(payload.errorMessage || 'APP 获取 ticket 失败'));
  }
}

async function requestPrelearnTicket() {
  const requestId = `prelearn_${Date.now()}_${Math.random().toString(16).slice(2)}`;

  return new Promise<TicketPayload>((resolve, reject) => {
    const timer = window.setTimeout(() => {
      pendingRequests.delete(requestId);
      reject(new Error('等待 APP 回传 ticket 超时'));
    }, 10000);

    pendingRequests.set(requestId, {
      resolve,
      reject,
      timer,
    });

    const sent = postMessageToApp({
      type: 'GET_PRELEARN_TICKET',
      requestId,
    });

    if (!sent) {
      window.clearTimeout(timer);
      pendingRequests.delete(requestId);
      reject(new Error('当前环境没有检测到 uni-app WebView Bridge'));
    }
  });
}

function exchangePrelearnPayload(payload: TicketPayload) {
  if (!payload.ticket) {
    throw new Error('APP 回传为空 ticket');
  }

  if (!payload.context) {
    throw new Error('APP 未回传预学习上下文');
  }

  return mockExchangeTicket(payload.ticket, payload.context);
}

function mockExchangeTicket(ticket: string, context: PrelearnContext) {
  return {
    sessionToken: `session_${ticket.slice(-12)}`,
    employeeIdentity: '由 H5 后端通过 ticket 换取,H5 URL 不携带员工ID',
    activityId: context.activityId,
    packageId: context.packageId,
    caseId: context.caseId,
  };
}

export function PrelearnBridgeDemo() {
  const launchUrl = useMemo(() => `${window.location.origin}${window.location.pathname}${window.location.search}`, []);
  const [status, setStatus] = useState<BridgeStatus>('idle');
  const [ticketPayload, setTicketPayload] = useState<TicketPayload | null>(null);
  const [context, setContext] = useState<PrelearnContext | null>(null);
  const [session, setSession] = useState<ReturnType<typeof mockExchangeTicket> | null>(null);
  const [error, setError] = useState('');
  const [logs, setLogs] = useState<string[]>([]);
  const initialized = useRef(false);
  const receivedAppInit = useRef(false);

  useEffect(() => {
    const receivePrelearningSession = (payload: TicketPayload) => {
      try {
        receivedAppInit.current = true;
        setStatus('ready');
        setError('');
        setTicketPayload(payload);
        setContext(payload.context || null);
        setSession(exchangePrelearnPayload(payload));
        appendLog(setLogs, 'APP 主动调用 window.initPrelearningSession,H5 已接收上下文和 ticket');
      } catch (caught) {
        const message = caught instanceof Error ? caught.message : 'APP 初始化参数无效';
        setStatus('error');
        setError(message);
        appendLog(setLogs, message);
      }
    };

    window.initPrelearningSession = receivePrelearningSession;

    const handleAppBackPressed = (payload?: { requestId?: string; reason?: string }) => {
      console.log('[prelearn bridge demo] H5 received app back pressed:', payload);
      appendLog(setLogs, `H5 收到 APP 返回事件:${payload?.reason || 'app_back'}`);
      postMessageToApp({
        type: 'PRELEARN_BACK_TO_APP',
        requestId: payload?.requestId || `back_confirm_${Date.now()}`,
        params: {
          reason: 'h5_confirm_app_back',
        },
      });
    };

    window.onPrelearnAppBackPressed = handleAppBackPressed;

    const handleBrowserMessage = (event: MessageEvent<BrowserBridgeMessage>) => {
      if (event.data?.source !== 'prelearn-app') return;

      if (event.data.type === 'PRELEARN_SESSION_INIT' && event.data.payload) {
        resolvePendingRequest(event.data.requestId, event.data.payload);
        receivePrelearningSession(event.data.payload);
      }

      if (event.data.type === 'PRELEARN_APP_BACK_PRESSED') {
        handleAppBackPressed({
          requestId: event.data.requestId,
          reason: event.data.reason,
        });
      }
    };

    window.addEventListener('message', handleBrowserMessage);

    window.__PRELEARN_BRIDGE_CALLBACK__ = (requestId, payload) => {
      resolvePendingRequest(requestId, payload);
    };

    return () => {
      pendingRequests.forEach((pending) => window.clearTimeout(pending.timer));
      pendingRequests.clear();
      window.removeEventListener('message', handleBrowserMessage);
      delete window.initPrelearningSession;
      delete window.onPrelearnAppBackPressed;
      delete window.__PRELEARN_BRIDGE_CALLBACK__;
    };
  }, []);

  const initPrelearningSession = useCallback(async () => {
    setStatus('waiting');
    setError('');
    setTicketPayload(null);
    setContext(null);
    setSession(null);
    appendLog(setLogs, 'H5 等待 APP 主动调用 window.initPrelearningSession');

    await loadUniWebviewSdk();
    const bridgeReady = await waitForBridgeReady();
    if (receivedAppInit.current) return;

    if (!bridgeReady) {
      setStatus('error');
      setError('未检测到 APP WebView Bridge。请在 APP WebView 或 uni-app H5 iframe 中打开此页面。');
      appendLog(setLogs, '未检测到 APP Bridge');
      return;
    }

    appendLog(setLogs, 'H5 已检测到 APP Bridge,若 APP 未主动注入则兜底发送 GET_PRELEARN_TICKET');
    postMessageToApp({
      type: 'PRELEARN_H5_READY',
      requestId: `ready_${Date.now()}_${Math.random().toString(16).slice(2)}`,
    });
    await new Promise((resolve) => window.setTimeout(resolve, 1200));
    if (receivedAppInit.current) return;

    try {
      const payload = await requestPrelearnTicket();
      setTicketPayload(payload);
      appendLog(setLogs, `APP 已回传 ticket,有效期 ${payload.expiresIn || 0} 秒`);

      setContext(payload.context || null);
      const exchangedSession = exchangePrelearnPayload(payload);
      setSession(exchangedSession);
      setStatus('ready');
      appendLog(setLogs, 'H5 模拟调用后端 exchange 接口,得到预学习 session');
    } catch (caught) {
      const message = caught instanceof Error ? caught.message : '初始化失败';
      setStatus('error');
      setError(message);
      appendLog(setLogs, message);
    }
  }, []);

  useEffect(() => {
    if (initialized.current) return;
    initialized.current = true;
    void initPrelearningSession();
  }, [initPrelearningSession]);

  const backToApp = () => {
    const requestId = `back_${Date.now()}`;
    console.log('[prelearn bridge demo] H5 send back event to app:', { requestId, reason: 'h5_button' });
    const sent = postMessageToApp({
      type: 'PRELEARN_BACK_TO_APP',
      requestId,
      params: {
        reason: 'h5_button',
      },
    });
    appendLog(setLogs, sent ? 'H5 通知 APP 关闭 WebView / 返回上一页' : '当前不在 APP WebView,无法通知 APP 返回');
  };

  return (
    <main className="min-h-screen bg-[#f6f8fb] text-[#1f2937]">
      <section className="mx-auto flex min-h-screen max-w-3xl flex-col gap-4 px-4 py-5">
        <header className="rounded-lg bg-white p-4 shadow-sm">
          <p className="text-sm text-[#64748b]">uni-app WebView Bridge Demo</p>
          <h1 className="mt-2 text-2xl font-semibold">套餐话术预学习 H5 取票验证</h1>
          <p className="mt-2 text-sm leading-6 text-[#475569]">
            H5 URL 只负责打开页面;APP 在 WebView 准备好后主动调用 H5 的 initPrelearningSession,把短期 ticket 和业务上下文传入。
          </p>
        </header>

        <section className="rounded-lg bg-white p-4 shadow-sm">
          <h2 className="text-base font-semibold">页面打开地址</h2>
          <p className="mt-3 break-all rounded bg-[#f8fafc] px-3 py-2 font-mono text-sm text-[#0f172a]">{launchUrl}</p>
          <p className="mt-2 text-sm text-[#64748b]">这里不携带 activityId、packageId、caseId、employeeId。</p>
        </section>

        <section className="rounded-lg bg-white p-4 shadow-sm">
          <h2 className="text-base font-semibold">APP Bridge 回传上下文</h2>
          <dl className="mt-3 grid gap-2 text-sm">
            {context ? Object.entries(context).map(([key, value]) => (
              <div className="flex justify-between rounded bg-[#f8fafc] px-3 py-2" key={key}>
                <dt className="text-[#64748b]">{key}</dt>
                <dd className="font-mono text-[#0f172a]">{value}</dd>
              </div>
            )) : <div className="rounded bg-[#f8fafc] px-3 py-2 text-[#64748b]">等待 APP 回传...</div>}
          </dl>
        </section>

        <section className="rounded-lg bg-white p-4 shadow-sm">
          <div className="flex items-center justify-between gap-3">
            <h2 className="text-base font-semibold">Bridge 状态</h2>
            <span className="rounded-full bg-[#e0f2fe] px-3 py-1 text-sm text-[#0369a1]">{status}</span>
          </div>

          {error ? <p className="mt-3 rounded bg-[#fef2f2] px-3 py-2 text-sm text-[#b91c1c]">{error}</p> : null}

          <div className="mt-4 flex flex-wrap gap-2">
            <button className="rounded bg-[#2563eb] px-4 py-2 text-sm font-medium text-white" onClick={initPrelearningSession}>
              重新初始化
            </button>
            <button className="rounded border border-[#cbd5e1] px-4 py-2 text-sm font-medium text-[#334155]" onClick={backToApp}>
              返回 APP 页面
            </button>
          </div>
        </section>

        <section className="rounded-lg bg-white p-4 shadow-sm">
          <h2 className="text-base font-semibold">APP 回传 ticket</h2>
          <pre className="mt-3 overflow-auto rounded bg-[#0f172a] p-3 text-xs leading-5 text-[#e2e8f0]">
            {ticketPayload ? JSON.stringify(ticketPayload, null, 2) : '等待 APP 回传...'}
          </pre>
        </section>

        <section className="rounded-lg bg-white p-4 shadow-sm">
          <h2 className="text-base font-semibold">H5 后端换取 session 后</h2>
          <pre className="mt-3 overflow-auto rounded bg-[#0f172a] p-3 text-xs leading-5 text-[#e2e8f0]">
            {session ? JSON.stringify(session, null, 2) : '等待 ticket exchange...'}
          </pre>
        </section>

        <section className="rounded-lg bg-white p-4 shadow-sm">
          <h2 className="text-base font-semibold">通信日志</h2>
          <ul className="mt-3 space-y-2 text-sm text-[#475569]">
            {logs.map((log) => (
              <li className="rounded bg-[#f8fafc] px-3 py-2" key={log}>
                {log}
              </li>
            ))}
          </ul>
        </section>
      </section>
    </main>
  );
}