import { BaseError, createCommands, wrapUserFunction, hostEmitter, isBoolean } from '@jolibox/common'; import { createAPI, createSyncAPI, registerCanIUse, t } from './base'; import { reportError } from '@/common/report/errors/report'; import { applyNative, onNative, publish } from '@jolibox/native-bridge'; import { nativeTaskEmitter } from '../report'; import { context } from '@/common/context'; const EXIT_GAME = 'exitGame'; const ON_READY = 'onReady'; const ON_SHOW = 'onJoliboxShow'; const ON_HIDE = 'onJoliboxHide'; const commands = createCommands(); const safeCallbackWrapper = wrapUserFunction(reportError as (err: Error | BaseError) => void); const exitGame = createAPI(EXIT_GAME, { paramsSchema: t.tuple(t.function(), t.boolean().optional().default(false)), implement: async (onBeforeExit: () => void, shouldStay = false) => { const safeCallback = safeCallbackWrapper(onBeforeExit); // 集中上报 safeCallback.call(this); // 透传context.shouldInterupt 且值为false时,为内部小程序。广播onRetentionResult if (isBoolean(context.shouldInterupt) && !context.shouldInterupt && context.from) { publish( 'onRetentionResult', { shouldStay }, context.from, true ); } if (!shouldStay) { context.setDoExitDirectly(); } await applyNative('exitAppAsync'); } }); const onShow = createSyncAPI(ON_SHOW, { paramsSchema: t.tuple(t.function()), implement(callback) { const safeCallback = safeCallbackWrapper(callback); onNative('onJoliboxEnterForeground', () => { safeCallback.call(this); nativeTaskEmitter.emit('visible', true); }); } }); const onHide = createSyncAPI(ON_HIDE, { paramsSchema: t.tuple(t.function()), implement(callback) { const safeCallback = safeCallbackWrapper(callback); onNative('onJoliboxEnterBackground', () => { safeCallback.call(this); nativeTaskEmitter.emit('visible', false); }); } }); 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.exit', exitGame); commands.registerCommand('LifecycleSDK.onReady', onReadyHandler); commands.registerCommand('LifecycleSDK.onJoliboxShow', onShow); commands.registerCommand('LifecycleSDK.onJoliboxHide', onHide); registerCanIUse('lifeCycle.exit', { version: '1.0.0' // mock }); registerCanIUse('lifeCycle.onReady', { version: '1.0.0' // mock }); registerCanIUse('lifeCycle.onJoliboxShow', { version: '1.0.0' // mock }); registerCanIUse('lifeCycle.onJoliboxHide', { version: '1.0.0' // mock });