0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-22 18:17:52 +00:00

fix mutation observer integration

This commit is contained in:
Víctor Losada Hernández
2024-10-17 23:38:11 +02:00
parent 9a4473526a
commit d872a496a7

View File

@@ -77,40 +77,45 @@ const BrewRenderer = (props)=>{
rawPages = props.text.split(/^\\page$/gm); rawPages = props.text.split(/^\\page$/gm);
} }
useEffect(()=>{ useEffect(() => {
const iframeDoc = document.getElementById('BrewRenderer'); const iframe = document.getElementById('BrewRenderer');
const hash = window.location.hash; const hash = window.location.hash;
console.log('Hash: ', hash || 'There is no hash');
console.log(iframeDoc || 'no iframe yet');
if(hash && iframeDoc) {
const anchor = iframeDoc.querySelector(hash);
if(anchor) { const scrollToHash = () => {
anchor.scrollIntoView(); const iframeDoc = iframe?.contentDocument || iframe?.contentWindow?.document;
let anchor = iframeDoc.querySelector(hash);
if (anchor) {
anchor.scrollIntoView({ behavior: 'smooth' });
} else { } else {
// Use MutationObserver to wait for the element if it's not immediately available // Use MutationObserver to wait for the element if it's not immediately available
const observer = new MutationObserver((mutations, obs)=>{ const observer = new MutationObserver((mutations, obs) => {
const anchorElement = iframeDoc.querySelector(hash); anchor = iframeDoc.querySelector(hash);
if(anchorElement) { if (anchor) {
anchorElement.scrollIntoView(); anchor.scrollIntoView({ behavior: 'smooth' });
obs.disconnect(); // Stop observing once the element is found obs.disconnect();
} }
}); });
observer.observe(iframeDoc, { if (iframeDoc.body) {
childList : true, observer.observe(iframeDoc.body, {
subtree : true, childList: true,
subtree: true,
}); });
} }
} }
/* };
const elementId = window.location.hash.slice(1);
if(elementId && state.isMounted) { if (hash) {
const element = document.getElementById(elementId); iframe.addEventListener('load', scrollToHash);
element.scrollIntoView({ block: 'start' });
if (iframe.contentDocument?.readyState === 'complete') {
scrollToHash();
} }
*/ }
return ()=>{ return ()=>{
iframe.removeEventListener('load', scrollToHash);
window.removeEventListener('resize', updateSize); window.removeEventListener('resize', updateSize);
}; };
}, []); }, []);