import React, { useEffect, useState, useMemo, forwardRef, MutableRefObject, } from 'react' import isFn from 'is-fn' import { Extension, Options, } from '../../types' import run from '../../run' import ExtInstance from './ExtInstance' type Props = Options & { [k: string]: any state: { [k: string]: any } } const eventHandlerRE = /^on[A-Z]/ const ExtRuntime = forwardRef(( props, ref ) => { const [ext, setExt] = useState() const { id, entry, state, attributes, dataSource, mock, } = props useEffect(() => { let currentExtPromise if (id && entry) { currentExtPromise = run(props) currentExtPromise ?.then((e) => { if (isFn(ref)) { (ref as (instance: Extension | undefined) => void)(e) } else if (ref) { (ref as MutableRefObject).current = e } setExt(e) }) } return () => { currentExtPromise ?.then((e) => { e?.destroy() }) } }, [id, entry]) useEffect(() => { const handlers = {} function onResetErrorBoundary() { setTimeout(() => { ext?.emit('render', state) }, 30) } if (ext) { for (const prop of Object.keys(props)) { if (eventHandlerRE.test(prop)) { const eventName = prop[2].toLowerCase() + prop.substr(3) handlers[eventName] = props[prop] ext.on(eventName, handlers[eventName]) } } ext.on('resetErrorBoundary', onResetErrorBoundary) } return () => { for (const eventName of Object.keys(handlers)) { ext?.off(eventName, handlers[eventName]) } ext?.off('resetErrorBoundar', onResetErrorBoundary) } }, [ ext, ...Object.entries(props) .filter(([key]) => eventHandlerRE.test(key)) .map(([key, value]) => value), ]) useEffect(() => { if (state) { ext?.emit('render', state) } }, [ext, JSON.stringify(state)]) useEffect(() => { if (attributes) { ext?.emit('attributes', attributes) } }, [ext, JSON.stringify(attributes)]) useEffect(() => { if (mock) { ext?.mockDataSource() } else if (dataSource) { ext?.emit('dataSource', dataSource) } }, [ext, JSON.stringify(dataSource), mock]) return useMemo( () => (ext ? ( ) : null), [ext] ) }) export default ExtRuntime