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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Edge swipe back: the previous page slides in underneath
Duarte Santos2f26ac030f08
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 0065f8c68..b97e709bd 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -1,4 +1,4 @@-import { useEffect, useLayoutEffect, useRef } from 'react'+import { useEffect, useLayoutEffect, useRef, useState } from 'react'import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation, useNavigationType } from 'react-router-dom'import { useStore } from './store/useStore.js'import { useUI } from './store/useUI.js'@@ -9,10 +9,10 @@ import { setLang, useLang, baseLang } from './lib/i18n.js'import { effectiveLang } from './lib/default-lang.js'import { setPlayOnSilent, setVibrate, setAlarmBuzzer, setNativeBuzzer } from './lib/sound.js'import { buzzAsAlarm } from './lib/rest-alert.js'-import { setNav } from './lib/nav.js'+import { setNav, notePath, keyBefore } from './lib/nav.js'import { setSystemBarsLight } from './lib/system-bars.js'import { initBackButton } from './lib/back.js'-import { installEdgeSwipeBack } from './lib/edge-swipe-back.js'+import { installEdgeSwipeBack, BACK_PREVIEW_EVENT } from './lib/edge-swipe-back.js'import { useWakeLock } from './lib/wakelock.js'import { installViewportGuard } from './lib/viewport-guard.js'import { installChipDrag } from './lib/hchips.js'@@ -157,10 +157,37 @@ function Shell() {window.addEventListener('scroll', onScroll, { passive: true })return () => window.removeEventListener('scroll', onScroll)}, [])+ // The edge swipe back (lib/edge-swipe-back.js) asks for the page it goes back to underneath+ // while the finger moves (`preview`), and says where it is going as it lets go (`returning`):+ // that page comes back where it was scrolled to, as the back button's push would not.+ const [preview, setPreview] = useState(null)+ const returning = useRef(null)+ useEffect(() => {+ const on = e => {+ const d = e.detail || {}+ if ('commit' in d) returning.current = d.commit+ else setPreview(d.path || null)+ }+ window.addEventListener(BACK_PREVIEW_EVENT, on)+ return () => window.removeEventListener(BACK_PREVIEW_EVENT, on)+ }, [])+ // Any navigation ends a preview: promoted (it is the page now) or not needed any more.+ useEffect(() => { setPreview(null) }, [loc.pathname])useLayoutEffect(() => {const first = pathRef.current === nullconst samePath = pathRef.current === loc.pathnamepathRef.current = loc.pathname+ notePath(loc.pathname, loc.key)+ if (returning.current && returning.current === loc.pathname && !first) {+ returning.current = null+ const y = scrollPositions.get(loc.pathname) || 0+ // Promoted from the preview it is laid out already: back at y in this same frame. A page+ // mounted fresh (no preview) needs its layout pass first, as a POP does.+ if (document.querySelector('#app > .page[data-promoted]')) { window.scrollTo(0, y); return }+ const frame = window.requestAnimationFrame(() => window.scrollTo(0, y))+ return () => window.cancelAnimationFrame(frame)+ }+ returning.current = null// A fresh load arrives as a POP with nothing remembered. It goes to the top like any new// route — now, not a frame later: that frame landed on top of a scroll a view made on mount// (the superset card centring its row, views/Workout.jsx), and a smooth scroll cut off by a@@ -201,42 +228,47 @@ function Shell() {</div>)+ const view = l => (!authed ? <Login /> : needsMobileOnboarding ? <MobileOnboarding /> : permSteps ? <PermissionSteps /> : (+ <Routes location={l}>+ <Route path="/home" element={<Home />} />+ {/* Gym check-in — switched off in Settings, the route falls through to the+ catch-all redirect below. */}+ {S.checkIn !== false && <Route path="/checkin" element={<CheckIn />} />}+ <Route path="/plan" element={<Plan />} />+ <Route path="/plan/r/:id" element={<RoutineEdit />} />+ <Route path="/workout" element={<Workout />} />+ <Route path="/stats" element={<Stats />} />+ <Route path="/history" element={<History />} />+ <Route path="/library" element={<Library />} />+ <Route path="/muscles" element={<Muscles />} />+ <Route path="/structural-balance" element={<StructuralBalance />} />+ <Route path="/progress-photos" element={<ProgressPhotos />} />+ <Route path="/measurements" element={<Measurements />} />+ <Route path="/settings" element={<SettingsRoute />} />+ <Route path="/settings/:page" element={<SettingsRoute />} />+ {/* The Coach screens gate themselves on the instance config; the routes exist+ unconditionally so a deep link from a notification lands somewhere sane+ rather than on the catch-all. */}+ <Route path="/coach" element={<CoachChat />} />+ <Route path="/coach/intake" element={<CoachIntake />} />+ <Route path="/coach/proposal" element={<Navigate to="/coach" replace />} />+ <Route path="/coach/setup" element={<CoachSetup />} />+ <Route path="/admin" element={user?.admin ? <Admin /> : <Navigate to="/home" replace />} />+ <Route path="*" element={<Navigate to="/home" replace />} />+ </Routes>+ ))+ const showPreview = !!preview && preview !== loc.pathname && authed && !needsMobileOnboarding && !permSteps+return (<>- {/* keyed on the route: a view that throws is contained, and switching tabs- re-mounts the boundary, so the tab bar is always a way out */}- <div id="app" className="vfade" key={loc.pathname}>- <ErrorBoundary>- {!authed ? <Login /> : needsMobileOnboarding ? <MobileOnboarding /> : permSteps ? <PermissionSteps /> : (- <Routes>- <Route path="/home" element={<Home />} />- {/* Gym check-in — switched off in Settings, the route falls through to the- catch-all redirect below. */}- {S.checkIn !== false && <Route path="/checkin" element={<CheckIn />} />}- <Route path="/plan" element={<Plan />} />- <Route path="/plan/r/:id" element={<RoutineEdit />} />- <Route path="/workout" element={<Workout />} />- <Route path="/stats" element={<Stats />} />- <Route path="/history" element={<History />} />- <Route path="/library" element={<Library />} />- <Route path="/muscles" element={<Muscles />} />- <Route path="/structural-balance" element={<StructuralBalance />} />- <Route path="/progress-photos" element={<ProgressPhotos />} />- <Route path="/measurements" element={<Measurements />} />- <Route path="/settings" element={<SettingsRoute />} />- <Route path="/settings/:page" element={<SettingsRoute />} />- {/* The Coach screens gate themselves on the instance config; the routes exist- unconditionally so a deep link from a notification lands somewhere sane- rather than on the catch-all. */}- <Route path="/coach" element={<CoachChat />} />- <Route path="/coach/intake" element={<CoachIntake />} />- <Route path="/coach/proposal" element={<Navigate to="/coach" replace />} />- <Route path="/coach/setup" element={<CoachSetup />} />- <Route path="/admin" element={user?.admin ? <Admin /> : <Navigate to="/home" replace />} />- <Route path="*" element={<Navigate to="/home" replace />} />- </Routes>- )}- </ErrorBoundary>+ {/* One page per route, keyed on it: a view that throws is contained, and switching tabs+ re-mounts the boundary, so the tab bar is always a way out. While an edge swipe back+ is under way the page it goes back to sits underneath (Page `under`), and as the swipe+ lands it simply stays: same key, same parent, so React keeps it instead of mounting+ the route again. */}+ <div id="app">+ <Page key={loc.pathname} loc={loc} render={view} />+ {showPreview && <Page key={preview} loc={previewLoc(preview)} render={view} under scrollY={scrollPositions.get(preview) || 0} />}</div>{/* Outside #app: the view's fade-in animates a transform, and a fixed element inside itwould ride along with the page for the length of it. Decides for itself when to show —@@ -251,6 +283,33 @@ function Shell() {)}+// The location the page underneath renders with: the entry it will be, when history knows it.+const previewLoc = pathname => ({ pathname, search: '', hash: '', state: null, key: keyBefore(pathname) || 'back-preview' })++/* One route's page. `under`: the page an edge swipe back is about to return to, drawn beneath+ the current one (index.css .page.under): fixed, at the scroll position it was left at, inert+ and hidden from assistive tech, so nothing in it can be tapped, focused or read out while it+ only shows. When the swipe lands it becomes the page in place (same element, same state, no+ second mount, no fade): the styles the gesture painted on it go, and App puts the window back+ at that scroll position in the same frame. */+function Page({ loc, render, under = false, scrollY = 0 }) {+ const ref = useRef(null)+ const wasUnder = useRef(under)+ const promoted = wasUnder.current && !under+ useLayoutEffect(() => {+ if (under || !wasUnder.current) return+ const el = ref.current+ if (el) { el.style.transform = ''; el.style.transition = ''; el.style.visibility = '' }+ }, [under])+ return <div ref={ref} className={'page' + (under ? ' under' : wasUnder.current ? '' : ' vfade')}+ data-path={loc.pathname} data-promoted={promoted ? '' : undefined}+ aria-hidden={under || undefined} inert={under || undefined}>+ <div className="page-in" style={under && scrollY ? { transform: `translateY(${-scrollY}px)` } : undefined}>+ <ErrorBoundary>{render(loc)}</ErrorBoundary>+ </div>+ </div>+}+export default function App() {const boot = useStore(s => s.boot)useEffect(() => { boot() }, [boot])diff --git a/frontend/src/App.swipe-preview.test.jsx b/frontend/src/App.swipe-preview.test.jsxnew file mode 100644index 000000000..10185dadb--- /dev/null+++ b/frontend/src/App.swipe-preview.test.jsx@@ -0,0 +1,103 @@+// @vitest-environment happy-dom+// The edge swipe back shows the page it returns to underneath while the finger moves (TestFlight+// 1.4.2 (27): only a dark backdrop, then the app "teleported"). App renders that page from the+// route table, inert and hidden from assistive tech, at the scroll position it was left at; when+// the swipe lands it IS the page (the same element, not a second mount), and the window is back+// at that position in the same pass. A cancelled swipe takes it away again.+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import App from './App.jsx'+import { DEF, useStore } from './store/useStore.js'+import { BACK_PREVIEW_EVENT } from './lib/edge-swipe-back.js'++vi.mock('./lib/sound.js', async importOriginal => ({ ...(await importOriginal()), setPlayOnSilent: vi.fn(), setVibrate: vi.fn(), setAlarmBuzzer: vi.fn(), setNativeBuzzer: vi.fn() }))+vi.mock('./lib/api.js', async importOriginal => {+ const actual = await importOriginal()+ return { ...actual, api: vi.fn(() => Promise.resolve({})), beacon: vi.fn() }+})++globalThis.IS_REACT_ACT_ENVIRONMENT = true++let host, root, originalS, scrolls+const pages = () => [...document.querySelectorAll('#app > .page')]+const under = () => document.querySelector('#app > .page.under')+const send = detail => act(() => { window.dispatchEvent(new CustomEvent(BACK_PREVIEW_EVENT, { detail })) })+const go = async hash => { await act(async () => { window.location.hash = hash; window.dispatchEvent(new HashChangeEvent('hashchange')); window.dispatchEvent(new PopStateEvent('popstate')) }) }+const scrolledTo = async y => {+ Object.defineProperty(window, 'scrollY', { configurable: true, value: y })+ await act(async () => { window.dispatchEvent(new Event('scroll')) })+}++beforeEach(async () => {+ originalS = useStore.getState().S+ useStore.setState({ S: JSON.parse(JSON.stringify(DEF)) })+ localStorage.setItem('gym_guest', '1') // a guest: the app itself, no sign-in screen+ window.location.hash = '#/settings'+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)+ scrolls = []+ window.scrollTo = vi.fn((x, y) => { scrolls.push([x, y]); Object.defineProperty(window, 'scrollY', { configurable: true, value: y }) })+ await act(async () => { root.render(<App />) })+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+ useStore.setState({ S: originalS })+ localStorage.removeItem('gym_guest')+})++describe('the page underneath an edge swipe back', () => {+ it('is the page the back button goes to, at its scroll position, inert and hidden', async () => {+ await scrolledTo(420)+ await go('#/settings/units')+ expect(pages().map(p => p.dataset.path)).toEqual(['/settings/units'])+ const back = document.querySelector('#app [data-back]')+ expect(back.getAttribute('data-back')).toBe('/settings')++ send({ path: '/settings' })+ expect(pages().map(p => p.dataset.path)).toEqual(['/settings/units', '/settings'])+ const u = under()+ expect(u.getAttribute('aria-hidden')).toBe('true')+ expect(u.hasAttribute('inert')).toBe(true)+ expect(u.querySelector('.page-in').style.transform).toBe('translateY(-420px)')+ // The page on top is still the one whose back button the gesture presses.+ expect(document.querySelector('#app > .page:not(.under) [data-back]')).toBe(back)+ })++ it('becomes the page when the swipe lands: the same element, no second mount, back where it was scrolled', async () => {+ await scrolledTo(420)+ await go('#/settings/units')+ send({ path: '/settings' })+ const u = under()+ const marker = u.querySelector('.page-in > *')+ send({ commit: '/settings' })+ await act(async () => { document.querySelector('#app > .page:not(.under) [data-back]').click() })+ expect(pages()).toEqual([u]) // kept, not mounted again+ expect(u.querySelector('.page-in > *')).toBe(marker) // its content too+ expect(u.classList.contains('under')).toBe(false)+ expect(u.classList.contains('vfade')).toBe(false) // no fade-in on a page already shown+ expect(u.hasAttribute('inert')).toBe(false)+ expect(u.getAttribute('aria-hidden')).toBeNull()+ expect(u.querySelector('.page-in').style.transform).toBe('')+ expect(u.id).toBe('')+ expect(scrolls.at(-1)).toEqual([0, 420])+ })++ it('a cancelled swipe takes it away and leaves the page as it was', async () => {+ await go('#/settings/units')+ const top = pages()[0]+ send({ path: '/settings' })+ expect(under()).not.toBeNull()+ send({ path: null })+ expect(pages()).toEqual([top])+ expect(window.location.hash).toBe('#/settings/units')+ })++ it('a back that lands somewhere else drops it, and that page mounts as usual', async () => {+ await go('#/settings/units')+ send({ path: '/stats' })+ await go('#/settings')+ expect(pages().map(p => p.dataset.path)).toEqual(['/settings'])+ expect(under()).toBeNull()+ })+})diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 96023b0f7..da98366e5 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -179,7 +179,15 @@ body.no-tabbar #app{padding-bottom:calc(24px + var(--sab))}body.no-tabbar.resting #app{padding-bottom:calc(96px + var(--sab))}.workout-end-spacer{height:0}@keyframes viewfade{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}-#app.vfade{animation:viewfade var(--med) var(--ease)}+#app > .page.vfade{animation:viewfade var(--med) var(--ease)}+/* The page an edge swipe back returns to (App.jsx Page `under`, lib/edge-swipe-back.js): laid+ out where #app lays out a page, fixed under the current one, at the scroll position it was+ left at (.page-in is moved up by it), hidden until the finger has committed to the swipe. */+#app > .page.under{+ position:fixed;top:0;left:0;right:0;bottom:0;z-index:0;overflow:hidden;+ padding:inherit;max-width:inherit;margin:0 auto;+ visibility:hidden;pointer-events:none;will-change:transform;+}/* Connection indicator (components/SyncBanner.jsx): pinned under the status bar for as long asthe app is not connected to a server. It carries the page's own ground and blur, like the@@ -2146,7 +2154,14 @@ button.wl-summary{width:100%;padding:0 0 10px;text-align:start;border-radius:var.exfix-link{display:inline-flex;align-items:center;gap:5px;margin:14px 0 4px;color:var(--label-3);text-decoration:none}.list .similar-label{margin:16px 2px 6px;grid-column:1/-1}-/* The edge swipe back (lib/edge-swipe-back.js): the page follows the finger over a dimmed- backdrop that stands in for the page underneath. */-.edge-back-shade{position:fixed;inset:0;background:#000;opacity:.35;pointer-events:none;z-index:0}-#app.edge-back-page{position:relative;z-index:1;background:var(--bg);box-shadow:0 0 28px rgba(0,0,0,.28);will-change:transform}+/* The edge swipe back (lib/edge-swipe-back.js): the page follows the finger, the one it goes+ back to slides in underneath with a shade over it. The sliding page's own ground reaches the+ screen's edges (--eb-*: how far #app's padding and margins leave it short of them). */+.edge-back-shade{position:fixed;inset:0;background:#000;opacity:.35;pointer-events:none;z-index:1}+.edge-back-page{position:relative;z-index:2;will-change:transform}+.edge-back-page::before{+ content:'';position:absolute;z-index:-1;pointer-events:none;background:var(--bg);+ top:calc(-1 * var(--eb-t,0px));bottom:calc(-1 * var(--eb-b,0px));+ left:calc(-1 * var(--eb-l,0px));right:calc(-1 * var(--eb-r,0px));+ box-shadow:0 0 28px rgba(0,0,0,.28);+}diff --git a/frontend/src/lib/edge-swipe-back.js b/frontend/src/lib/edge-swipe-back.jsindex 9637bdda2..739e41258 100644--- a/frontend/src/lib/edge-swipe-back.js+++ b/frontend/src/lib/edge-swipe-back.js@@ -25,6 +25,10 @@ export const SLOP_PX = 10 // movement before the gesture decides sidewaexport const COMMIT_FRACTION = 1 / 3export const FLICK_PX_PER_MS = 0.5 // a flick this fast goes back from any distance past the slopconst SETTLE_MS = 260+const PARALLAX = 0.3 // the page underneath starts this far to the left, and slides in+const SHADE = 0.35 // its dimming at the start of the swipe++export const BACK_PREVIEW_EVENT = 'opengym:back-preview'/* ---------- pure decisions ---------- */@@ -65,7 +69,8 @@ export function releaseOf({ dx, width, vx }) {/** The page's own back button, or null: visible, enabled, and not behind an open sheet. */export function backTarget(doc = document) {if (doc.querySelector('#modal-root.open')) return null- const el = doc.querySelector('#app [data-back]')+ // the page on top: the one underneath (App.jsx `under`) has back buttons of its own+ const el = doc.querySelector('#app > .page:not(.under) [data-back]') || doc.querySelector('#app [data-back]')if (!el || el.disabled) return nullreturn el}@@ -92,33 +97,71 @@ export function installEdgeSwipeBack(win = window, opts = {}) {else enabled = edgeSwipeEnabled({ mobile: false, ios, standalone })}- let g = null // { id, x0, y0, t, x, lastX, lastT, vx, rtl, width, target, lock, page, shade }+ let g = null // { id, x0, y0, lastX, lastT, vx, rtl, width, target, path, lock, page, under, shade }++ // The page it goes back to (App.jsx renders it underneath while asked to; `path` null ends+ // that), and, as the swipe lands, where it is returning, so App restores its scroll position.+ const preview = path => win.dispatchEvent(new win.CustomEvent(BACK_PREVIEW_EVENT, { detail: { path } }))+ const committing = path => win.dispatchEvent(new win.CustomEvent(BACK_PREVIEW_EVENT, { detail: { commit: path } }))+ const underlay = () => (g && (g.under || (g.under = doc.querySelector('#app > .page.under')))) || null+ // transform and opacity only, so the frames stay on the compositorconst paint = (dx, ms = 0) => {if (!g || !g.page) return- const off = Math.max(0, dx) * (g.rtl ? -1 : 1)- const tr = ms ? `transform ${ms}ms cubic-bezier(.32,.72,0,1)` : 'none'- g.page.style.transition = tr- g.page.style.transform = off ? `translateX(${off}px)` : ''+ const p = Math.min(1, Math.max(0, dx) / g.width)+ const dir = g.rtl ? -1 : 1+ const tr = prop => (ms ? `${prop} ${ms}ms cubic-bezier(.32,.72,0,1)` : 'none')+ g.page.style.transition = tr('transform')+ g.page.style.transform = p ? `translateX(${p * g.width * dir}px)` : ''+ const under = underlay()+ if (under) {+ under.style.visibility = 'visible'+ under.style.transition = tr('transform')+ under.style.transform = `translateX(${-PARALLAX * (1 - p) * g.width * dir}px)`+ }if (g.shade) {g.shade.style.transition = ms ? `opacity ${ms}ms linear` : 'none'- g.shade.style.opacity = String(Math.max(0, 1 - dx / g.width) * 0.35)+ g.shade.style.opacity = String((1 - p) * SHADE)}}const startVisual = () => {if (reducedMotion(win)) return- const page = doc.getElementById('app')+ const page = doc.querySelector('#app > .page:not(.under)') || doc.getElementById('app')if (!page) returng.page = page+ // The page's own ground reaches the screen's edges (index.css .edge-back-page::before): its+ // box stops at #app's padding, and the page underneath must not show through around it.+ const r = page.getBoundingClientRect()+ page.style.setProperty('--eb-l', Math.max(0, r.left) + 'px')+ page.style.setProperty('--eb-r', Math.max(0, g.width - r.right) + 'px')+ page.style.setProperty('--eb-t', Math.max(0, r.top) + 'px')+ page.style.setProperty('--eb-b', Math.max(0, (win.innerHeight || 0) - r.bottom) + 'px')page.classList.add('edge-back-page')const shade = doc.createElement('div')shade.className = 'edge-back-shade'page.parentNode.insertBefore(shade, page)g.shade = shade}+ // Cancelled: everything back as it was, and the page underneath goes away.const endVisual = gesture => {- if (gesture.page) { gesture.page.style.transition = ''; gesture.page.style.transform = ''; gesture.page.classList.remove('edge-back-page') }+ if (gesture.page) {+ gesture.page.style.transition = ''; gesture.page.style.transform = ''+ for (const v of ['--eb-l', '--eb-r', '--eb-t', '--eb-b']) gesture.page.style.removeProperty(v)+ gesture.page.classList.remove('edge-back-page')+ }gesture.shade?.remove()+ if (gesture.path) preview(null)+ }+ // Landed: the page underneath is the page now (App keeps it, same element). The page that+ // slid out stays where it went until React has taken it away, so nothing flashes back.+ const landed = gesture => {+ if (gesture.path) committing(gesture.path)+ gesture.target.click()+ const raf = win.requestAnimationFrame || (f => win.setTimeout(f, 16))+ raf(() => raf(() => {+ gesture.shade?.remove()+ if (gesture.page?.isConnected) endVisual({ ...gesture, path: null })+ }))}const onDown = e => {@@ -130,7 +173,11 @@ export function installEdgeSwipeBack(win = window, opts = {}) {if (!target) return// Claimed: nothing under the edge (a set row, a card) starts its own swipe from this touch.e.stopPropagation()- g = { id: e.pointerId, x0: e.clientX, y0: e.clientY, lastX: e.clientX, lastT: e.timeStamp || Date.now(), vx: 0, rtl, width, target, lock: null }+ // The page underneath starts mounting now, hidden, so it is there by the time the finger has+ // moved far enough to show it. Not with reduced motion: nothing slides, nothing to show.+ const path = reducedMotion(win) ? null : (target.getAttribute('data-back') || null)+ g = { id: e.pointerId, x0: e.clientX, y0: e.clientY, lastX: e.clientX, lastT: e.timeStamp || Date.now(), vx: 0, rtl, width, target, path, lock: null }+ if (path) preview(path)}const onMove = e => {if (!g || e.pointerId !== g.id) return@@ -156,14 +203,11 @@ export function installEdgeSwipeBack(win = window, opts = {}) {if (done.lock !== 'go') { endVisual(done); return }const dx = progressOf(done.x0, e.clientX, done.rtl)const go = releaseOf({ dx, width: done.width, vx: done.vx }) === 'back' && e.type !== 'pointercancel'- if (!done.page) { endVisual(done); if (go) done.target.click(); return }+ if (!done.page) { if (go) landed(done); else endVisual(done); return }g = done // for paintpaint(go ? done.width : 0, SETTLE_MS)g = null- win.setTimeout(() => {- if (go) done.target.click()- endVisual(done)- }, SETTLE_MS)+ win.setTimeout(() => { if (go) landed(done); else endVisual(done) }, SETTLE_MS)}// A claimed touch must not scroll the page under it: pointer events alone do not stop a WebKit// scroll, and a scroll that starts in the slop cancels the pointer. Only touches that began indiff --git a/frontend/src/lib/edge-swipe-back.test.js b/frontend/src/lib/edge-swipe-back.test.jsindex 0d0ef9034..2d2a1f26f 100644--- a/frontend/src/lib/edge-swipe-back.test.js+++ b/frontend/src/lib/edge-swipe-back.test.js@@ -4,7 +4,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {EDGE_PX, COMMIT_FRACTION, edgeSwipeEnabled, startsAtEdge, progressOf, lockOf, releaseOf,- backTarget, installEdgeSwipeBack,+ backTarget, installEdgeSwipeBack, BACK_PREVIEW_EVENT,} from './edge-swipe-back.js'describe('where it is on', () => {@@ -195,9 +195,107 @@ describe('every page back arrow is marked', () => {for (const [file, src] of Object.entries(files)) {for (const line of src.split('\n')) {if (!/chevronLeft/.test(line) || !/<button/.test(line)) continue- if (/onClick=\{(\(\) => nav\(|back\}|home\})/.test(line) && !/data-back/.test(line)) unmarked.push(file + ': ' + line.trim())+ // …with where it goes (data-back="/plan"), for the page underneath; a bare attribute+ // would render as "true" and point the preview nowhere.+ if (/onClick=\{(\(\) => nav\(|back\}|home\})/.test(line) && !/data-back=/.test(line)) unmarked.push(file + ': ' + line.trim())}}expect(unmarked).toEqual([])})})++// TestFlight 1.4.2 (27): the page it goes back to shows underneath, sliding in from a little to+// the left (parallax) under a fading shade; App.jsx renders it when asked (BACK_PREVIEW_EVENT).+describe('the page underneath', () => {+ let events+ const stack = () => {+ document.body.innerHTML = `<div id="app"><div class="page" data-path="/plan/r/1"><button data-back="/plan">Back</button><div class="swrow">a set</div></div></div><div id="modal-root"></div>`+ back = document.querySelector('[data-back]'); back.onclick = vi.fn()+ row = document.querySelector('.swrow')+ }+ // What App.jsx does on the event: the page underneath appears (or goes) in #app.+ const onPreview = e => {+ events.push(e.detail)+ const app = document.getElementById('app')+ if ('path' in e.detail) {+ app.querySelector('.page.under')?.remove()+ if (e.detail.path) { const u = document.createElement('div'); u.className = 'page under'; u.dataset.path = e.detail.path; app.append(u) }+ }+ }+ beforeEach(() => { events = []; window.addEventListener(BACK_PREVIEW_EVENT, onPreview) })+ afterEach(() => window.removeEventListener(BACK_PREVIEW_EVENT, onPreview))++ it('is asked for as the edge touch is claimed, slides in with the page, and becomes the page on landing', () => {+ stack(); stop = installEdgeSwipeBack(window, { enabled: true })+ row.dispatchEvent(ptr('pointerdown', 6))+ expect(events).toEqual([{ path: '/plan' }])+ row.dispatchEvent(ptr('pointermove', 30))+ row.dispatchEvent(ptr('pointermove', 6 + W / 2))+ const top = document.querySelector('.page:not(.under)')+ const under = document.querySelector('.page.under')+ expect(top.style.transform).toBe(`translateX(${W / 2}px)`)+ expect(under.style.visibility).toBe('visible')+ expect(under.style.transform).toBe(`translateX(${-0.3 * 0.5 * W}px)`) // halfway in: -15%+ expect(document.querySelector('.edge-back-shade').style.opacity).toBe(String(0.5 * 0.35))+ expect(top.classList.contains('edge-back-page')).toBe(true)+ row.dispatchEvent(ptr('pointerup', 6 + W / 2))+ expect(under.style.transform).toBe('translateX(0px)') // slides fully in+ vi.advanceTimersByTime(261)+ expect(events.at(-1)).toEqual({ commit: '/plan' }) // App restores its scroll+ expect(back.onclick).toHaveBeenCalledTimes(1)+ expect(top.style.transform).toBe(`translateX(${W}px)`) // stays out: no flash back+ expect(events).not.toContainEqual({ path: null })+ // Two frames on, React has replaced it; a page still there (the button went nowhere) is reset.+ vi.advanceTimersByTime(100)+ expect(document.querySelector('.edge-back-shade')).toBeNull()+ expect(top.style.transform).toBe('')+ })++ it('a cancelled swipe slides it back out and has it taken away', () => {+ stack(); stop = installEdgeSwipeBack(window, { enabled: true })+ row.dispatchEvent(ptr('pointerdown', 6))+ row.dispatchEvent(ptr('pointermove', 30))+ row.dispatchEvent(ptr('pointermove', 60))+ row.dispatchEvent(ptr('pointerup', 60))+ expect(document.querySelector('.page.under').style.transform).toBe(`translateX(${-0.3 * W}px)`)+ vi.advanceTimersByTime(300)+ expect(events.at(-1)).toEqual({ path: null })+ expect(document.querySelector('.page.under')).toBeNull()+ expect(document.querySelector('.edge-back-shade')).toBeNull()+ expect(document.querySelector('.page').style.transform).toBe('')+ expect(back.onclick).not.toHaveBeenCalled()+ })++ it('a tap at the edge asks for it and then lets it go', () => {+ stack(); stop = installEdgeSwipeBack(window, { enabled: true })+ row.dispatchEvent(ptr('pointerdown', 6))+ row.dispatchEvent(ptr('pointerup', 6))+ expect(events).toEqual([{ path: '/plan' }, { path: null }])+ })++ it('right to left: it slides in from the right', () => {+ stack(); document.documentElement.dir = 'rtl'+ stop = installEdgeSwipeBack(window, { enabled: true })+ row.dispatchEvent(ptr('pointerdown', W - 6))+ row.dispatchEvent(ptr('pointermove', W - 30))+ row.dispatchEvent(ptr('pointermove', W - 6 - W / 2))+ expect(document.querySelector('.page.under').style.transform).toBe(`translateX(${0.3 * 0.5 * W}px)`)+ })++ it('with reduced motion it is never asked for: nothing slides, the page just goes back', () => {+ stack(); window.matchMedia = vi.fn(q => ({ matches: /reduce/.test(q) }))+ stop = installEdgeSwipeBack(window, { enabled: true })+ swipe(row, [6, 40, 250])+ expect(events.filter(e => 'path' in e)).toEqual([])+ expect(back.onclick).toHaveBeenCalledTimes(1)+ })++ it('a back button that cannot say where it goes (data-back="") swipes without one', () => {+ stack(); back.setAttribute('data-back', '')+ stop = installEdgeSwipeBack(window, { enabled: true })+ swipe(row, [6, 40, 250])+ vi.advanceTimersByTime(300)+ expect(events).toEqual([])+ expect(back.onclick).toHaveBeenCalledTimes(1)+ })+})diff --git a/frontend/src/lib/nav.js b/frontend/src/lib/nav.jsindex 0a5f1ff84..d3271c1b9 100644--- a/frontend/src/lib/nav.js+++ b/frontend/src/lib/nav.js@@ -4,6 +4,17 @@ export const setNav = fn => { _nav = fn }// `opts` goes to the router as is ({ replace: true }).export const nav = (to, opts) => (opts ? _nav(to, opts) : _nav(to))+// The route each history entry showed, by the router's index for it (App.jsx notes every one), so a+// back button that walks history (Settings) can say where it goes: the edge swipe back shows that+// page underneath while the finger moves (lib/edge-swipe-back.js).+const pathAt = new Map()+const idxNow = () => { try { return Number(globalThis.history?.state?.idx) || 0 } catch { return 0 } }+export const notePath = (path, key) => { pathAt.set(idxNow(), { path, key: key || null }) }+export const pathBefore = () => (idxNow() > 0 ? pathAt.get(idxNow() - 1)?.path || null : null)+/** The router key of the entry before this one, when it showed `path`: the page underneath an+ * edge swipe back is that entry's page, and a view keyed on its entry (Settings' search) reads it. */+export const keyBefore = path => { const e = idxNow() > 0 ? pathAt.get(idxNow() - 1) : null; return e && e.path === path ? e.key : null }+// Every open sheet sits on a history entry of its own (Modals.jsx), and closing it walks back// only while the page is still where the sheet opened. A sheet that closes and moves to another// page at once left that entry behind: back from the new page landed on it, the same page withdiff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsxindex 0b930714b..fe03e36bb 100644--- a/frontend/src/views/Admin.jsx+++ b/frontend/src/views/Admin.jsx@@ -283,7 +283,7 @@ export default function Admin() {return <div className="narrow"><div className="hdr">- <button className="iconbtn" data-back onClick={() => nav('/settings/account')} aria-label="Back"><Icon name="chevronLeft" /></button>+ <button className="iconbtn" data-back="/settings/account" onClick={() => nav('/settings/account')} aria-label="Back"><Icon name="chevronLeft" /></button><div style={{ flex: 1, marginInlineStart: 8 }}><h1 style={{ margin: 0 }}>Admin</h1><div className="sub">{users ? users.length + ' users · ' + activeCount + ' active this week' : usersErr ? 'Could not load' : 'Loading…'}</div></div><button className="iconbtn" onClick={() => { loadUsers(); loadInvites(); setTick(n => n + 1) }} aria-label="refresh">↻</button>diff --git a/frontend/src/views/CheckIn.jsx b/frontend/src/views/CheckIn.jsxindex 534c30f48..a932cf355 100644--- a/frontend/src/views/CheckIn.jsx+++ b/frontend/src/views/CheckIn.jsx@@ -70,7 +70,7 @@ export default function CheckIn() {return <div className="narrow"><div className="hdr">- <button className="iconbtn" data-back onClick={() => nav('/home')} aria-label={t('Home')}><Icon name="chevronLeft" /></button>+ <button className="iconbtn" data-back="/home" onClick={() => nav('/home')} aria-label={t('Home')}><Icon name="chevronLeft" /></button><div style={{ flex: 1 }}><h1 style={{ fontSize: 28 }}>{t('Check in')}</h1><div className="sub">{cards.length ? t('Show this at the gym') : t('Add your gym card')}</div>diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsxindex 7e4676dfe..a41694a9b 100644--- a/frontend/src/views/CoachChat.jsx+++ b/frontend/src/views/CoachChat.jsx@@ -190,7 +190,7 @@ export default function CoachChat() {return <div className="narrow chat"><div className="chat-hdr">- <button className="iconbtn" data-back onClick={() => nav('/plan')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>+ <button className="iconbtn" data-back="/plan" onClick={() => nav('/plan')} aria-label={t('Back')}><Icon name="chevronLeft" /></button><div className="chat-av"><Icon name="sparkles" /></div><div className="grow"><h1>{t('Coach')}</h1>diff --git a/frontend/src/views/CoachIntake.jsx b/frontend/src/views/CoachIntake.jsxindex c3b294586..f5a429536 100644--- a/frontend/src/views/CoachIntake.jsx+++ b/frontend/src/views/CoachIntake.jsx@@ -140,7 +140,7 @@ export default function CoachIntake() {return <div className="narrow ob"><div className="ob-top">- <button className="iconbtn" data-back onClick={back} aria-label={t('Back')}><Icon name="chevronLeft" /></button>+ <button className="iconbtn" data-back={step ? '' : editing ? '/coach' : '/plan'} onClick={back} aria-label={t('Back')}><Icon name="chevronLeft" /></button>{key !== 'consent' && <div className="ob-dots">{dots.map((s, i) => <span key={s} className={'ob-dot' + (i === dotIndex ? ' on' : i < dotIndex ? ' done' : '')} />)}</div>}diff --git a/frontend/src/views/CoachSetup.jsx b/frontend/src/views/CoachSetup.jsxindex 534a0b1a2..bd80af9df 100644--- a/frontend/src/views/CoachSetup.jsx+++ b/frontend/src/views/CoachSetup.jsx@@ -137,7 +137,7 @@ export default function CoachSetup() {return <div className="narrow"><div className="hdr">- <button className="iconbtn" data-back onClick={() => nav('/settings')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>+ <button className="iconbtn" data-back="/settings" onClick={() => nav('/settings')} aria-label={t('Back')}><Icon name="chevronLeft" /></button><div style={{ flex: 1, marginInlineStart: 10 }}><h1>{t('AI Coach')}</h1></div></div>diff --git a/frontend/src/views/History.jsx b/frontend/src/views/History.jsxindex 1b5d7f85e..504c45427 100644--- a/frontend/src/views/History.jsx+++ b/frontend/src/views/History.jsx@@ -21,7 +21,7 @@ export default function History() {const S = useStore(s => s.S)const rows = historyRows(S)return <>- <div className="hdr"><button className="iconbtn" data-back onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button>+ <div className="hdr"><button className="iconbtn" data-back="/stats" onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button><div style={{ flex: 1, marginInlineStart: 12 }}><h1>{t('History')}</h1><div className="sub">{tn('{0} workout', '{0} workouts', S.workouts.length)}</div></div></div><Button icon="plus" onClick={logPastWorkoutSheet} style={{ marginBottom: 12 }}>{t('Log a past workout')}</Button>{rows.length ? <div className="list">{rows.map(r => r.wdiff --git a/frontend/src/views/Measurements.jsx b/frontend/src/views/Measurements.jsxindex 8d679e279..ec78a7cba 100644--- a/frontend/src/views/Measurements.jsx+++ b/frontend/src/views/Measurements.jsx@@ -187,7 +187,7 @@ export default function Measurements() {return <div className="narrow"><div className="hdr">- <button className="iconbtn" data-back onClick={() => nav('/home')} aria-label={t('Home')}><Icon name="chevronLeft" /></button>+ <button className="iconbtn" data-back="/home" onClick={() => nav('/home')} aria-label={t('Home')}><Icon name="chevronLeft" /></button><div style={{ flex: 1, marginLeft: 10 }}><h1>{t('Body measurements')}</h1><div className="sub">{t('Circumference & composition')}</div></div><button className="iconbtn" onClick={manageMeasurementsSheet} aria-label={t('Choose measurements')}><Icon name="gear" /></button></div>diff --git a/frontend/src/views/Muscles.jsx b/frontend/src/views/Muscles.jsxindex e954189fc..2e76482a6 100644--- a/frontend/src/views/Muscles.jsx+++ b/frontend/src/views/Muscles.jsx@@ -7,7 +7,7 @@ import Icon from '../components/Icon.jsx'export default function Muscles() {const nav = useNavigate()return <>- <div className="hdr"><button className="iconbtn" data-back onClick={() => nav('/library')} aria-label={t('Exercises')}><Icon name="chevronLeft" /></button>+ <div className="hdr"><button className="iconbtn" data-back="/library" onClick={() => nav('/library')} aria-label={t('Exercises')}><Icon name="chevronLeft" /></button><div style={{ flex: 1, marginInlineStart: 12 }}><h1>{t('Explore muscles')}</h1><div className="sub">{t('Choose a muscle to see exercises that train it.')}</div></div></div><MuscleExplorer onDetail={exerciseDetailSheet} onPlan={addToRoutineSheet} />diff --git a/frontend/src/views/ProgressPhotos.jsx b/frontend/src/views/ProgressPhotos.jsxindex 68a2d342b..e4f455c6f 100644--- a/frontend/src/views/ProgressPhotos.jsx+++ b/frontend/src/views/ProgressPhotos.jsx@@ -170,7 +170,7 @@ export default function ProgressPhotos() {}return <>- <div className="hdr"><button className="iconbtn" data-back onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button>+ <div className="hdr"><button className="iconbtn" data-back="/stats" onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button><div style={{ flex: 1, marginInlineStart: 12 }}><h1>{t('Progress photos')}</h1><div className="sub">{tn('{0} photo', '{0} photos', photos.length)}</div></div>{photos.length >= 2 && (comparingdiff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsxindex db8573bb9..9bc34490b 100644--- a/frontend/src/views/RoutineEdit.jsx+++ b/frontend/src/views/RoutineEdit.jsx@@ -464,7 +464,7 @@ export default function RoutineEdit() {return <div className="narrow"><div className="hdr">- <button className="iconbtn" data-back onClick={() => nav('/plan')} aria-label={t('Plan')}><Icon name="chevronLeft" /></button>+ <button className="iconbtn" data-back="/plan" onClick={() => nav('/plan')} aria-label={t('Plan')}><Icon name="chevronLeft" /></button><div style={{ flex: 1, margin: '0 12px' }}><input className="input" defaultValue={r.name} style={{ fontWeight: 600, fontSize: 20, letterSpacing: '-.021em' }}onChange={e => update(s => { s.routines.find(x => x.id === id).name = e.target.value.trim() || t('Routine') })} />diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 455a85d85..af0e287f6 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -46,6 +46,7 @@ import { usePasskeys, PasskeysRow, DeviceLinkRow, openDeviceLinkRedeem } from '.import { DeleteAccountRow } from '../components/DeleteAccount.jsx'import { Section, Row, SelectRow, Switch, Segmented, Button, TextField, SearchField } from '../components/ui.jsx'import { PAGES, ROOT_GROUPS, pageVisible, searchSettings, pageTrail } from './settings-pages.js'+import { pathBefore } from '../lib/nav.js'/* Settings (v1.3.11). The root is one screen: an account card, eleven rows that each open a page(/settings/<page>), and a search over every row. Rare things live one level further down@@ -67,7 +68,7 @@ export function SettingsRoute() {const ctx = { user: useStore(s => s.user), mobile: MOBILE }if (page && (!PAGES[page] || !pageVisible(PAGES[page].parent || page, ctx))) return <Navigate to="/settings" replace />if (page === 'coach') return <Navigate to="/coach/setup" replace />- return <Settings key={page || 'root'} page={page || null} find={loc.state?.find || null} via={loc.state?.via || null} />+ return <Settings key={page || 'root'} page={page || null} find={loc.state?.find || null} via={loc.state?.via || null} entryKey={loc.key} />}// "Mon" / "Sun" in the app's language, for the Plan & schedule row's preview.@@ -80,7 +81,7 @@ const standalone = () => {try { return !!(window.matchMedia?.('(display-mode: standalone)').matches || window.navigator.standalone === true) } catch { return false }}-export default function Settings({ page = null, find = null, via = null }) {+export default function Settings({ page = null, find = null, via = null, entryKey = null }) {const nav = useNavigate()const S = useStore(s => s.S)const user = useStore(s => s.user)@@ -918,7 +919,7 @@ export default function Settings({ page = null, find = null, via = null }) {<div className="sp-nav">{/* Named by what it says ("Settings", "Workout"), so a voice command for the visibleword finds it; the chevron is hidden from assistive tech. */}- <button className="sp-back" data-back onClick={back}>+ <button className="sp-back" data-back={((window.history.state?.idx || 0) > 0 ? pathBefore() : null) || (parent ? '/settings/' + parent : '/settings')} onClick={back}><Icon name="chevronLeft" /><span>{parent ? t(PAGES[parent].title) : t('Settings')}</span></button><h1 className="sp-title">{t(PAGES[page].title)}</h1>@@ -928,16 +929,17 @@ export default function Settings({ page = null, find = null, via = null }) {}/* ---------------- the root ---------------- */- return <SettingsRoot ctx={ctx} preview={preview} open={open} user={user} sync={sync}+ return <SettingsRoot ctx={ctx} preview={preview} open={open} user={user} sync={sync} entryKey={entryKey}home={() => nav('/home')} go={(hit) => {if (hit.page === 'coach') { nav('/coach/setup'); return }nav('/settings/' + hit.page, hit.isPage ? undefined : { state: hit.via ? { find: hit.title, via: hit.via } : { find: hit.title } })}} />}-function SettingsRoot({ ctx, preview, open, user, sync, home, go }) {- // The router's key for this history entry (what useLocation().key reads), taken once.- const [key] = useState(() => window.history.state?.key || null)+function SettingsRoot({ ctx, preview, open, user, sync, home, go, entryKey }) {+ // The router's key for this history entry, taken once. From the router rather than+ // window.history: drawn under an edge swipe back the page is the entry before the current one.+ const [key] = useState(() => (entryKey && entryKey !== 'default' && entryKey !== 'back-preview' ? entryKey : window.history.state?.key || null))const [q, setQ] = useState(() => (key && lastQuery.key === key ? lastQuery.q : ''))const set = v => { lastQuery = { q: v, key }; setQ(v) }const hits = q.trim() ? searchSettings(q, ctx) : null@@ -952,7 +954,7 @@ function SettingsRoot({ ctx, preview, open, user, sync, home, go }) {const initial = user && !DEMO ? String(user.name || '?').trim().charAt(0).toUpperCase() : nullreturn <div className="narrow"><div className="sp-nav">- <button className="sp-back" data-back onClick={home} aria-label={t('Home')}><Icon name="chevronLeft" /><span>{t('Home')}</span></button>+ <button className="sp-back" data-back="/home" onClick={home} aria-label={t('Home')}><Icon name="chevronLeft" /><span>{t('Home')}</span></button></div><h1 className="sp-root-title">{t('Settings')}</h1><div className="sp-search">diff --git a/frontend/src/views/StructuralBalance.jsx b/frontend/src/views/StructuralBalance.jsxindex e140f8c82..b895aad81 100644--- a/frontend/src/views/StructuralBalance.jsx+++ b/frontend/src/views/StructuralBalance.jsx@@ -42,7 +42,7 @@ export default function StructuralBalance() {}return <>- <div className="hdr"><button className="iconbtn" data-back onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button>+ <div className="hdr"><button className="iconbtn" data-back="/stats" onClick={() => nav('/stats')} aria-label={t('Stats')}><Icon name="chevronLeft" /></button><div style={{ flex: 1, marginInlineStart: 12 }}><h1>{t('Structural balance')}</h1><div className="sub">{t('Compare your lifts against a published ratio table to find the weak link.')}</div></div></div>