import type { Key } from '@astrale-os/sdk/schema' import type { App, HostCapabilities, ResolvedView } from '@astrale-os/shell' import type { CSSProperties, ReactElement, ReactNode } from 'react' import { forwardRef, useEffect, useRef, useState } from 'react' import type { SandboxPolicy, ViewHostHandle } from '../../window/host.js' import type { WindowState } from '../../window/lifecycle/states.js' import { ViewHost } from '../../window/host.js' import { useOpenApp } from './open-app.hook.js' export type AppHostFallbackState = | WindowState | { readonly phase: 'opening' } | { readonly phase: 'no-view' } export interface AppHostProps { app: App | Key.Origin /** Override the installed Domain entry View. */ view?: ResolvedView capabilities?: HostCapabilities sandbox?: SandboxPolicy fallback?: (state: AppHostFallbackState) => ReactNode className?: string style?: CSSProperties } /** Resolve and mount an installed Domain through the ordinary Shell View lifecycle. */ export const AppHost = forwardRef( function AppHost(props, ref): ReactElement { const open = useOpenApp() const [opened, setOpened] = useState(undefined) const [error, setError] = useState(undefined) const origin = typeof props.app === 'string' ? props.app : props.app.origin const openRef = useRef(open) openRef.current = open useEffect(() => { let active = true setOpened(undefined) setError(undefined) void openRef.current(origin).then( (view) => { if (active) setOpened(view) }, (cause: unknown) => { if (active) setError(cause) }, ) return () => { active = false } }, [origin]) const { fallback, className, style } = props const box = (children: ReactNode): ReactElement => (
{children}
) if (error !== undefined) return box(fallback?.({ phase: 'crashed', error }) ?? null) if (opened === undefined && props.view === undefined) { return box(fallback?.({ phase: 'opening' }) ?? null) } const view = props.view ?? opened if (view === null || view === undefined) return box(fallback?.({ phase: 'no-view' }) ?? null) return ( fallback(state) : undefined} className={className} style={style} /> ) }, )