-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.ts
More file actions
80 lines (69 loc) · 2.04 KB
/
index.ts
File metadata and controls
80 lines (69 loc) · 2.04 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import React, { useEffect, useRef } from "react";
import {
filterOutRichData,
isRichData,
mapKeyToPropertyName,
mapKeyToEventName,
shouldKeyBeMapped
} from "./helper";
import { OverrideProps, EventListenerMap } from "./interfaces";
import { DEFAULT_EVENT_PREFIX } from "./constants";
export const adapt = <T = any>(
componentSelector: string,
overrideProps?: OverrideProps
) => {
return (props: T & EventListenerMap) => {
const webComponentRef = useRef<HTMLElement | null>(null);
useEffect(() => {
const eventListeners: EventListenerMap = {};
const removeEventListeners = () => {
for (let key in eventListeners) {
const handler = eventListeners[key];
webComponentRef.current!.removeEventListener(
mapKeyToEventName(key, overrideProps),
handler
);
}
};
const setUpEventListeners = () => {
for (let key in props) {
const handler = props[key];
if (
key.indexOf(DEFAULT_EVENT_PREFIX) === -1 &&
!shouldKeyBeMapped(key, overrideProps)
) {
continue;
}
if (typeof handler !== `function`) {
continue;
}
eventListeners[key] = handler;
webComponentRef.current!.addEventListener(
mapKeyToEventName(key, overrideProps),
handler
);
}
};
const updatePropertiesForRichData = () => {
for (let key in props) {
const data = props[key];
if (!isRichData(data) || key === "children") {
continue;
}
webComponentRef.current![
mapKeyToPropertyName(key, overrideProps)
] = data;
}
};
setUpEventListeners();
updatePropertiesForRichData();
return () => {
removeEventListeners();
};
});
return React.createElement(componentSelector, {
ref: (ref: HTMLElement) => (webComponentRef.current = ref),
...filterOutRichData(props, overrideProps)
});
};
};