link-stack/apps/link/app/(main)/_components/ZammadWrapper.tsx
2023-09-08 16:34:13 +02:00

132 lines
3.7 KiB
TypeScript

"use client";
import { FC, useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Iframe from "react-iframe";
import { useSession } from "next-auth/react";
import { Box, Grid, CircularProgress } from "@mui/material";
type ZammadWrapperProps = {
path: string;
hideSidebar?: boolean;
};
export const ZammadWrapper: FC<ZammadWrapperProps> = ({
path,
hideSidebar = true,
}) => {
const router = useRouter();
const { data: session } = useSession();
const [authenticated, setAuthenticated] = useState(false);
const [display, setDisplay] = useState("none");
const url = `/zammad${path}`;
const id = url.replace(/[^a-zA-Z0-9]/g, "");
useEffect(() => {
const checkAuthenticated = async () => {
const res = await fetch("/zammad/auth/sso", {
method: "GET",
redirect: "manual",
});
if (res.type === "opaqueredirect") {
setAuthenticated(true);
} else {
setAuthenticated(false);
}
};
checkAuthenticated();
}, [path]);
if (!session) {
console.log("No session");
return (
<Box sx={{ width: "100%" }}>
<Grid
container
direction="column"
sx={{ height: 500 }}
justifyContent="center"
alignContent="center"
alignItems="center"
>
<Grid item>
<CircularProgress size={80} color="success" />
</Grid>
</Grid>
</Box>
);
}
if (session && authenticated) {
console.log("Session and authenticated");
return (
<Iframe
id={id}
url={url}
width="100%"
height="100%"
frameBorder={0}
styles={{ display }}
onLoad={() => {
const linkElement = document.querySelector(
`#${id}`,
) as HTMLIFrameElement;
console.log({ path });
console.log({ id });
console.log({ linkElement });
if (
linkElement.contentDocument &&
linkElement.contentDocument?.querySelector &&
linkElement.contentDocument.querySelector("#navigation") &&
linkElement.contentDocument.querySelector("body")
) {
// @ts-ignore
linkElement.contentDocument.querySelector("#navigation").style =
"display: none";
// @ts-ignore
linkElement.contentDocument.querySelector("body").style =
"font-family: Arial";
if (
hideSidebar &&
linkElement.contentDocument.querySelector(".sidebar")
) {
// @ts-ignore
linkElement.contentDocument.querySelector(".sidebar").style =
"display: none";
}
// @ts-ignore
if (linkElement.contentDocument.querySelector(".overview-header")) {
// @ts-ignore
(
linkElement.contentDocument.querySelector(
".overview-header",
) as any
).style = "display: none";
}
setDisplay("inherit");
if (linkElement.contentWindow) {
linkElement.contentWindow.addEventListener("hashchange", () => {
const hash = linkElement.contentWindow?.location?.hash ?? "";
if (hash.startsWith("#ticket/zoom/")) {
setDisplay("none");
const ticketID = hash.split("/").pop();
router.push(`/tickets/${ticketID}`);
setTimeout(() => {
setDisplay("inherit");
}, 1000);
}
});
}
}
}}
/>
);
}
};