|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useEffect, useMemo, useState } from "react"; |
| 4 | + |
| 5 | +interface SyncedAppIframeProps { |
| 6 | + srcPath: string; |
| 7 | + title: string; |
| 8 | + height?: string; |
| 9 | + initialQuery?: string; |
| 10 | +} |
| 11 | + |
| 12 | +export default function SyncedAppIframe({ |
| 13 | + srcPath, |
| 14 | + title, |
| 15 | + height = "calc(100vh - 58px)", |
| 16 | + initialQuery = "", |
| 17 | +}: SyncedAppIframeProps) { |
| 18 | + const [query, setQuery] = useState(initialQuery); |
| 19 | + |
| 20 | + const iframeUrl = useMemo(() => { |
| 21 | + return query ? `${srcPath}?${query}` : srcPath; |
| 22 | + }, [query, srcPath]); |
| 23 | + |
| 24 | + useEffect(() => { |
| 25 | + const basePath = srcPath.replace(/\/embed$/, ""); |
| 26 | + |
| 27 | + const syncQueryFromLocation = () => { |
| 28 | + const currentQuery = window.location.search.replace(/^\?/, ""); |
| 29 | + setQuery(currentQuery); |
| 30 | + }; |
| 31 | + |
| 32 | + const handleMessage = (event: MessageEvent) => { |
| 33 | + if (event.origin !== window.location.origin) { |
| 34 | + return; |
| 35 | + } |
| 36 | + |
| 37 | + if ( |
| 38 | + event.data?.type === "hashchange" && |
| 39 | + typeof event.data.hash === "string" |
| 40 | + ) { |
| 41 | + const hash = event.data.hash || ""; |
| 42 | + |
| 43 | + if (hash && !hash.startsWith("#")) { |
| 44 | + const subPath = hash.startsWith("/") ? hash : `/${hash}`; |
| 45 | + window.history.replaceState(null, "", `${basePath}${subPath}`); |
| 46 | + } else { |
| 47 | + window.history.replaceState(null, "", `${basePath}${hash}`); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + if ( |
| 52 | + event.data?.type === "urlUpdate" && |
| 53 | + typeof event.data.params === "string" |
| 54 | + ) { |
| 55 | + const query = event.data.params ? `?${event.data.params}` : ""; |
| 56 | + window.history.replaceState(null, "", `${basePath}${query}`); |
| 57 | + setQuery(event.data.params || ""); |
| 58 | + } |
| 59 | + }; |
| 60 | + |
| 61 | + syncQueryFromLocation(); |
| 62 | + window.addEventListener("message", handleMessage); |
| 63 | + window.addEventListener("popstate", syncQueryFromLocation); |
| 64 | + return () => { |
| 65 | + window.removeEventListener("message", handleMessage); |
| 66 | + window.removeEventListener("popstate", syncQueryFromLocation); |
| 67 | + }; |
| 68 | + }, [srcPath]); |
| 69 | + |
| 70 | + return ( |
| 71 | + <iframe |
| 72 | + src={iframeUrl} |
| 73 | + title={title} |
| 74 | + allow="clipboard-write" |
| 75 | + style={{ |
| 76 | + width: "100%", |
| 77 | + height, |
| 78 | + border: "none", |
| 79 | + display: "block", |
| 80 | + }} |
| 81 | + /> |
| 82 | + ); |
| 83 | +} |
0 commit comments