(
displayName: string,
controller: { create: (options: OptionsType) => Promise<OverlayType> },
defineCustomElement: () => void,
component: ReactComponentOrElement,
componentProps?: any
)
| 16 | } |
| 17 | |
| 18 | export function useOverlay<OptionsType, OverlayType extends OverlayBase>( |
| 19 | displayName: string, |
| 20 | controller: { create: (options: OptionsType) => Promise<OverlayType> }, |
| 21 | defineCustomElement: () => void, |
| 22 | component: ReactComponentOrElement, |
| 23 | componentProps?: any |
| 24 | ) { |
| 25 | const overlayRef = useRef<OverlayType>(); |
| 26 | const containerElRef = useRef<HTMLDivElement>(); |
| 27 | const didDismissEventName = useMemo(() => `on${displayName}DidDismiss`, [displayName]); |
| 28 | const didPresentEventName = useMemo(() => `on${displayName}DidPresent`, [displayName]); |
| 29 | const willDismissEventName = useMemo(() => `on${displayName}WillDismiss`, [displayName]); |
| 30 | const willPresentEventName = useMemo(() => `on${displayName}WillPresent`, [displayName]); |
| 31 | const [isOpen, setIsOpen] = useState(false); |
| 32 | const ionContext = useContext(IonContext); |
| 33 | const [overlayId] = useState(generateId('overlay')); |
| 34 | |
| 35 | defineCustomElement(); |
| 36 | |
| 37 | useEffect(() => { |
| 38 | if (isOpen && component && containerElRef.current) { |
| 39 | if (React.isValidElement(component)) { |
| 40 | ionContext.addOverlay(overlayId, component, containerElRef.current!); |
| 41 | } else { |
| 42 | const element = createElement(component as React.ComponentClass, componentProps); |
| 43 | ionContext.addOverlay(overlayId, element, containerElRef.current!); |
| 44 | } |
| 45 | } |
| 46 | }, [component, containerElRef.current, isOpen, componentProps]); |
| 47 | |
| 48 | const present = useCallback(async (options: OptionsType & HookOverlayOptions) => { |
| 49 | if (overlayRef.current) { |
| 50 | return; |
| 51 | } |
| 52 | |
| 53 | const { onDidDismiss, onWillDismiss, onDidPresent, onWillPresent, ...rest } = options; |
| 54 | |
| 55 | if (typeof document !== 'undefined') { |
| 56 | containerElRef.current = document.createElement('div'); |
| 57 | } |
| 58 | |
| 59 | overlayRef.current = await controller.create({ |
| 60 | ...(rest as any), |
| 61 | component: containerElRef.current, |
| 62 | }); |
| 63 | |
| 64 | attachProps(overlayRef.current, { |
| 65 | [didDismissEventName]: handleDismiss, |
| 66 | [didPresentEventName]: (e: CustomEvent) => onDidPresent && onDidPresent(e), |
| 67 | [willDismissEventName]: (e: CustomEvent) => onWillDismiss && onWillDismiss(e), |
| 68 | [willPresentEventName]: (e: CustomEvent) => onWillPresent && onWillPresent(e), |
| 69 | }); |
| 70 | |
| 71 | overlayRef.current.present(); |
| 72 | |
| 73 | setIsOpen(true); |
| 74 | |
| 75 | function handleDismiss(event: CustomEvent<OverlayEventDetail<any>>) { |
no test coverage detected