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

62 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";
2022-03-28 13:25:05 +00:00
2022-05-09 12:59:12 +00:00
export function Panel({
html,
script,
flex,
2022-05-11 18:10:45 +00:00
editor,
2022-05-09 12:59:12 +00:00
}: {
html: string;
script?: string;
flex: number;
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: html,
2022-05-09 12:59:12 +00:00
script: 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;
};
}, [html]);
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 (
2022-08-02 12:40:04 +00:00
<div className="sb-panel" style={{ flex }}>
2022-04-04 13:25:07 +00:00
<iframe srcDoc={iframeHtml} ref={iFrameRef} />
2022-03-28 13:25:05 +00:00
</div>
);
}