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

48 lines
1.2 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-03-28 13:25:05 +00:00
2022-04-04 16:33:13 +00:00
export function Panel({ html, flex }: { html: string; flex: number }) {
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,
});
}
}
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;
console.log("Got message from panel", data);
};
window.addEventListener("message", messageListener);
return () => {
window.removeEventListener("message", messageListener);
};
}, []);
2022-03-28 13:25:05 +00:00
return (
2022-04-04 16:33:13 +00:00
<div className="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>
);
}