diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 9a49fad..0433c55 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -8,6 +8,7 @@ import { setLang, useLang } from './lib/i18n.js' import { setNav } from './lib/nav.js' import { initBackButton } from './lib/back.js' import { useWakeLock } from './lib/wakelock.js' +import { installViewportGuard } from './lib/viewport-guard.js' import { startFlow } from './sheets.jsx' import Icon from './components/Icon.jsx' import TabBar from './components/TabBar.jsx' @@ -77,6 +78,8 @@ function Shell() { // The position is recorded from scroll events rather than read at route // change, because by then a shorter page may already have clamped it. const pathRef = useRef(loc.pathname) + // iOS leaves the page displaced after the keyboard goes away (see lib/viewport-guard.js). + useEffect(() => installViewportGuard(), []) useEffect(() => { const onScroll = () => { // Modals pins the body while a sheet is open; scrollY is 0 then, not a position. diff --git a/frontend/src/components/Modals.jsx b/frontend/src/components/Modals.jsx index 86ed358..acda36d 100644 --- a/frontend/src/components/Modals.jsx +++ b/frontend/src/components/Modals.jsx @@ -170,6 +170,11 @@ export default function Modals() { return () => { b.position = b.top = b.left = b.right = b.width = '' window.scrollTo(0, y) + // If the sheet closed with the keyboard still up (tap "+" in the picker, then finish), + // iOS scrolls the page again while the keyboard dismisses — after the line above ran. + // Ask once more when that animation is over. The window-level guard in + // lib/viewport-guard.js covers the keyboard closing while a sheet stays open. + window.setTimeout(() => { if (document.body.style.position !== 'fixed') window.scrollTo(0, y) }, 350) } }, [sheets.length > 0]) diff --git a/frontend/src/lib/viewport-guard.js b/frontend/src/lib/viewport-guard.js new file mode 100644 index 0000000..8fd0524 --- /dev/null +++ b/frontend/src/lib/viewport-guard.js @@ -0,0 +1,70 @@ +/* The iOS keyboard leaves the page displaced. + * + * On iOS Safari (and the home-screen PWA) the keyboard does not resize the layout viewport; + * it scrolls the page so the focused field is visible, even when the body is pinned by an + * open sheet. When the keyboard goes away again, the scroll it made is not always undone: + * the layout viewport stays offset inside the screen, everything `position:fixed` — the tab + * bar, the rest timer — sits where the layout viewport ends, i.e. mid-screen, and the page's + * first rows hide under the status bar. It stays like that until something scrolls. + * + * The exercise picker is where it bites: search, tap "+", the sheet stays open, the keyboard + * closes — and the sheet's own restore (Modals.jsx) has not run because nothing closed. So the + * correction lives here, on the window, and fires whenever the keyboard has just gone away or + * a text field lost focus: if the visual viewport is not where the layout viewport is, ask for + * the scroll position we already have. iOS treats that as a scroll and realigns the viewports; + * on every other platform it is a no-op. + */ +const KEYBOARD_MIN_PX = 100 +const SETTLE_MS = 350 // the keyboard's dismiss animation; the offset is only wrong after it + +const isText = el => !!el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable) + +export function viewportDisplacement(win = window) { + const vv = win.visualViewport + if (!vv) return 0 + const offset = vv.offsetTop || 0 + const scrolledPast = (vv.pageTop || 0) - (win.scrollY || 0) + return Math.max(offset, scrolledPast) +} + +export function keyboardOpen(win = window) { + const vv = win.visualViewport + if (!vv) return false + return (win.innerHeight - vv.height) > KEYBOARD_MIN_PX +} + +/** Realign the viewports if iOS left them apart. Returns true when a correction was issued. */ +export function realign(win = window) { + if (keyboardOpen(win)) return false + if (isText(win.document.activeElement)) return false + if (viewportDisplacement(win) <= 1) return false + win.scrollTo(win.scrollX || 0, win.scrollY || 0) + return true +} + +export function installViewportGuard(win = window) { + const vv = win.visualViewport + if (!vv) return () => {} + let wasOpen = keyboardOpen(win) + const timers = new Set() + const later = (fn, ms) => { const t = win.setTimeout(() => { timers.delete(t); fn() }, ms); timers.add(t) } + const settle = () => { realign(win); later(() => realign(win), SETTLE_MS) } + + const onResize = () => { + const open = keyboardOpen(win) + if (wasOpen && !open) settle() + wasOpen = open + } + const onScroll = () => { if (!wasOpen) realign(win) } + const onFocusOut = e => { if (isText(e.target)) settle() } + + vv.addEventListener('resize', onResize) + vv.addEventListener('scroll', onScroll) + win.document.addEventListener('focusout', onFocusOut) + return () => { + vv.removeEventListener('resize', onResize) + vv.removeEventListener('scroll', onScroll) + win.document.removeEventListener('focusout', onFocusOut) + timers.forEach(t => win.clearTimeout(t)) + } +} diff --git a/frontend/src/lib/viewport-guard.test.js b/frontend/src/lib/viewport-guard.test.js new file mode 100644 index 0000000..334a66e --- /dev/null +++ b/frontend/src/lib/viewport-guard.test.js @@ -0,0 +1,75 @@ +// @vitest-environment node +import { describe, it, expect, vi } from 'vitest' +import { installViewportGuard, realign, viewportDisplacement, keyboardOpen } from './viewport-guard.js' + +function fakeWindow({ innerHeight = 800, vvHeight = 800, offsetTop = 0, pageTop = 0, scrollY = 0, active = null } = {}) { + const listeners = {} + const on = (map, type, fn) => { (map[type] = map[type] || []).push(fn) } + const vv = { + height: vvHeight, offsetTop, pageTop, listeners: {}, + addEventListener(t, fn) { on(this.listeners, t, fn) }, removeEventListener() {} + } + const doc = { + activeElement: active, listeners: {}, + addEventListener(t, fn) { on(this.listeners, t, fn) }, removeEventListener() {} + } + const win = { + innerHeight, scrollX: 0, scrollY, visualViewport: vv, document: doc, + scrollTo: vi.fn(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout, + fire: (target, type, ev = {}) => (target.listeners[type] || []).forEach(fn => fn(ev)) + } + return win +} + +describe('viewport guard', () => { + it('reads the displacement from either the offset or a page-top that outran scrollY', () => { + expect(viewportDisplacement(fakeWindow({ offsetTop: 190 }))).toBe(190) + expect(viewportDisplacement(fakeWindow({ pageTop: 120, scrollY: 0 }))).toBe(120) + expect(viewportDisplacement(fakeWindow())).toBe(0) + expect(viewportDisplacement({ visualViewport: null })).toBe(0) + }) + + it('knows the keyboard from the visual viewport losing more than a toolbar', () => { + expect(keyboardOpen(fakeWindow({ vvHeight: 480 }))).toBe(true) + expect(keyboardOpen(fakeWindow({ vvHeight: 760 }))).toBe(false) + }) + + it('realigns a displaced page by scrolling to where it already is — and only then', () => { + const w = fakeWindow({ offsetTop: 190, scrollY: 0 }) + expect(realign(w)).toBe(true) + expect(w.scrollTo).toHaveBeenCalledWith(0, 0) + + expect(realign(fakeWindow())).toBe(false) // aligned + expect(realign(fakeWindow({ offsetTop: 190, vvHeight: 480 }))).toBe(false) // keyboard still up + expect(realign(fakeWindow({ offsetTop: 190, active: { tagName: 'INPUT' } }))).toBe(false) // still typing + }) + + it('fires when the keyboard has just closed, again after its animation, and on focusout', async () => { + vi.useFakeTimers() + const w = fakeWindow({ vvHeight: 480 }) + const off = installViewportGuard(w) + // keyboard closes but iOS leaves the offset behind + w.visualViewport.height = 800; w.visualViewport.offsetTop = 190 + w.fire(w.visualViewport, 'resize') + expect(w.scrollTo).toHaveBeenCalledTimes(1) + vi.advanceTimersByTime(400) + expect(w.scrollTo).toHaveBeenCalledTimes(2) // the late check after the dismiss animation + // a blur from a text field re-checks as well; a button losing focus does not + w.fire(w.document, 'focusout', { target: { tagName: 'BUTTON' } }) + expect(w.scrollTo).toHaveBeenCalledTimes(2) + w.fire(w.document, 'focusout', { target: { tagName: 'INPUT' } }) + expect(w.scrollTo).toHaveBeenCalledTimes(3) + off() + vi.advanceTimersByTime(400) + expect(w.scrollTo).toHaveBeenCalledTimes(3) // timers cleared on uninstall + vi.useRealTimers() + }) + + it('does nothing while the keyboard is open, and nothing at all without a visualViewport', () => { + const w = fakeWindow({ vvHeight: 480, offsetTop: 190 }) + installViewportGuard(w) + w.fire(w.visualViewport, 'scroll') + expect(w.scrollTo).not.toHaveBeenCalled() + expect(typeof installViewportGuard({ visualViewport: null, document: {} })).toBe('function') + }) +})