-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.tsx
99 lines (83 loc) · 2.27 KB
/
index.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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import React, { createRef, useEffect, useState } from 'react';
import { ResourceFetcherService } from './resource-fetcher.service';
import { getObjectFromPath } from './getObjectFromPath';
import { useHistory } from 'react-router-dom';
import urljoin from 'url-join';
interface SRMEvent {
[value: string]: any;
}
interface SRMMethods {
setBasename: (basename: string) => string;
setLanguage: (language: string) => string;
setEvent: (data: SRMEvent) => SRMEvent;
}
export interface Props {
originUrl: string;
exportPath: string;
basename?: string;
language?: string;
event?: { [key: string]: any };
arguments?: any;
eventHandlers?: { [id: string]: (...args: Array<any>) => Promise<any> };
loaded?: (el: HTMLElement) => any;
rendered?: (ret: any) => any;
}
export function ReactSRMWrapper({
originUrl,
exportPath,
basename,
language,
event,
arguments: renderArguments,
eventHandlers,
loaded,
rendered,
}: Props) {
const anchorEl = createRef<HTMLDivElement>();
const history = useHistory();
const [initialized, setInitialized] = useState(false);
const [executed, setExecuted] = useState(false);
const [srmMethods, setSrmMethods] = useState<SRMMethods | undefined>(undefined);
const initialize = async () => {
if (originUrl && !originUrl.endsWith('/')) {
originUrl += '/';
}
await ResourceFetcherService.loadSRM(originUrl);
loaded?.(anchorEl.current!);
setInitialized(true);
};
useEffect(() => {
initialize();
}, []);
useEffect(() => {
execute();
}, [anchorEl, initialized])
useEffect(() => {
if (event) {
srmMethods?.setEvent(event);
}
}, [event])
const execute = () => {
if (executed || !anchorEl.current || !initialized) {
return;
}
setExecuted(true);
const obj = getObjectFromPath(exportPath);
if (!obj || !obj.render) {
return;
}
setSrmMethods(obj.render({
element: anchorEl.current,
basename: basename,
language: language,
event: event,
navigate: (commands: any[], _options: any) => history.push(urljoin(commands)),
sendEvent: (id: string, ...args: Array<any>) => eventHandlers?.[id]?.(...args),
...renderArguments,
}));
rendered?.(srmMethods);
}
return (
<div ref={anchorEl}></div>
);
}