1
0
silverbullet/packages/web/components/panel.tsx

59 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-04-05 15:02:17 +00:00
import { useEffect, useRef } from "react";
2022-04-04 13:25:07 +00:00
// @ts-ignore
import iframeHtml from "bundle-text:./panel.html";
2022-05-11 18:10:45 +00:00
import { Editor } from "../editor";
import { PanelConfig } from "../types";
2022-03-28 13:25:05 +00:00
2022-05-09 12:59:12 +00:00
export function Panel({
config,
2022-05-11 18:10:45 +00:00
editor,
2022-05-09 12:59:12 +00:00
}: {
config: PanelConfig;
2022-05-11 18:10:45 +00:00
editor: Editor;
2022-05-09 12:59:12 +00:00
}) {
2022-03-28 13:25:05 +00:00
const iFrameRef = useRef<HTMLIFrameElement>(null);
2022-04-04 13:25:07 +00:00
useEffect(() => {
function loadContent() {
if (iFrameRef.current?.contentWindow) {
iFrameRef.current.contentWindow.postMessage({
type: "html",
html: config.html,
script: config.script,
2022-04-04 13:25:07 +00:00
});
}
}
if (!iFrameRef.current) {
return;
}
let iframe = iFrameRef.current;
iframe.onload = loadContent;
loadContent();
return () => {
iframe.onload = null;
};
}, [config.html, config.script]);
2022-04-05 15:02:17 +00:00
useEffect(() => {
let messageListener = (evt: any) => {
if (evt.source !== iFrameRef.current!.contentWindow) {
return;
}
let data = evt.data;
if (!data) return;
2022-05-11 18:10:45 +00:00
if (data.type === "event") {
2022-07-17 16:52:47 +00:00
editor.dispatchAppEvent(data.name, ...data.args);
2022-05-11 18:10:45 +00:00
}
2022-04-05 15:02:17 +00:00
};
window.addEventListener("message", messageListener);
return () => {
window.removeEventListener("message", messageListener);
};
}, []);
2022-03-28 13:25:05 +00:00
return (
<div className="sb-panel" style={{ flex: config.mode }}>
2022-04-04 13:25:07 +00:00
<iframe srcDoc={iframeHtml} ref={iFrameRef} />
2022-03-28 13:25:05 +00:00
</div>
);
}