import { useState, useEffect } from 'react' function bindKey(bindKey, handler) { const kHandler = ({ key }) => { if (key === bindKey) handler() } useEffect(() => { if (typeof window !== 'undefined') { window.addEventListener('keydown', kHandler); } return () => { if (typeof window !== 'undefined') { window.removeEventListener('keydown', kHandler); } } }, []); } function setLocationHash(hash) { if (typeof window !== 'undefined') { if (history?.pushState) { history.pushState(null, null, hash); } else { window.location.hash = hash } } } export function Modal({ children, content, title, link, hash, urlHash }) { const modalHash = urlHash.includes('/') ? urlHash.split('/').at(0) : urlHash const [openModal, setOpenModal] = useState(urlHash === hash); const scrollToTimeslot = () => { const timeslotIndex = urlHash.includes('/') && urlHash.split('/').at(1) if (modalHash && timeslotIndex) { const timeSlotId = `${modalHash}-timeslot${Number(timeslotIndex) + 1}` const element = document.getElementById(timeSlotId) element && element.scrollIntoView({ behavior: 'smooth', block: 'center' }); } } const open = () => { if (!openModal) { setLocationHash(hash) setOpenModal(true) } // The modal needs to be open before we can scroll to the timeslot setTimeout(() => { scrollToTimeslot() }, 100); } const close = () => { setLocationHash('#') setOpenModal(false) } useEffect(() => { if (modalHash === hash) { open() } else { setOpenModal(false) } }, [urlHash]); /* TODO: This runs on every modal */ bindKey('Escape', close) return ( <>
{children}
{title}
{content}
{link && Website } Close
) }