import { Env, Lifecycle } from '@jolibox/types'; import { BaseSDK, BaseSDKEventMap } from './sdk'; const LIFECYCLE_ON_READY = 'LifecycleSDK.onReady'; /** * @internal * Defines the event map specific to the LifecycleSDK, extending BaseSDKEventMap. */ interface LifecycleSDKEventMap extends BaseSDKEventMap { [LIFECYCLE_ON_READY]: Env['hostUserInfo'] | undefined; } /** * @public * Manages lifecycle events and functionalities within the Jolibox SDK. * This includes handling application readiness, exit procedures, and visibility changes. */ export class LifecycleSDK extends BaseSDK implements Lifecycle { constructor() { super(); } /** * @public * Registers a callback to be invoked when the Jolibox environment is ready. * This typically signifies that the main application or game can start its operations. * @param callback - A function to call when the environment is ready. It may receive host user information as a parameter. * @event LifecycleSDK.onReady Dispatched after the provided callback is executed, with host user info. */ onReady(callback: (info?: Env['hostUserInfo']) => void) { const wrappedOnReady = (info?: Env['hostUserInfo']) => { callback.call(this, info); this.triggerEvent(LIFECYCLE_ON_READY, info); }; this.commands.executeCommand('LifecycleSDK.onReady', wrappedOnReady.bind(this)); } /** * @private * Initiates the process to exit the Jolibox application or game. * Allows registering a callback to be executed before the exit occurs. * @param params - An object containing: * - `onBeforeExit`: A function to call before the application exits. * - `shouldStay` (optional): A boolean indicating if the application should attempt to prevent the exit. The exact behavior may depend on the host environment. * @returns {object | undefined} An error object if the 'lifeCycle.exit' capability is not available, otherwise undefined. */ exit(params: { onBeforeExit: () => void; shouldStay?: boolean }) { const errMsg = this.canIUseIfThrow('lifeCycle.exit'); if (errMsg) { return errMsg; } this.commands.executeCommand('LifecycleSDK.exit', params.onBeforeExit, params.shouldStay); } /** * @public * Registers a callback to be invoked when the Jolibox application is hidden (e.g., moved to the background). * @param callback - A function to call when the application is hidden. */ onJoliboxHide(callback: () => void) { this.commands.executeCommand('LifecycleSDK.onJoliboxHide', callback.bind(this)); } /** * @public * Registers a callback to be invoked when the Jolibox application is shown (e.g., brought to the foreground). * @param callback - A function to call when the application is shown. */ onJoliboxShow(callback: () => void) { this.commands.executeCommand('LifecycleSDK.onJoliboxShow', callback.bind(this)); } }