import React, { useEffect, useRef } from 'react' import Snackbar from '@mui/material/Snackbar' import Cookies from 'js-cookie' import SnackbarContent from '@mui/material/SnackbarContent' import { Dialog, DialogActions, DialogContent } from '@mui/material' import { LmComponentRender } from '@LmComponentRender' import { ButtonStoryblok } from '../../typings/generated/components-schema' import { useScrollOnce } from '../../utils/hooks/useScrolledOnce' import { LmSnackbarProps } from './snackbarTypes' import { useAppContext } from '@context/AppContext' export default function LmSnackbar({ content }: LmSnackbarProps) { const { insideStoryblok } = useAppContext() const [open, setOpen] = React.useState(false) const isScrolled = useScrollOnce() const cookieExists = useRef( content.cookie_name ? !!Cookies.get(content.cookie_name) : false ) useEffect(() => { let initalValue = true if ( cookieExists.current || content.auto_show || content.display === 'show_on_scroll' ) { initalValue = false } setOpen(initalValue) }, [content.display, content.auto_show]) useEffect(() => { if (!content.display || !isScrolled) { return } if (content.display === 'show_on_scroll' && !cookieExists.current) { setOpen(true) } else if (content.display === 'hide_on_scroll') { setOpen(false) } }, [isScrolled, content.display]) useEffect(() => { if (!content.auto_close) { return undefined } const timer = setTimeout(() => { setOpen(false) }, content.auto_close) return () => clearTimeout(timer) }, [content.auto_close]) useEffect(() => { if (!content.auto_show && !cookieExists.current) { return undefined } const timer = setTimeout(() => { setOpen(true) }, content.auto_show) return () => clearTimeout(timer) }, [content.auto_show]) const handleAccept = () => { setOpen(false) if (content.cookie_name) { const cookieOptions: Cookies.CookieAttributes = { expires: content?.expire_in_days ? Number(content.expire_in_days) : 1, sameSite: 'lax', secure: window.location ? window.location.protocol === 'https:' : true } Cookies.set(content.cookie_name, 'true', cookieOptions) cookieExists.current = true } } if (cookieExists.current && !insideStoryblok) { return null } return content.dialog ? ( setOpen(false)} >
{(content?.close_action || []).map((blok) => ( ))}
{(content?.descriptions || []).map((blok) => ( ))} {(content?.additional_actions || []).map((blok) => ( ))}
) : ( {(content?.descriptions || []).map((blok) => ( ))} } action={ <> {(content?.additional_actions || []).map((blok) => ( ))} {(content?.close_action || []).map((blok) => ( ))} } /> ) }