import { BaseError, createCommands, hostEmitter, wrapUserFunction } from '@jolibox/common'; import { createSyncAPI, registerCanIUse, t } from './base'; import { reportError } from '@/common/report/errors/report'; import { h5TaskEmitter } from '../report'; const ON_SHOW = 'onJoliboxShow'; const ON_HIDE = 'onJoliboxHide'; const ON_READY = 'onReady'; const commands = createCommands(); const safeCallbackWrapper = wrapUserFunction(reportError as (err: Error | BaseError) => void); let isPageVisible = true; let isPageFocused = true; let lastEventTime = 0; const visibleEmitter = h5TaskEmitter; // 防止交叉触发 function handleVisibilityChange() { const currentTime = Date.now(); if (currentTime - lastEventTime < 100) return; // 忽略100ms内的重复触发 lastEventTime = currentTime; const currentState = document.visibilityState === 'visible'; if (currentState !== isPageVisible) { isPageVisible = currentState; visibleEmitter.emit('visible', isPageVisible); } } function handleFocusBlur(eventType: string) { const currentTime = Date.now(); if (currentTime - lastEventTime < 100) return; // 忽略100ms内的重复触发 lastEventTime = currentTime; if (eventType === 'focus' && !isPageFocused) { isPageFocused = true; } else if (eventType === 'blur' && isPageFocused) { isPageFocused = false; } visibleEmitter.emit('visible', isPageFocused); } document.addEventListener('visibilitychange', handleVisibilityChange); window.addEventListener('focus', () => handleFocusBlur('focus')); window.addEventListener('blur', () => handleFocusBlur('blur')); const onShow = createSyncAPI(ON_SHOW, { paramsSchema: t.tuple(t.function()), implement(callback) { const safeCallback = safeCallbackWrapper(callback); visibleEmitter.on('visible', (visible) => { visible && safeCallback(); }); } }); const onHide = createSyncAPI(ON_HIDE, { paramsSchema: t.tuple(t.function()), implement(callback) { const safeCallback = safeCallbackWrapper(callback); visibleEmitter.on('visible', (visible) => { !visible && safeCallback(); }); } }); const onReadyHandler = createSyncAPI(ON_READY, { paramsSchema: t.tuple(t.function()), implement(callback) { const safeCallback = safeCallbackWrapper(callback); hostEmitter.on('LifecycleEvent.onReady', (info) => { safeCallback(info); }); } }); commands.registerCommand('LifecycleSDK.onReady', onReadyHandler); commands.registerCommand('LifecycleSDK.onJoliboxShow', onShow); commands.registerCommand('LifecycleSDK.onJoliboxHide', onHide); registerCanIUse('lifeCycle.onReady', { version: '1.0.0' // mock }); registerCanIUse('lifeCycle.onJoliboxShow', { version: '1.0.0' // mock }); registerCanIUse('lifeCycle.onJoliboxHide', { version: '1.0.0' // mock });