2023-01-27 15:21:19 +00:00
|
|
|
import { AppActionsHandler } from "@dashboard/apps/components/AppFrame/appActionsHandler";
|
2022-08-10 13:26:09 +00:00
|
|
|
import {
|
|
|
|
Actions,
|
|
|
|
DispatchResponseEvent,
|
|
|
|
Events,
|
2022-09-06 11:11:06 +00:00
|
|
|
} from "@saleor/app-sdk/app-bridge";
|
2021-08-20 13:58:53 +00:00
|
|
|
import React from "react";
|
2022-07-05 08:39:58 +00:00
|
|
|
|
2021-08-20 13:58:53 +00:00
|
|
|
export const useAppActions = (
|
2022-12-29 12:51:54 +00:00
|
|
|
frameEl: React.MutableRefObject<HTMLIFrameElement | null>,
|
2022-06-21 09:36:55 +00:00
|
|
|
appOrigin: string,
|
2022-07-05 08:39:58 +00:00
|
|
|
appId: string,
|
2021-08-20 13:58:53 +00:00
|
|
|
) => {
|
2023-01-27 15:21:19 +00:00
|
|
|
const { handle: handleNotification } =
|
|
|
|
AppActionsHandler.useHandleNotificationAction();
|
|
|
|
const { handle: handleUpdateRouting } =
|
|
|
|
AppActionsHandler.useHandleUpdateRoutingAction(appId);
|
|
|
|
const { handle: handleRedirect } =
|
|
|
|
AppActionsHandler.useHandleRedirectAction(appId);
|
|
|
|
|
|
|
|
const handleAction = (action: Actions | undefined): DispatchResponseEvent => {
|
2021-08-20 13:58:53 +00:00
|
|
|
switch (action?.type) {
|
2022-08-10 13:26:09 +00:00
|
|
|
case "notification": {
|
2023-01-27 15:21:19 +00:00
|
|
|
return handleNotification(action);
|
2022-08-10 13:26:09 +00:00
|
|
|
}
|
2021-08-20 13:58:53 +00:00
|
|
|
case "redirect": {
|
2023-01-27 15:21:19 +00:00
|
|
|
return handleRedirect(action);
|
2021-08-20 13:58:53 +00:00
|
|
|
}
|
2022-11-22 09:29:29 +00:00
|
|
|
case "updateRouting": {
|
2023-01-27 15:21:19 +00:00
|
|
|
return handleUpdateRouting(action);
|
|
|
|
}
|
|
|
|
case "notifyReady": {
|
|
|
|
console.warn("Not implemented");
|
2022-11-22 09:29:29 +00:00
|
|
|
}
|
2021-08-20 13:58:53 +00:00
|
|
|
default: {
|
2022-08-10 13:26:09 +00:00
|
|
|
throw new Error("Unknown action type");
|
2021-08-20 13:58:53 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const postToExtension = (event: Events) => {
|
2022-12-29 12:51:54 +00:00
|
|
|
if (frameEl?.current?.contentWindow) {
|
2021-08-20 13:58:53 +00:00
|
|
|
frameEl.current.contentWindow.postMessage(event, appOrigin);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
React.useEffect(() => {
|
|
|
|
const handler = (event: MessageEvent<Actions>) => {
|
|
|
|
if (event.origin === appOrigin) {
|
2023-01-27 15:21:19 +00:00
|
|
|
const response = handleAction(event.data);
|
2021-08-20 13:58:53 +00:00
|
|
|
|
|
|
|
postToExtension(response);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
window.addEventListener("message", handler);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
window.removeEventListener("message", handler);
|
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return {
|
2022-06-21 09:36:55 +00:00
|
|
|
postToExtension,
|
2021-08-20 13:58:53 +00:00
|
|
|
};
|
|
|
|
};
|