import type { Vue } from 'vue-facing-decorator'; import { Modal as BootstrapModal } from 'bootstrap'; import { globalState } from '../../app/global-state'; type VueType = typeof Vue.prototype; interface IVue extends VueType { } type ModalTarget = BootstrapModal | HTMLElement | Element; interface ModalDisplayArgs { modal: ModalTarget; data?: T; onHidden?: (response: ModalResponseData) => void; onShown?: (e: ModalOnShownArgs) => void; onBeforeShown?: (e: ModalOnBeforeShownArgs) => void; } interface ModalHideArgs { modal: ModalTarget; } interface ModalResponseData { data?: T; } export interface ModalOnBeforeShownArgs { instance: IVue; } export interface ModalOnShownArgs { instance: IVue; } export interface OnBeforeShownHook { (args: { modalHandler: BootstrapModal; modalElement: HTMLElement }): void; } interface ModalLifecycleBinding { bound: boolean; onShown: (() => void) | null; onHidden: (() => void) | null; } // Per-element store of the latest onShown/onHidden callbacks. We bind the // element listeners exactly once (lazily) and re-dispatch to whichever // callback was most recently registered, which mirrors the jQuery pattern of // `.off('hidden.bs.modal').on('hidden.bs.modal', ...)` without needing to keep // function references around. const lifecycleBindings = new WeakMap(); // Keyboard focus around an open dialog (see `ModalUtils.trackKeyboardFocus`). const TABBABLE_SELECTOR = [ 'a[href]', 'area[href]', 'button', 'input:not([type="hidden"])', 'select', 'textarea', 'summary', 'iframe', '[tabindex]', '[contenteditable]:not([contenteditable="false"])', ].map(selector => `${selector}:not([tabindex^="-"])`).join(','); // Re-focusing a text field after the dialog closes would open the on-screen keyboard on a phone. const TEXT_ENTRY_SELECTOR = 'input:not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="checkbox"]):not([type="radio"]), select, textarea, [contenteditable]:not([contenteditable="false"])'; // A container that spans the page says nothing about where a control went (see `getContainers`). const PAGE_LEVEL_SELECTOR = 'body, main, header, nav, footer, aside, [role="main"], [role="banner"], [role="navigation"], [role="contentinfo"], [role="complementary"]'; interface FocusReturnTarget { opener: HTMLElement; /** The opener's containers below the page level, nearest first: what is left of them tells where its control went. */ containers: HTMLElement[]; } const keyboardFocusBound = new WeakSet(); const focusReturnTargets = new WeakMap(); // A dialog on a touch device carries `data-bs-focus="false"` (see `modal.tsx`): Bootstrap neither moves the focus into it // nor keeps it there — `trackKeyboardFocus` does both. Bootstrap would focus the dialog box once it has shown and pull back // any focus that leaves it, taking the focus (and the on-screen keyboard with it) from a text field focused in the tap // that opened the dialog: the stand-in field that raises the keyboard of a sheet's search box on iOS, a field that // opens a sheet as it is typed in. const keepsOwnFocus = (modalElement: HTMLElement): boolean => modalElement.getAttribute('data-bs-focus') === 'false'; // The open dialogs that keep their own focus, the one shown last on top. const focusKeepingDialogs: HTMLElement[] = []; // Input types nobody types into: focus on them holds no on-screen keyboard. const NON_TEXT_INPUT_TYPES = new Set([ 'button', 'checkbox', 'color', 'file', 'hidden', 'image', 'radio', 'range', 'reset', 'submit', ]); // Whether focus on `el` holds the on-screen keyboard up: moving the focus to anything but a text field closes it. const holdsSoftKeyboard = (el: Element | null): boolean => { if (el instanceof HTMLInputElement) { return !el.readOnly && !el.disabled && !NON_TEXT_INPUT_TYPES.has(el.type); } if (el instanceof HTMLTextAreaElement) { return !el.readOnly && !el.disabled; } return el instanceof HTMLElement && el.isContentEditable; }; // A focus that leaves the dialog on top goes back to the dialog box, as Bootstrap's focus trap has it on a desktop — // unless it went into a field that holds the on-screen keyboard, or into another open dialog that minds its own focus: // one of Bootstrap's, one still fading in above this one, or a modal layer of the app's own that is not a Bootstrap // dialog at all (an onboarding tour's card over the sheet it is explaining). The dialogs below this one are modal too, // but they are in the list, so a focus that reaches them is still brought back. const keepFocusInTopDialog = (e: FocusEvent): void => { const top = focusKeepingDialogs[focusKeepingDialogs.length - 1]; const target = e.target; if (top == null || !(target instanceof Element) || top.contains(target) || holdsSoftKeyboard(target)) { return; } const dialog = target.closest('.modal.show, [aria-modal="true"]'); if (dialog != null && !focusKeepingDialogs.includes(dialog)) { return; } top.focus({ preventScroll: true }); }; const stopKeepingFocus = (modalElement: HTMLElement): void => { const index = focusKeepingDialogs.indexOf(modalElement); if (index === -1) { return; } focusKeepingDialogs.splice(index, 1); if (focusKeepingDialogs.length === 0) { document.removeEventListener('focusin', keepFocusInTopDialog); } }; // The dialog has shown: the focus goes to the dialog box (which raises no on-screen keyboard) unless it is in the dialog // already or holds the on-screen keyboard, and it is kept in the dialog from now on. const keepFocusIn = (modalElement: HTMLElement): void => { stopKeepingFocus(modalElement); focusKeepingDialogs.push(modalElement); if (focusKeepingDialogs.length === 1) { document.addEventListener('focusin', keepFocusInTopDialog); } const active = document.activeElement; if (!modalElement.contains(active) && !holdsSoftKeyboard(active)) { modalElement.focus({ preventScroll: true }); } }; const isRendered = (el: Element): boolean => el.getClientRects().length > 0 && getComputedStyle(el).visibility === 'visible'; const isTabbable = (el: HTMLElement): boolean => (el as HTMLButtonElement).disabled != true && isRendered(el); const getTabbableChildren = (root: HTMLElement): HTMLElement[] => Array.from(root.querySelectorAll(TABBABLE_SELECTOR)).filter(isTabbable); const isKeyboardFocused = (el: HTMLElement): boolean => { try { return el.matches(':focus-visible'); } catch { // An engine without `:focus-visible` keeps the previous behaviour (no focus return). return false; } }; // Tab and Shift+Tab wrap inside the open dialog instead of first leaving it for the page behind it. const keepTabInside = (modalElement: HTMLElement, e: KeyboardEvent): void => { if (e.key !== 'Tab' || e.defaultPrevented) { return; } const tabbable = getTabbableChildren(modalElement); if (tabbable.length === 0) { return; } const first = tabbable[0]; const last = tabbable[tabbable.length - 1]; const active = document.activeElement; if (e.shiftKey && (active === first || active === modalElement)) { e.preventDefault(); last.focus(); } else if (!e.shiftKey && active === last) { e.preventDefault(); first.focus(); } }; // The opener may have become unfocusable while the dialog was open — e.g. a button in a popover that // collapsed when the dialog opened. Then the collapsed disclosure control next to the hidden part (the // popover's own toggle) is the control the user came from. const findCollapsedDisclosure = (opener: HTMLElement): HTMLElement | null => { let container = opener.parentElement; while (container != null && container !== document.body && !isRendered(container)) { container = container.parentElement; } if (container == null || container === document.body) { return null; } return Array.from(container.querySelectorAll('[aria-expanded="false"]')).find(isTabbable) ?? null; }; // The containers of the opener below the page level, nearest first (see `FocusReturnTarget`). const getContainers = (opener: HTMLElement): HTMLElement[] => { const containers: HTMLElement[] = []; for (let parent = opener.parentElement; parent != null && !parent.matches(PAGE_LEVEL_SELECTOR); parent = parent.parentElement) { containers.push(parent); } return containers; }; // The opener left the page while the dialog was open — the sign-in that closed it re-rendered the header, and its // "Sign in" control is now "My account". The control that took its place is the first one in the nearest container // of the opener that survived. A container that spans the page is not looked at: guessing a control there would // be a jump, not a return. const findReplacementControl = (containers: HTMLElement[]): HTMLElement | null => { const survivor = containers.find(container => container.isConnected && isRendered(container)); return survivor == null ? null : getTabbableChildren(survivor)[0] ?? null; }; const returnFocus = (modalElement: HTMLElement): void => { const target = focusReturnTargets.get(modalElement); focusReturnTargets.delete(modalElement); if (target == null) { return; } // Never take focus away from something the app focused on purpose when the dialog closed. const active = document.activeElement; if (active != null && active !== document.body && !modalElement.contains(active)) { return; } const { opener } = target; if (!opener.isConnected) { findReplacementControl(target.containers)?.focus({ preventScroll: true }); return; } opener.focus({ preventScroll: true }); if (document.activeElement !== opener) { findCollapsedDisclosure(opener)?.focus({ preventScroll: true }); } }; const ensureLifecycleListeners = (el: HTMLElement): ModalLifecycleBinding => { let binding = lifecycleBindings.get(el); if (binding == null) { binding = { bound: false, onShown: null, onHidden: null }; lifecycleBindings.set(el, binding); } if (!binding.bound) { binding.bound = true; el.addEventListener('shown.bs.modal', () => { binding!.onShown?.(); }); el.addEventListener('hidden.bs.modal', () => { binding!.onHidden?.(); }); } return binding; }; const resolveModal = (target: ModalTarget): { instance: BootstrapModal; element: HTMLElement } | null => { if (target == null) { return null; } // Bootstrap's Modal instance exposes `_element` (the underlying HTMLElement). const maybeBootstrap = target as any; if (maybeBootstrap._element instanceof HTMLElement) { return { instance: maybeBootstrap as BootstrapModal, element: maybeBootstrap._element }; } if (target instanceof HTMLElement) { return { instance: BootstrapModal.getOrCreateInstance(target), element: target }; } if (target instanceof Element) { return { instance: BootstrapModal.getOrCreateInstance(target), element: target as HTMLElement }; } return null; }; export class ModalUtils { private static _onBeforeShownHandlers: OnBeforeShownHook[]; static addOnBeforeShownHandler(handler: OnBeforeShownHook) { if (ModalUtils._onBeforeShownHandlers == null) { ModalUtils._onBeforeShownHandlers = []; } ModalUtils._onBeforeShownHandlers.push(handler); } static showModal(instance: IVue, dataArgs: ModalDisplayArgs | IVue | Element): void { let args: ModalDisplayArgs = dataArgs as any; if (args.modal == null) { args = { modal: args as any } as ModalDisplayArgs; } const resolved = resolveModal(args.modal); if (resolved == null) { console.error('Modal context not specified'); return; } let nextTick = instance?.$nextTick; if (nextTick == null) { nextTick = (cb) => { cb(); }; } nextTick(() => { const { instance: modalHandler, element: modalElement } = resolved; const binding = ensureLifecycleListeners(modalElement); binding.onHidden = args.onHidden ? () => args.onHidden!({ data: args.data }) : null; binding.onShown = args.onShown ? () => args.onShown!({ instance }) : null; if (args.onBeforeShown != null) { args.onBeforeShown({ instance }); } if (ModalUtils._onBeforeShownHandlers) { for (const hook of ModalUtils._onBeforeShownHandlers) { hook({ modalHandler, modalElement }); } } ModalUtils.trackKeyboardFocus(modalElement, document.activeElement); modalHandler.show(); }); } /** * Keyboard focus around a dialog (WCAG 2.4.3). Call it right before the dialog is shown, while focus is * still on the control that opened it: * - Tab / Shift+Tab wrap inside the open dialog. Before, Shift+Tab on its first control left the dialog for * the page's last control (the browser scrolled the page behind the backdrop to it) until Bootstrap's * focus trap pulled focus back. * - when the dialog is hidden, focus goes back to that control instead of being dropped on . * - on a touch device (the dialog carries `data-bs-focus="false"`, see `modal.tsx`) the focus goes into the dialog * once it has shown and is kept there, as Bootstrap does on a desktop — but a text field that holds the * on-screen keyboard keeps the focus (see `keepsOwnFocus`), wherever that field is: a field behind the dialog * that opened it as it was typed in keeps the keystrokes, the price of the stand-in field iOS needs. * * The return is keyboard-only: the opener is remembered only when it has keyboard focus (`:focus-visible`) and is * not a text field — a text field that opens a dialog gives the focus back itself (the date picker's field, which * must not open its sheet again as it takes it). A tapped opener is not given the focus back: on a touch device the * dialog has taken it, and it ends on once the dialog is gone. */ static trackKeyboardFocus(modalElement: HTMLElement, opener: Element | null): void { // A repeated show() of an open dialog keeps the opener remembered by the first one. if (!modalElement.classList.contains('show')) { const isOpener = opener instanceof HTMLElement && opener !== document.body && !modalElement.contains(opener) && !opener.matches(TEXT_ENTRY_SELECTOR) && isKeyboardFocused(opener); if (isOpener) { focusReturnTargets.set(modalElement, { opener, containers: getContainers(opener) }); } else { focusReturnTargets.delete(modalElement); } } if (keyboardFocusBound.has(modalElement)) { return; } keyboardFocusBound.add(modalElement); modalElement.addEventListener('keydown', e => keepTabInside(modalElement, e)); modalElement.addEventListener('shown.bs.modal', () => { if (keepsOwnFocus(modalElement)) { keepFocusIn(modalElement); } }); // Released before the focus goes back to the opener, which may sit in a dialog below this one. modalElement.addEventListener('hidden.bs.modal', () => stopKeepingFocus(modalElement)); modalElement.addEventListener('hidden.bs.modal', () => returnFocus(modalElement)); } static hideModal(dataArgs: ModalHideArgs | IVue | Element): void { let args: ModalHideArgs = dataArgs as any; if (args.modal == null) { args = { modal: args as any } as ModalHideArgs; } const resolved = resolveModal(args.modal); if (resolved == null) { console.error('Modal context not found'); return; } setTimeout(() => { resolved.instance.hide(); }, 1); } static hideAllOpenModals(): void { const allModals = document.querySelectorAll('.modal.show'); if (allModals.length > 0) { for (let i = 0; i < allModals.length; i++) { const element = allModals[i]; ModalUtils.hideModal(element); } } } static destroyModalInstance(element: string | Element) { if (element == null || !globalState.windowExists) { return; } const targetElement: Element | null = typeof element === 'string' ? document.querySelector(element) : element; if (targetElement == null) { return; } // A dialog disposed while open (its page went away) never fires `hidden.bs.modal`. stopKeepingFocus(targetElement as HTMLElement); // Clear our cached onShown/onHidden so a future showModal() doesn't fire // stale callbacks against a disposed component. const binding = lifecycleBindings.get(targetElement as HTMLElement); if (binding != null) { binding.onShown = null; binding.onHidden = null; } const modalInstance = BootstrapModal.getInstance(targetElement); if (modalInstance == null) { return; } targetElement.classList.remove('show'); const scrollBar = (modalInstance as any)._scrollBar; modalInstance.dispose(); const openModal = document.querySelectorAll('.modal.show'); if (openModal.length == 0) { document.body.classList.remove('modal-open'); scrollBar?.reset(); } } static handleModalMountDelay(instance: IVue, cb: () => void) { if (instance?.$el?.closest('.modal-dialog')) { instance.$nextTick(() => { instance.$nextTick(() => { setTimeout(() => { cb(); }, 100); }); }); } else { cb(); } } static bindModalBottomSheetHandle(getModal: () => HTMLElement, hideModal: () => void) { if ((getModal() as any)?._dragBound) { return; } setTimeout(() => { const modal = getModal() as HTMLElement; const modalDialog = modal.querySelector('.modal-dialog') as HTMLElement; const dragHandle = modal.querySelector('.drag-handle'); let startY = 0; let currentY = 0; let isDragging = false; const threshold = 100; const cancelDragging = () => { isDragging = false; modal.classList.remove('modal-is-dragging'); }; const startDragging = () => { isDragging = true; modal.classList.add('modal-is-dragging'); }; const onMove = (y) => { const translateY = Math.max(y - startY, 0); modalDialog.style.transform = `translateY(${translateY}px)`; }; const endDrag = () => { cancelDragging(); const dragDistance = currentY - startY; if (dragDistance > threshold) { hideModal(); // Bootstrap silently ignores hide() while a show/hide transition is running // (_isTransitioning) — e.g. when the user catches the sheet mid slide-up and // flings it down. The dialog would then stay stranded off-screen on the inline // drag transform, under a live backdrop (blur-locked screen). Once transitions // have settled, retry the hide if the drag transform is still applied; a // successful hide resets the transform via hidden.bs.modal, so a legitimately // re-shown modal is never closed by this retry. setTimeout(() => { if (modal.classList.contains('show') && modalDialog.style.transform !== '') { hideModal(); } }, 400); } else { modalDialog.style.transform = ''; } }; // Touch events dragHandle.addEventListener('touchstart', (e) => { startY = (e as TouchEvent).touches[0].clientY; // A tap fires no touchmove — without this reset, currentY kept the previous // gesture's end position and a mere tap could read as a >threshold "drag". currentY = startY; startDragging(); }); dragHandle.addEventListener('touchmove', (e) => { if (!isDragging) { return; } currentY = (e as TouchEvent).touches[0].clientY; onMove(currentY); }); dragHandle.addEventListener('touchend', endDrag); // Mouse events dragHandle.addEventListener('mousedown', (e) => { startY = (e as MouseEvent).clientY; // Same stale-currentY guard as touchstart: a click without mousemove must // compute a zero drag distance, not inherit the previous gesture's end. currentY = startY; startDragging(); const onMouseMove = (e) => { if (!isDragging) { return; } currentY = e.clientY; onMove(currentY); e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); }; const onMouseUp = () => { endDrag(); globalState.removeEventListener('mousemove', onMouseMove); globalState.removeEventListener('mouseup', onMouseUp); }; globalState.addEventListener('mousemove', onMouseMove); globalState.addEventListener('mouseup', onMouseUp); }); // Reset on modal hide modal.addEventListener('hidden.bs.modal', () => { cancelDragging(); modalDialog.style.transform = ''; }); (modal as any)._dragBound = true; }, 100); } }