|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import { useEffect, useRef } from "react"; |
| 5 | +import { createRoot } from "react-dom/client"; |
| 6 | + |
| 7 | +import styles from "./iframe-wrapper.module.scss"; |
| 8 | + |
| 9 | +export function IframeWrapper({ id = "iframe", AppComponent }: { id?: string; AppComponent: React.ComponentType }) { |
| 10 | + const iframeRef = useRef<HTMLIFrameElement>(null); |
| 11 | + |
| 12 | + useEffect(() => { |
| 13 | + const iframe = iframeRef.current; |
| 14 | + if (!iframe) { |
| 15 | + return; |
| 16 | + } |
| 17 | + |
| 18 | + const iframeDocument = iframe.contentDocument!; |
| 19 | + // Prevent iframe document instance from reload |
| 20 | + // https://bugzilla.mozilla.org/show_bug.cgi?id=543435 |
| 21 | + iframeDocument.open(); |
| 22 | + // set html5 doctype |
| 23 | + iframeDocument.writeln("<!DOCTYPE html>"); |
| 24 | + iframeDocument.close(); |
| 25 | + |
| 26 | + const innerAppRoot = iframeDocument.createElement("div"); |
| 27 | + iframeDocument.body.appendChild(innerAppRoot); |
| 28 | + copyStyles(document, iframeDocument); |
| 29 | + iframeDocument.dir = document.dir; |
| 30 | + const syncClassesCleanup = syncClasses(document.body, iframeDocument.body); |
| 31 | + const root = createRoot(innerAppRoot); |
| 32 | + root.render(<AppComponent />); |
| 33 | + return () => { |
| 34 | + syncClassesCleanup(); |
| 35 | + root.unmount(); |
| 36 | + }; |
| 37 | + }, [id, AppComponent]); |
| 38 | + |
| 39 | + return <iframe ref={iframeRef} id={id} title={id} className={styles["full-screen"]}></iframe>; |
| 40 | +} |
| 41 | + |
| 42 | +function copyStyles(srcDoc: Document, targetDoc: Document) { |
| 43 | + for (const stylesheet of Array.from(srcDoc.querySelectorAll("link[rel=stylesheet]"))) { |
| 44 | + const newStylesheet = targetDoc.createElement("link"); |
| 45 | + for (const attr of stylesheet.getAttributeNames()) { |
| 46 | + newStylesheet.setAttribute(attr, stylesheet.getAttribute(attr)!); |
| 47 | + } |
| 48 | + targetDoc.head.appendChild(newStylesheet); |
| 49 | + } |
| 50 | + |
| 51 | + for (const styleEl of Array.from(srcDoc.querySelectorAll("style"))) { |
| 52 | + const newStyle = targetDoc.createElement("style"); |
| 53 | + newStyle.textContent = styleEl.textContent; |
| 54 | + targetDoc.head.appendChild(newStyle); |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +function syncClasses(from: HTMLElement, to: HTMLElement) { |
| 59 | + to.className = from.className; |
| 60 | + const observer = new MutationObserver(() => { |
| 61 | + to.className = from.className; |
| 62 | + }); |
| 63 | + |
| 64 | + observer.observe(from, { attributes: true, attributeFilter: ["class"] }); |
| 65 | + |
| 66 | + return () => { |
| 67 | + observer.disconnect(); |
| 68 | + }; |
| 69 | +} |
0 commit comments