Files
pipelines/web/src/mobileViewport.js
T

61 lines
2.9 KiB
JavaScript

// CSS viewport units account for browser toolbars, not reliably for the soft
// keyboard. Use the visual viewport only for a substantial keyboard-sized
// reduction; do not fight pinch zoom, small toolbar changes or user scrolling.
export function mobileViewportState({ width, height, layoutHeight, baselineHeight, scale = 1, offsetTop = 0, editing = false, wasOpen = false }) {
const visible = Number(height);
const baseline = Math.max(Number(layoutHeight) || 0, Number(baselineHeight) || 0);
const keyboard = (editing || wasOpen) && width < 600 && Math.abs(scale - 1) < 0.01 &&
visible > 0 && baseline - visible >= Math.max(100, baseline * 0.2);
return { keyboard, height: keyboard ? Math.round(visible) : null, top: keyboard ? Math.max(0, Math.round(offsetTop)) : 0 };
}
/** Update geometry only: never rebuild DOM, blur an input, or scroll the page. */
export function installMobileViewport(win = window, doc = document) {
const viewport = win.visualViewport;
if (!viewport) return () => {};
const root = doc.documentElement;
let baseline = win.innerHeight;
let width = win.innerWidth;
let open = false;
let frame = null;
function update() {
frame = null;
const active = doc.activeElement;
const editing = Boolean(active?.matches?.("textarea, input:not([type=checkbox]):not([type=radio]):not([type=button]):not([type=submit]), [contenteditable=true]"));
if (width !== win.innerWidth) {
width = win.innerWidth;
baseline = win.innerHeight;
} else if (!editing && !open) {
baseline = Math.max(win.innerHeight, viewport.height);
}
const state = mobileViewportState({ width, height: viewport.height, layoutHeight: win.innerHeight, baselineHeight: baseline, scale: viewport.scale, offsetTop: viewport.offsetTop, editing, wasOpen: open });
open = state.keyboard;
root.classList.toggle("keyboard-open", open);
if (open) {
root.style.setProperty("--keyboard-visible-height", `${state.height}px`);
root.style.setProperty("--keyboard-viewport-top", `${state.top}px`);
} else {
root.style.removeProperty("--keyboard-visible-height");
root.style.removeProperty("--keyboard-viewport-top");
}
}
function schedule() {
if (frame == null) frame = win.requestAnimationFrame(update);
}
for (const event of ["resize", "scroll"]) viewport.addEventListener(event, schedule);
win.addEventListener("resize", schedule);
doc.addEventListener("focusin", schedule);
doc.addEventListener("focusout", schedule);
update();
return () => {
for (const event of ["resize", "scroll"]) viewport.removeEventListener(event, schedule);
win.removeEventListener("resize", schedule);
doc.removeEventListener("focusin", schedule);
doc.removeEventListener("focusout", schedule);
if (frame != null) win.cancelAnimationFrame(frame);
root.classList.remove("keyboard-open");
root.style.removeProperty("--keyboard-visible-height");
root.style.removeProperty("--keyboard-viewport-top");
};
}