|
| 1 | +import { useCallback, useEffect, useRef } from 'react'; |
| 2 | + |
| 3 | +function isTextInput( |
| 4 | + el: EventTarget | null, |
| 5 | +): el is HTMLInputElement | HTMLTextAreaElement { |
| 6 | + if (!el || !(el instanceof HTMLElement)) return false; |
| 7 | + if (el instanceof HTMLTextAreaElement) return true; |
| 8 | + if (el instanceof HTMLInputElement) { |
| 9 | + const type = el.type?.toLowerCase() ?? 'text'; |
| 10 | + return ![ |
| 11 | + 'hidden', |
| 12 | + 'checkbox', |
| 13 | + 'radio', |
| 14 | + 'file', |
| 15 | + 'button', |
| 16 | + 'submit', |
| 17 | + 'reset', |
| 18 | + ].includes(type); |
| 19 | + } |
| 20 | + return false; |
| 21 | +} |
| 22 | + |
| 23 | +/** Prevent scrolling past the last real content row inside the form scroll area. */ |
| 24 | +export function clampScrollTop(el: HTMLElement): void { |
| 25 | + const max = Math.max(0, el.scrollHeight - el.clientHeight); |
| 26 | + if (el.scrollTop > max) { |
| 27 | + el.scrollTop = max; |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +/** |
| 32 | + * Clamps FormLayout scroll when the IME opens and after text field focus. |
| 33 | + * Avoids scrolling into flex filler / padding void above the nav bar. |
| 34 | + */ |
| 35 | +export function useKeyboardScrollClamp<T extends HTMLElement>() { |
| 36 | + const scrollRef = useRef<T | null>(null); |
| 37 | + |
| 38 | + const clamp = useCallback(() => { |
| 39 | + const el = scrollRef.current; |
| 40 | + if (el) clampScrollTop(el); |
| 41 | + }, []); |
| 42 | + |
| 43 | + useEffect(() => { |
| 44 | + const el = scrollRef.current; |
| 45 | + if (!el) return; |
| 46 | + |
| 47 | + const vv = window.visualViewport; |
| 48 | + |
| 49 | + const onViewportChange = () => { |
| 50 | + requestAnimationFrame(clamp); |
| 51 | + }; |
| 52 | + |
| 53 | + const onFocusIn = (event: FocusEvent) => { |
| 54 | + const target = event.target; |
| 55 | + if (!isTextInput(target)) return; |
| 56 | + |
| 57 | + requestAnimationFrame(() => { |
| 58 | + requestAnimationFrame(() => { |
| 59 | + if (target instanceof HTMLElement) { |
| 60 | + try { |
| 61 | + target.scrollIntoView({ block: 'nearest', behavior: 'instant' }); |
| 62 | + } catch { |
| 63 | + target.scrollIntoView({ block: 'nearest' }); |
| 64 | + } |
| 65 | + } |
| 66 | + clamp(); |
| 67 | + }); |
| 68 | + }); |
| 69 | + }; |
| 70 | + |
| 71 | + vv?.addEventListener('resize', onViewportChange); |
| 72 | + vv?.addEventListener('scroll', onViewportChange); |
| 73 | + el.addEventListener('focusin', onFocusIn); |
| 74 | + |
| 75 | + return () => { |
| 76 | + vv?.removeEventListener('resize', onViewportChange); |
| 77 | + vv?.removeEventListener('scroll', onViewportChange); |
| 78 | + el.removeEventListener('focusin', onFocusIn); |
| 79 | + }; |
| 80 | + }, [clamp]); |
| 81 | + |
| 82 | + return scrollRef; |
| 83 | +} |
0 commit comments