import { PortalUtils } from './utils'; // `import.meta.env.SSR` is statically replaced by Vite. Declared here because not every // consumer loads `vite/client` types (gopass-eshop does not); the members match Vite's // own declarations, so both merge where they are loaded. declare global { interface ImportMetaEnv { SSR: boolean; } interface ImportMeta { readonly env: ImportMetaEnv; } } interface BootstrapScrollBar { hide: () => void; reset: () => void; } interface BootstrapFocusTrap { activate: () => void; deactivate: () => void; } type BootstrapHelpers = [ new () => BootstrapScrollBar, new (config: { trapElement: HTMLElement; autofocus: boolean }) => BootstrapFocusTrap, ]; /** * Bootstrap's entry does not export ScrollBarHelper / FocusTrap, so they come from * `bootstrap/js/src/util/*`: lazily, and only outside SSR. SSR builds that alias * `bootstrap` to a shim (gopass-eshop) rewrite every `bootstrap/...` subpath as well and * cannot resolve these, whether imported statically or dynamically. Both Vite 6 and 8 * drop a constant-false ternary branch before resolving it; Vite 6 does not drop code * after an early `return`, so keep this shape. * * The `js/src` copy also brings its own EventHandler, which matters: `FocusTrap.activate()` * removes every `.bs.focustrap` listener of its EventHandler, so sharing the entry's copy * would disable the focus trap of an enclosing Bootstrap modal. */ const loadBootstrapHelpers = (): Promise => (import.meta.env.SSR ? Promise.resolve(null) : Promise.all([ import('bootstrap/js/src/util/scrollbar.js'), import('bootstrap/js/src/util/focustrap.js'), ]).then(([ scrollBar, focusTrap, ]): BootstrapHelpers => [ scrollBar.default, focusTrap.default, ])); /** Holder count and page offset of the iOS body pin, kept on like Bootstrap's `data-bs-*` bookkeeping. */ const PIN_HOLDERS_ATTRIBUTE = 'data-modal-scroll-lock-holders'; const PIN_OFFSET_ATTRIBUTE = 'data-modal-scroll-lock-offset'; const PIN_STYLE_PROPERTIES = [ 'position', 'top', 'left', 'right', 'width', ]; /** * iOS Safari still scrolls an `overflow: hidden` page while its toolbar is collapsed, and * pans the page to reveal a focused input. Pinning with `position: fixed` (offset * by the current scroll) leaves nothing to scroll. Counted, so overlapping locks (a panel * still animating out while the next one opens) share a single pin. */ const pinBody = (): void => { const body = document.body; const holders = Number(body.getAttribute(PIN_HOLDERS_ATTRIBUTE) ?? 0); body.setAttribute(PIN_HOLDERS_ATTRIBUTE, String(holders + 1)); if (holders > 0) { return; } const offset = window.scrollY; body.setAttribute(PIN_OFFSET_ATTRIBUTE, String(offset)); body.style.position = 'fixed'; body.style.top = `-${offset}px`; body.style.left = '0'; body.style.right = '0'; body.style.width = '100%'; }; const unpinBody = (): void => { const body = document.body; const holders = Number(body.getAttribute(PIN_HOLDERS_ATTRIBUTE) ?? 0); if (holders < 1) { return; } if (holders > 1) { body.setAttribute(PIN_HOLDERS_ATTRIBUTE, String(holders - 1)); return; } const offset = Number(body.getAttribute(PIN_OFFSET_ATTRIBUTE) ?? 0); body.removeAttribute(PIN_HOLDERS_ATTRIBUTE); body.removeAttribute(PIN_OFFSET_ATTRIBUTE); PIN_STYLE_PROPERTIES.forEach(property => body.style.removeProperty(property)); // `instant`: Bootstrap's reboot sets `scroll-behavior: smooth`, which would visibly scroll the page back. window.scrollTo({ top: offset, left: 0, behavior: 'instant' }); }; /** * Locks the page behind a modal-like overlay the way Bootstrap's Modal does, using * Bootstrap's own helpers: `ScrollBarHelper` hides the body scrollbar (padding-compensated, * so the page does not shift) and `FocusTrap` keeps focus inside the overlay. On iOS the * body is pinned as well, see `pinBody`. * * Follows Modal's ordering: `lock()` is `show()`, `releaseFocus()` is the start of `hide()` * (focus is handed back while an exit animation still runs) and `unlock()` is the finished * hide / `dispose()`. All methods are idempotent, so every teardown path may call `unlock()` * regardless of whether another did. The Bootstrap helpers arrive asynchronously (see * `loadBootstrapHelpers`); a lock released before they load never applies them. */ export default class ModalScrollLock { private readonly trapElement: HTMLElement; private scrollBar: BootstrapScrollBar | null = null; private focusTrap: BootstrapFocusTrap | null = null; private isLocked = false; private isPinned = false; private isFocusTrapWanted = false; constructor(trapElement: HTMLElement) { this.trapElement = trapElement; } lock(): void { this.isFocusTrapWanted = true; if (!this.isLocked) { this.isLocked = true; // Synchronous, unlike the Bootstrap helpers: the pin must be in place before the // overlay's input takes focus, or Safari pans the page to reveal that input. if (PortalUtils.isIOS()) { pinBody(); this.isPinned = true; } } // Rejections (a failed chunk load) stay unhandled on purpose, so ChunkLoadRecovery can heal them. this.applyBootstrapHelpers(); } releaseFocus(): void { this.isFocusTrapWanted = false; this.focusTrap?.deactivate(); } unlock(): void { this.releaseFocus(); if (!this.isLocked) { return; } this.isLocked = false; if (this.isPinned) { this.isPinned = false; unpinBody(); } this.scrollBar?.reset(); this.scrollBar = null; } private async applyBootstrapHelpers(): Promise { const helpers = await loadBootstrapHelpers(); if (helpers == null || !this.isLocked) { return; } const [ ScrollBarHelper, FocusTrap, ] = helpers; // ScrollBarHelper.hide() must not run twice: the second call would save the // already-locked `overflow: hidden` as the value reset() restores. if (this.scrollBar == null) { this.scrollBar = new ScrollBarHelper(); this.scrollBar.hide(); } if (this.isFocusTrapWanted) { // No autofocus: the owner decides which element inside the overlay gets focus. this.focusTrap ??= new FocusTrap({ trapElement: this.trapElement, autofocus: false }); this.focusTrap.activate(); } } }