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

64 lines
1.5 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 { System } from "@plugos/plugos/system";
import { SilverBulletHooks } from "@silverbulletmd/common/manifest";
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") {
editor.dispatchAppEvent(data.name, data.args);
}
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-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>
);
}