2022-10-10 12:50:21 +00:00
|
|
|
import { useEffect, useRef } from "../deps.ts";
|
2023-07-14 14:56:20 +00:00
|
|
|
import { Client } from "../client.ts";
|
2022-10-10 12:50:21 +00:00
|
|
|
import { PanelConfig } from "../types.ts";
|
2023-10-03 12:16:33 +00:00
|
|
|
import { panelHtml } from "./panel_html.ts";
|
2022-10-10 12:50:21 +00:00
|
|
|
|
|
|
|
export function Panel({
|
|
|
|
config,
|
|
|
|
editor,
|
|
|
|
}: {
|
|
|
|
config: PanelConfig;
|
2023-07-14 14:56:20 +00:00
|
|
|
editor: Client;
|
2022-10-10 12:50:21 +00:00
|
|
|
}) {
|
|
|
|
const iFrameRef = useRef<HTMLIFrameElement>(null);
|
|
|
|
useEffect(() => {
|
|
|
|
function loadContent() {
|
|
|
|
if (iFrameRef.current?.contentWindow) {
|
|
|
|
iFrameRef.current.contentWindow.postMessage({
|
|
|
|
type: "html",
|
|
|
|
html: config.html,
|
|
|
|
script: config.script,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!iFrameRef.current) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const iframe = iFrameRef.current;
|
|
|
|
iframe.onload = loadContent;
|
|
|
|
loadContent();
|
|
|
|
return () => {
|
|
|
|
iframe.onload = null;
|
|
|
|
};
|
|
|
|
}, [config.html, config.script]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const messageListener = (evt: any) => {
|
|
|
|
if (evt.source !== iFrameRef.current!.contentWindow) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const data = evt.data;
|
|
|
|
if (!data) {
|
|
|
|
return;
|
|
|
|
}
|
2023-01-16 09:40:16 +00:00
|
|
|
switch (data.type) {
|
|
|
|
case "event":
|
|
|
|
editor.dispatchAppEvent(data.name, ...data.args);
|
|
|
|
break;
|
|
|
|
case "syscall": {
|
|
|
|
const { id, name, args } = data;
|
2023-07-14 11:44:30 +00:00
|
|
|
editor.system.localSyscall(name, args).then(
|
|
|
|
(result) => {
|
|
|
|
if (!iFrameRef.current?.contentWindow) {
|
|
|
|
// iFrame already went away
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
iFrameRef.current!.contentWindow!.postMessage({
|
|
|
|
type: "syscall-response",
|
|
|
|
id,
|
|
|
|
result,
|
|
|
|
});
|
|
|
|
},
|
|
|
|
).catch((e: any) => {
|
2023-01-16 10:06:07 +00:00
|
|
|
if (!iFrameRef.current?.contentWindow) {
|
|
|
|
// iFrame already went away
|
|
|
|
return;
|
|
|
|
}
|
2023-01-16 09:40:16 +00:00
|
|
|
iFrameRef.current!.contentWindow!.postMessage({
|
|
|
|
type: "syscall-response",
|
|
|
|
id,
|
|
|
|
error: e.message,
|
|
|
|
});
|
|
|
|
});
|
|
|
|
break;
|
|
|
|
}
|
2022-10-10 12:50:21 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
globalThis.addEventListener("message", messageListener);
|
|
|
|
return () => {
|
|
|
|
globalThis.removeEventListener("message", messageListener);
|
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<div className="sb-panel" style={{ flex: config.mode }}>
|
|
|
|
<iframe srcDoc={panelHtml} ref={iFrameRef} />
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|