- Notifications
You must be signed in to change notification settings - Fork 13.5k
/
Copy pathframework-delegate.tsx
53 lines (40 loc) · 1.46 KB
/
framework-delegate.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
importtype{FrameworkDelegate}from'@ionic/core/components';
import{createPortal}from'react-dom';
import{generateId}from'./utils/generateId';
// TODO(FW-2959): types
typeReactComponent=(props?: any)=>JSX.Element;
exportconstReactDelegate=(
addView: (view: React.ReactElement)=>void,
removeView: (view: React.ReactElement)=>void
): FrameworkDelegate=>{
constrefMap=newWeakMap<HTMLElement,React.ReactElement>();
constreactDelegateId=`react-delegate-${generateId()}`;
// Incrementing counter to generate unique keys for each view
letid=0;
constattachViewToDom=async(
parentElement: HTMLElement,
component: ReactComponent,
propsOrDataObj?: any,
cssClasses?: string[]
): Promise<any>=>{
constdiv=document.createElement('div');
cssClasses&&div.classList.add(...cssClasses);
parentElement.appendChild(div);
constcomponentWithProps=component(propsOrDataObj);
constkey=`${reactDelegateId}-${id++}`;
consthostComponent=createPortal(componentWithProps,div,key);
refMap.set(div,hostComponent);
addView(hostComponent);
returnPromise.resolve(div);
};
constremoveViewFromDom=(_container: any,component: HTMLElement): Promise<void>=>{
consthostComponent=refMap.get(component);
hostComponent&&removeView(hostComponent);
component.remove();
returnPromise.resolve();
};
return{
attachViewToDom,
removeViewFromDom,
};
};