'use client' import * as React from 'react' import { isTextEntryElement } from '@admin/utils/shared/is-text-entry-element' const FIELD_SELECTOR = 'input:not([type=hidden]), textarea, select, button, [contenteditable=true], [tabindex]:not([tabindex="-1"])' // The keyboard starts sliding up a few hundred ms after focus; no viewport resize by then means none. const KEYBOARD_WAIT_MS = 600 // The fixed `PageHeader` (h-14) plus a 16px gap, the same as `scroll-mt-18`. const HEADER_OFFSET_PX = 72 // Focuses the first visible, enabled control in the panel, skipping `sr-only` label rows. function focusFirstField(panel: HTMLElement) { for (const field of panel.querySelectorAll(FIELD_SELECTOR)) { if (field.closest('.sr-only') || !field.checkVisibility()) { continue } field.focus({ preventScroll: true }) if (document.activeElement === field) { return field } } return null } // Once the keyboard has shrunk the visual viewport, scrolls the field's accordion item to the top // of what is left on screen, unless the field is already fully visible above the keyboard. function revealAboveKeyboard(field: HTMLElement) { const viewport = window.visualViewport if (!viewport || !isTextEntryElement(field)) { return () => {} } const target = field.closest('[data-slot=accordion-item]') ?? field const reveal = () => { stop() const { top, bottom } = field.getBoundingClientRect() const visibleTop = viewport.offsetTop + HEADER_OFFSET_PX const visibleBottom = viewport.offsetTop + viewport.height if (top < visibleTop || bottom > visibleBottom) { target.scrollIntoView({ block: 'start', behavior: 'smooth' }) } } const stop = () => { viewport.removeEventListener('resize', reveal) window.clearTimeout(timeout) } const timeout = window.setTimeout(stop, KEYBOARD_WAIT_MS) viewport.addEventListener('resize', reveal) return stop } // A ref callback for a panel that mounts when it opens: focuses its first field (an input opens the // phone keyboard) and, once the keyboard is up, scrolls the row into the space above it. Focus is // tried in the same commit, inside the tap that opened the panel, so iOS still treats it as // user-initiated, and once more on the next frame if the panel was not visible yet. export function useFocusFirstField() { return React.useCallback((panel: HTMLElement | null) => { if (!panel) { return } let stopReveal = () => {} const focus = () => { const field = focusFirstField(panel) if (field) { stopReveal = revealAboveKeyboard(field) } return field } if (focus()) { return () => stopReveal() } const frame = requestAnimationFrame(focus) return () => { cancelAnimationFrame(frame) stopReveal() } }, []) }