|
const queryArg = "section"; |
|
|
|
function syncHFSpacesURLHash(){ |
|
|
|
const urlParams = new URLSearchParams(window.location.search); |
|
const sectionId = urlParams.get(queryArg); |
|
|
|
if (sectionId) { |
|
|
|
const targetElement = document.getElementById(sectionId); |
|
|
|
|
|
if (targetElement) { |
|
targetElement.scrollIntoView(); |
|
history.replaceState(null, null, `#${sectionId}`); |
|
} |
|
} |
|
|
|
updateHashBasedOnHashChange(); |
|
|
|
|
|
let isScrolling = false; |
|
let lastKnownScrollPosition = 0; |
|
|
|
|
|
window.addEventListener('scroll', function() { |
|
lastKnownScrollPosition = window.scrollY; |
|
|
|
if (!isScrolling) { |
|
window.requestAnimationFrame(function() { |
|
updateHashBasedOnScroll(lastKnownScrollPosition); |
|
isScrolling = false; |
|
}); |
|
} |
|
|
|
isScrolling = true; |
|
}); |
|
|
|
|
|
updateHashBasedOnScroll(window.scrollY); |
|
} |
|
|
|
|
|
function updateHashBasedOnScroll(scrollPosition) { |
|
|
|
const elementsWithIds = Array.from(document.querySelectorAll('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]')); |
|
|
|
|
|
if (elementsWithIds.length === 0) return; |
|
|
|
|
|
let closestElement = null; |
|
let closestDistance = Infinity; |
|
const viewportMiddle = scrollPosition + window.innerHeight / 2; |
|
|
|
|
|
elementsWithIds.forEach(element => { |
|
const elementTop = element.getBoundingClientRect().top + scrollPosition; |
|
const distance = Math.abs(elementTop - viewportMiddle); |
|
|
|
if (distance < closestDistance) { |
|
closestDistance = distance; |
|
closestElement = element; |
|
} |
|
}); |
|
|
|
|
|
if (closestElement && closestElement.id) { |
|
|
|
if (window.location.hash !== `#${closestElement.id}`) { |
|
|
|
history.replaceState(null, null, `#${closestElement.id}`); |
|
postMessageToHFSpaces(closestElement.id); |
|
} |
|
} |
|
} |
|
|
|
function updateHashBasedOnHashChange() { |
|
window.addEventListener('hashchange', () => { |
|
const elementId = window.location.hash.slice(1); |
|
postMessageToHFSpaces(elementId); |
|
}); |
|
} |
|
|
|
function postMessageToHFSpaces(elementId){ |
|
const parentOrigin = "https://huggingface.co"; |
|
window.parent.postMessage({ queryString: `${queryArg}=${elementId}` }, parentOrigin); |
|
} |
|
|
|
export { syncHFSpacesURLHash }; |