Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

iOS: the connect sheet keeps the pairing code field in sight

Duarte Santos6d1b6ff4ebcd
diff --git a/frontend/src/index.css b/frontend/src/index.css
index 875f25be3..99af739c8 100644
--- a/frontend/src/index.css
+++ b/frontend/src/index.css
@@ -1504,7 +1504,10 @@ body.no-tabbar #timer.working{box-shadow:inset 0 var(--hair) 0 var(--acc),0 -10p
animation:sheetup .34s var(--ease);
overscroll-behavior:contain;touch-action:pan-y;will-change:transform;
}
-.sheet:has(.picker-search){
+/* A sheet with a field (.picker-search) or marked .kb-lift (the connect sheet) stands on the
+ keyboard instead of letting the system scroll the pinned page to reach the field: see
+ lib/use-sheet-keyboard.js for the two variables. */
+.sheet:has(.picker-search),.sheet:has(.kb-lift){
bottom:max(var(--picker-keyboard-bottom,0px),var(--native-kb,0px));
/* with the keyboard up the sheet is capped by the visual viewport — which still starts
under the notch, hence the inset here too */
diff --git a/frontend/src/lib/native-keyboard.test.js b/frontend/src/lib/native-keyboard.test.js
index b723bcde2..728114c95 100644
--- a/frontend/src/lib/native-keyboard.test.js
+++ b/frontend/src/lib/native-keyboard.test.js
@@ -124,7 +124,8 @@ describe('the two halves agree', () => {
it('every sheet stands on the keyboard and the picker takes the larger lift', () => {
expect(css).toMatch(/:root\[data-native-kb\] \.sheet\{\s*bottom:max\(var\(--picker-keyboard-bottom,0px\),var\(--native-kb,0px\)\);/)
- expect(css).toMatch(/\.sheet:has\(\.picker-search\)\{\s*bottom:max\(var\(--picker-keyboard-bottom,0px\),var\(--native-kb,0px\)\);/)
+ // The connect sheet (.kb-lift) stands on the keyboard the way the picker does.
+ expect(css).toMatch(/\.sheet:has\(\.picker-search\),\.sheet:has\(\.kb-lift\)\{\s*bottom:max\(var\(--picker-keyboard-bottom,0px\),var\(--native-kb,0px\)\);/)
expect(css).toMatch(/max-height:min\(90vh,calc\(100dvh - var\(--sat\) - 8px - var\(--native-kb,0px\)\)\)/)
})
diff --git a/frontend/src/lib/use-sheet-keyboard.js b/frontend/src/lib/use-sheet-keyboard.js
index eccfd6655..ac41e7330 100644
--- a/frontend/src/lib/use-sheet-keyboard.js
+++ b/frontend/src/lib/use-sheet-keyboard.js
@@ -1,5 +1,5 @@
import { useCallback, useEffect } from 'react'
-import { nativeKeyboardHeight, NATIVE_KEYBOARD_EVENT } from './native-keyboard.js'
+import { nativeKeyboardHeight, NATIVE_KEYBOARD_EVENT, revealAboveKeyboard } from './native-keyboard.js'
/* How far the keyboard reaches up the layout viewport, and the height left above it. */
export function sheetKeyboardInsets(win) {
@@ -25,8 +25,12 @@ export function sheetKeyboardInsets(win) {
(lib/native-keyboard.js) and the larger of the two wins.
`inputRef` points at the text input (or textarea) whose closest `.sheet` gets the vars.
- `enabled` lets a caller switch the sync off (e.g. a picker without a search box). */
-export function useSheetKeyboard(inputRef, enabled = true) {
+ `enabled` lets a caller switch the sync off (e.g. a picker without a search box).
+ `reveal`: also scroll the sheet itself so the focused field inside it sits above the keyboard,
+ for a sheet that stands on the keyboard (a `.kb-lift` inside it, see index.css) and holds more
+ than one field: the second field is under the keys until the sheet scrolls, and left to iOS,
+ it scrolls the pinned page instead. */
+export function useSheetKeyboard(inputRef, enabled = true, { reveal = false } = {}) {
const sync = useCallback(() => {
const input = inputRef.current
const sheet = input?.closest?.('.sheet')
@@ -35,7 +39,14 @@ export function useSheetKeyboard(inputRef, enabled = true) {
const { bottomInset, visualHeight } = sheetKeyboardInsets(window)
sheet.style.setProperty('--picker-keyboard-bottom', `${bottomInset}px`)
sheet.style.setProperty('--picker-visual-height', `${visualHeight}px`)
- }, [inputRef])
+ if (!reveal) return
+ const active = typeof document !== 'undefined' ? document.activeElement : null
+ if (active && active !== sheet && sheet.contains(active)) {
+ // After the sheet has taken its new bottom and height.
+ const raf = window.requestAnimationFrame || (f => setTimeout(f, 16))
+ raf(() => { if (document.activeElement === active) revealAboveKeyboard(active, window) })
+ }
+ }, [inputRef, reveal])
useEffect(() => {
if (!enabled) return
diff --git a/frontend/src/views/MobileOnboarding.ios-keyboard.test.jsx b/frontend/src/views/MobileOnboarding.ios-keyboard.test.jsx
new file mode 100644
index 000000000..db5b2179d
--- /dev/null
+++ b/frontend/src/views/MobileOnboarding.ios-keyboard.test.jsx
@@ -0,0 +1,90 @@
+// @vitest-environment happy-dom
+// TestFlight build 26, iPhone: on "Connect to my server", tapping the pairing-code field shifted
+// the screen so the field ended up above the visible area; tapping out and in again fixed it.
+// The sheet sat at the bottom under the keyboard, so WebKit scrolled the pinned page to reach
+// the field, and the first focus landed 250 ms into the sheet's 340 ms slide-up, measured on a
+// moving sheet. Now the sheet stands on the keyboard (index.css .kb-lift), scrolls the focused
+// field above the keys itself, and the autofocus waits for the sheet to land.
+import React, { act } from 'react'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createRoot } from 'react-dom/client'
+import { useUI } from '../store/useUI.js'
+import { _setLangState } from '../lib/i18n-core.js'
+import { ConnectSheet, CfAccessSheet, SHEET_SETTLE_MS } from './MobileOnboarding.jsx'
+
+let root, host, sheet, savedVV
+const rect = (top, bottom) => () => ({ top, bottom, left: 0, right: 300, width: 300, height: bottom - top })
+
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ _setLangState('en', null, null, null)
+ useUI.setState({ sheets: [], toastMsg: '' })
+ // An 800 px screen with a 340 px keyboard up: the visual viewport is what is left.
+ savedVV = Object.getOwnPropertyDescriptor(window, 'visualViewport')
+ Object.defineProperty(window, 'innerHeight', { configurable: true, value: 800 })
+ Object.defineProperty(window, 'visualViewport', { configurable: true, value: Object.assign(new EventTarget(), { height: 460, offsetTop: 0, pageTop: 0 }) })
+ host = document.createElement('div')
+ sheet = document.createElement('div')
+ sheet.className = 'sheet'
+ host.appendChild(sheet)
+ document.body.appendChild(host)
+ root = createRoot(sheet)
+})
+afterEach(() => {
+ act(() => root.unmount()); host.remove()
+ if (savedVV) Object.defineProperty(window, 'visualViewport', savedVV)
+ else delete window.visualViewport
+ vi.useRealTimers()
+})
+
+describe('the connect sheet and the iOS keyboard', () => {
+ it('does not focus a field before the sheet has finished sliding up', () => {
+ vi.useFakeTimers()
+ act(() => root.render(<ConnectSheet close={() => {}} />))
+ const [url] = sheet.querySelectorAll('input')
+ act(() => { vi.advanceTimersByTime(250) })
+ expect(document.activeElement).not.toBe(url)
+ expect(SHEET_SETTLE_MS).toBeGreaterThan(340) // index.css @keyframes sheetup is .34s
+ act(() => { vi.advanceTimersByTime(SHEET_SETTLE_MS) })
+ expect(document.activeElement).toBe(url)
+ })
+
+ it('pairing again focuses the code field, also only once the sheet has landed', () => {
+ vi.useFakeTimers()
+ act(() => root.render(<ConnectSheet close={() => {}} initialUrl="https://gym.example.com" again />))
+ act(() => { vi.advanceTimersByTime(SHEET_SETTLE_MS) })
+ expect(document.activeElement).toBe(sheet.querySelectorAll('input')[1])
+ })
+
+ it('stands on the keyboard and scrolls the code field above it, without scrolling the page', async () => {
+ const scrollTo = vi.spyOn(window, 'scrollTo').mockImplementation(() => {})
+ act(() => root.render(<ConnectSheet close={() => {}} />))
+ expect(sheet.querySelector('.kb-lift')).not.toBeNull()
+ const code = sheet.querySelectorAll('input')[1]
+ // The sheet's top at 300, the code field at 520-564: under the keyboard, which starts at 460.
+ sheet.getBoundingClientRect = rect(300, 800)
+ code.getBoundingClientRect = rect(520, 564)
+ await act(async () => {
+ code.focus()
+ code.dispatchEvent(new FocusEvent('focus'))
+ await new Promise(r => setTimeout(r, 40))
+ })
+ expect(sheet.style.getPropertyValue('--picker-keyboard-bottom')).toBe('340px')
+ expect(sheet.style.getPropertyValue('--picker-visual-height')).toBe('460px')
+ // 564 + 16 margin past the 460 px line: the sheet itself scrolls by the difference.
+ expect(sheet.scrollTop).toBe(120)
+ expect(scrollTo).not.toHaveBeenCalled()
+ })
+
+ it('the Cloudflare Access sheet, three fields, does the same', () => {
+ act(() => root.render(<CfAccessSheet close={() => {}} />))
+ expect(sheet.querySelector('.kb-lift')).not.toBeNull()
+ })
+
+ it('index.css lifts a .kb-lift sheet the way it lifts the picker', () => {
+ const css = readFileSync(resolve(__dirname, '../index.css'), 'utf8')
+ expect(css).toMatch(/\.sheet:has\(\.picker-search\),\.sheet:has\(\.kb-lift\)\{\s*bottom:max\(var\(--picker-keyboard-bottom,0px\),var\(--native-kb,0px\)\);/)
+ })
+})
diff --git a/frontend/src/views/MobileOnboarding.jsx b/frontend/src/views/MobileOnboarding.jsx
index 064b677f6..b40d80be3 100644
--- a/frontend/src/views/MobileOnboarding.jsx
+++ b/frontend/src/views/MobileOnboarding.jsx
@@ -10,6 +10,7 @@ import { Button } from '../components/ui.jsx'
import { askAddDeviceData } from '../sheets.jsx'
import { normalizeServerUrl } from '../lib/remote.js'
import { loadCfAccess, saveCfAccess } from '../lib/cf-access.js'
+import { useSheetKeyboard } from '../lib/use-sheet-keyboard.js'
// A plain http:// server works (#428), but whatever the app sends, the pairing code and then its
// token, crosses the network readable. Said once under the field, not in the way: on a home
@@ -22,6 +23,10 @@ export function plainHttp(raw) {
}
+// The sheet's slide-up (index.css @keyframes sheetup, .34s) plus a frame: a field focused before
+// it lands has the keyboard reveal it at a position the sheet is about to leave.
+export const SHEET_SETTLE_MS = 400
+
// `server`: the address the token is most likely for (the one being typed into ConnectSheet).
const openCfAccess = server => useUI.getState().openSheet(close => <CfAccessSheet close={close} server={server} />)
@@ -35,6 +40,8 @@ export function CfAccessSheet({ close, server = '' }) {
const [clientSecret, setClientSecret] = useState('')
const [had, setHad] = useState(false)
const [busy, setBusy] = useState(false)
+ const addrRef = useRef(null)
+ const onFocus = useSheetKeyboard(addrRef, true, { reveal: true })
const origin = normalizeServerUrl(addr)
useEffect(() => {
loadCfAccess().then(c => { if (c) { setClientId(c.clientId); setClientSecret(c.clientSecret); setHad(true); if (c.origin) setAddr(c.origin) } })
@@ -50,21 +57,21 @@ export function CfAccessSheet({ close, server = '' }) {
} catch (e) { useUI.getState().toast(e.message || t('Could not save')) }
finally { setBusy(false) }
}
- return <>
+ return <div className="kb-lift">
<h3>{t('Cloudflare Access')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>
{t('Only if your server is behind Cloudflare Access: the service token this phone sends with every request to it. Kept in this phone’s secure storage.')}
</div>
- <input className="input" placeholder={t('Server address (e.g. gym.example.com)')} value={addr} aria-label={t('Server address (e.g. gym.example.com)')}
- onChange={e => setAddr(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" />
+ <input ref={addrRef} className="input" placeholder={t('Server address (e.g. gym.example.com)')} value={addr} aria-label={t('Server address (e.g. gym.example.com)')}
+ onFocus={onFocus} onChange={e => setAddr(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" />
{origin && <div className="dim small" role="note" style={{ marginTop: 8, lineHeight: 1.45, overflowWrap: 'anywhere' }}>
{t('Sent only to {0}, never to another server.', new URL(origin).host)}
</div>}
<div style={{ height: 10 }} />
- <input className="input" placeholder="CF-Access-Client-Id" value={clientId}
+ <input className="input" placeholder="CF-Access-Client-Id" value={clientId} onFocus={onFocus}
onChange={e => setClientId(e.target.value)} autoCapitalize="none" autoCorrect="off" spellCheck={false} />
<div style={{ height: 10 }} />
- <input className="input" type="password" placeholder="CF-Access-Client-Secret" value={clientSecret}
+ <input className="input" type="password" placeholder="CF-Access-Client-Secret" value={clientSecret} onFocus={onFocus}
onChange={e => setClientSecret(e.target.value)} autoCapitalize="none" autoCorrect="off" spellCheck={false} autoComplete="off" />
<div style={{ height: 12 }} />
<Button variant="primary" onClick={() => save(clientId, clientSecret)} disabled={busy}>{t('Save')}</Button>
@@ -72,7 +79,7 @@ export function CfAccessSheet({ close, server = '' }) {
<div style={{ height: 10 }} />
<Button icon="trash" onClick={() => save('', '')} disabled={busy}>{t('Remove')}</Button>
</>}
- </>
+ </div>
}
// `again`: a phone whose server stopped accepting it (components/ServerSync.jsx pairAgain) — the
@@ -88,7 +95,16 @@ export function ConnectSheet({ close, initialUrl = '', again = false }) {
const [error, setError] = useState('')
const ref = useRef(null)
const codeRef = useRef(null)
- useEffect(() => { setTimeout(() => (initialUrl ? codeRef : ref).current?.focus(), 250) }, [])
+ // The sheet stands on the keyboard and scrolls the focused field into view itself (index.css
+ // .kb-lift). On iOS the code field went out of sight above the screen (TestFlight build 26):
+ // the sheet sat at the bottom under the keys, so WebKit scrolled the pinned page to reach the
+ // field, and the first focus came 250 ms into the sheet's 340 ms slide-up, measured on a
+ // sheet still moving. The autofocus now waits for the sheet to land.
+ const onFocus = useSheetKeyboard(ref, true, { reveal: true })
+ useEffect(() => {
+ const tm = setTimeout(() => (initialUrl ? codeRef : ref).current?.focus(), SHEET_SETTLE_MS)
+ return () => clearTimeout(tm)
+ }, [])
const go = async () => {
if (!url.trim() || !code.trim()) { useUI.getState().toast(t('Enter your server address and the code')); return }
setBusy(true)
@@ -97,7 +113,7 @@ export function ConnectSheet({ close, initialUrl = '', again = false }) {
catch (e) { setError(e.message || t('Could not connect')) }
finally { setBusy(false) }
}
- return <>
+ return <div className="kb-lift">
<h3>{again ? t('Pair again') : t('Connect to my server')}</h3>
<div className="muted small" style={{ marginBottom: 14 }}>
{again
@@ -105,19 +121,19 @@ export function ConnectSheet({ close, initialUrl = '', again = false }) {
: t('Open Settings → Account → “Pair the mobile app” on the openGym site you’re already signed into, then enter its address and the code shown there.')}
</div>
<input ref={ref} className="input" placeholder={t('Server address (e.g. gym.example.com)')} value={url}
- onChange={e => setUrl(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" />
+ onFocus={onFocus} onChange={e => setUrl(e.target.value)} autoCapitalize="none" autoCorrect="off" inputMode="url" />
{plainHttp(url) && <div className="dim small" role="note" style={{ marginTop: 8, lineHeight: 1.45 }}>
{t('Plain http:// isn’t encrypted. Fine on your home network, but use https:// if your server is reachable from the internet.')}
</div>}
<div style={{ height: 10 }} />
<input ref={codeRef} className="input" placeholder={t('Pairing code')} maxLength={8} value={code}
- onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />
+ onFocus={onFocus} onChange={e => setCode(e.target.value.toUpperCase())} style={{ letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }} />
{error && <div className="small" role="alert" style={{ color: 'var(--red)', marginTop: 10, lineHeight: 1.45, overflowWrap: 'anywhere' }}>{error}</div>}
<div style={{ height: 12 }} />
<Button variant="primary" onClick={go} disabled={busy}>{busy ? t('Connecting…') : t('Connect')}</Button>
<div style={{ height: 10 }} />
<Button icon="key" onClick={() => openCfAccess(normalizeServerUrl(url) || '')} disabled={busy}>{t('Cloudflare Access')}</Button>
- </>
+ </div>
}
export default function MobileOnboarding() {