space-review / interface.js
fffiloni's picture
Keep the Hub viewport in sync with expanding reviews
332b637 verified
Raw History Blame Contribute Delete
8 kB
(() => {
function connectHubFrame(shell) {
if (window.parent === window) return null;
const hubOrigins = ["https://huggingface.co", "https://hf.co"];
const layout = shell.closest(".gradio-container > .main");
let hubFrame = hubOrigins.some(origin => document.referrer.startsWith(origin + "/"));
let resizeFrame = 0;
function fitHubFrame() {
const resizer = window.parentIFrame;
if (!hubFrame || !resizer?.size) return;
// The Hub scrolls the outer page. Measure the app itself, independently of iframe height.
document.documentElement.style.overflowY = "visible";
const padding = layout ? parseFloat(getComputedStyle(layout).paddingBottom) : 0;
const contentHeight = Math.ceil(shell.getBoundingClientRect().bottom + window.scrollY + padding);
if (contentHeight > window.innerHeight + 1) resizer.size(contentHeight);
}
function scheduleFrameFit() {
if (!hubFrame || resizeFrame) return;
resizeFrame = requestAnimationFrame(() => {
resizeFrame = 0;
fitHubFrame();
});
}
new ResizeObserver(scheduleFrameFit).observe(shell);
window.addEventListener("resize", scheduleFrameFit);
window.addEventListener("pageshow", scheduleFrameFit);
window.addEventListener("message", (event) => {
if (event.source !== window.parent || !hubOrigins.includes(event.origin)) return;
if (typeof event.data !== "string" || !event.data.startsWith("[iFrameSizer]")) return;
hubFrame = true;
scheduleFrameFit();
});
scheduleFrameFit();
return (target) => {
const resizer = window.parentIFrame;
if (!hubFrame || !resizer?.scrollToOffset) return false;
fitHubFrame();
const margin = parseFloat(getComputedStyle(target).scrollMarginTop) || 0;
const offset = Math.max(0, Math.round(target.getBoundingClientRect().top + window.scrollY - margin));
resizer.scrollToOffset(0, offset);
return true;
};
}
function bindReviewPage(shell) {
let waiting = false;
let movedWhileWaiting = false;
let seenTurn = 0;
let frame = 0;
const motion = window.matchMedia("(prefers-reduced-motion: reduce)");
const sweeps = new Map();
const revealInHub = connectHubFrame(shell);
function syncLoadingSweeps() {
for (const [ghost, animation] of sweeps) {
if (motion.matches || !ghost.isConnected) {
animation.cancel();
sweeps.delete(ghost);
}
}
if (motion.matches) return;
for (const ghost of shell.querySelectorAll(".sr-ghost")) {
if (!sweeps.has(ghost)) {
sweeps.set(ghost, ghost.animate(
[{ backgroundPosition: "100% 0" }, { backgroundPosition: "0% 0" }],
{ duration: 1450, iterations: Infinity },
));
}
}
}
function syncBadgeSpacing() {
const badge = document.getElementById("huggingface-space-header");
shell.classList.toggle("sr-has-space-badge", Boolean(badge?.getClientRects().length));
}
new MutationObserver(syncBadgeSpacing).observe(document.body, { childList: true });
syncBadgeSpacing();
motion.addEventListener("change", syncLoadingSweeps);
const keepReading = () => {
if (waiting) movedWhileWaiting = true;
};
const revealReply = (reply) => {
if (!revealInHub?.(reply)) reply.scrollIntoView({ block: "start", inline: "nearest", behavior: "instant" });
};
function showReviewPass(article, index) {
const total = Number(article.dataset.reviewTotal);
if (index < 1 || index > total) return;
article.dataset.reviewCurrent = String(index);
for (const part of article.querySelectorAll("[data-review-part]")) {
part.hidden = Number(part.dataset.reviewPart) !== index;
}
article.querySelector("[data-review-position]").textContent = index;
article.querySelector('[data-review-step="-1"]').setAttribute("aria-disabled", String(index === 1));
article.querySelector('[data-review-step="1"]').setAttribute("aria-disabled", String(index === total));
}
window.addEventListener("wheel", keepReading, { capture: true, passive: true });
window.addEventListener("touchmove", keepReading, { capture: true, passive: true });
window.addEventListener("keydown", (event) => {
if (event.target instanceof Element && event.target.closest("input, textarea, select, [contenteditable]")) return;
if (["ArrowDown", "ArrowUp", "PageDown", "PageUp", "Home", "End", " "].includes(event.key)) keepReading();
}, true);
shell.addEventListener("click", (event) => {
if (!(event.target instanceof Element)) return;
const step = event.target.closest("[data-review-step]");
if (step) {
const article = step.closest("[data-review-current]");
showReviewPass(article, Number(article.dataset.reviewCurrent) + Number(step.dataset.reviewStep));
return;
}
const link = event.target.closest('.sr-latest-link, .sr-pass-link, a[href="#sr-captures"]');
if (!link) return;
const destination = document.getElementById(link.hash.slice(1));
if (!destination) return;
event.preventDefault();
keepReading();
if (link.dataset.reviewJump) {
showReviewPass(destination.closest("[data-review-current]"), Number(link.dataset.reviewJump));
}
destination.tabIndex = -1;
destination.focus({ preventScroll: true });
revealReply(destination);
}, true);
function updatePage() {
frame = 0;
syncLoadingSweeps();
const button = shell.querySelector("#review-options button.label-wrap");
if (button) {
const open = button.classList.contains("open");
button.setAttribute("aria-controls", "options-fields");
button.setAttribute("aria-expanded", String(open));
if (open) button.removeAttribute("aria-describedby");
else button.setAttribute("aria-describedby", "sr-options-preview");
}
const latest = shell.querySelector("#sr-latest-reply");
const turn = Number(latest?.dataset.turn || 0);
const pending = shell.querySelector("#followup-status [role='status']:not(.sr-pass-ready)");
if (pending) {
if (!waiting) movedWhileWaiting = false;
waiting = true;
return;
}
if (waiting && !movedWhileWaiting && turn > seenTurn) {
revealReply(latest);
}
waiting = false;
seenTurn = turn;
}
new MutationObserver(() => {
if (!frame) frame = requestAnimationFrame(updatePage);
}).observe(shell, { childList: true, subtree: true, attributes: true, attributeFilter: ["class"] });
updatePage();
}
const shell = document.querySelector("#shell");
if (shell) {
bindReviewPage(shell);
} else {
const mount = new MutationObserver(() => {
const page = document.querySelector("#shell");
if (page) {
mount.disconnect();
bindReviewPage(page);
}
});
mount.observe(document.body, { childList: true, subtree: true });
}
})();