2021-09-13 14:14:04 +00:00
|
|
|
import useShop from "@saleor/hooks/useShop";
|
2021-08-20 13:58:53 +00:00
|
|
|
import { useTheme } from "@saleor/macaw-ui";
|
2022-06-08 06:44:28 +00:00
|
|
|
import clsx from "clsx";
|
2021-08-20 13:58:53 +00:00
|
|
|
import React from "react";
|
|
|
|
import urlJoin from "url-join";
|
|
|
|
|
|
|
|
import { useStyles } from "./styles";
|
|
|
|
import { useAppActions } from "./useAppActions";
|
|
|
|
|
|
|
|
interface Props {
|
|
|
|
src: string;
|
|
|
|
appToken: string;
|
2022-04-25 16:06:45 +00:00
|
|
|
appId: string;
|
2022-06-08 06:44:28 +00:00
|
|
|
className?: string;
|
2021-08-20 13:58:53 +00:00
|
|
|
onLoad?(): void;
|
|
|
|
onError?(): void;
|
|
|
|
}
|
|
|
|
|
|
|
|
const getOrigin = (url: string) => new URL(url).origin;
|
|
|
|
|
|
|
|
export const AppFrame: React.FC<Props> = ({
|
|
|
|
src,
|
|
|
|
appToken,
|
2022-04-25 16:06:45 +00:00
|
|
|
appId,
|
2022-06-08 06:44:28 +00:00
|
|
|
className,
|
2021-08-20 13:58:53 +00:00
|
|
|
onLoad,
|
2022-06-21 09:36:55 +00:00
|
|
|
onError,
|
2021-08-20 13:58:53 +00:00
|
|
|
}) => {
|
2021-09-13 14:14:04 +00:00
|
|
|
const shop = useShop();
|
2021-08-20 13:58:53 +00:00
|
|
|
const frameRef = React.useRef<HTMLIFrameElement>();
|
|
|
|
const { sendThemeToExtension } = useTheme();
|
|
|
|
const classes = useStyles();
|
|
|
|
const appOrigin = getOrigin(src);
|
|
|
|
const { postToExtension } = useAppActions(frameRef, appOrigin);
|
|
|
|
|
|
|
|
const handleLoad = () => {
|
|
|
|
postToExtension({
|
|
|
|
type: "handshake",
|
|
|
|
payload: {
|
|
|
|
token: appToken,
|
2022-06-21 09:36:55 +00:00
|
|
|
version: 1,
|
|
|
|
},
|
2021-08-20 13:58:53 +00:00
|
|
|
});
|
|
|
|
sendThemeToExtension();
|
|
|
|
|
|
|
|
if (onLoad) {
|
|
|
|
onLoad();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-09-13 14:14:04 +00:00
|
|
|
if (!shop?.domain.host) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2021-08-20 13:58:53 +00:00
|
|
|
return (
|
|
|
|
<iframe
|
|
|
|
ref={frameRef}
|
2022-04-25 16:06:45 +00:00
|
|
|
src={urlJoin(src, `?domain=${shop.domain.host}&id=${appId}`)}
|
2021-08-20 13:58:53 +00:00
|
|
|
onError={onError}
|
|
|
|
onLoad={handleLoad}
|
2022-06-08 06:44:28 +00:00
|
|
|
className={clsx(classes.iframe, className)}
|
2022-03-25 12:39:09 +00:00
|
|
|
sandbox="allow-same-origin allow-forms allow-scripts"
|
2021-08-20 13:58:53 +00:00
|
|
|
/>
|
|
|
|
);
|
|
|
|
};
|