From e3541535e278381bce817e69ff21b40d83a2e512 Mon Sep 17 00:00:00 2001 From: Maurice Date: Fri, 6 Nov 2026 15:37:55 +0100 Subject: [PATCH] fix(native): first visits no longer wait behind the offline warm-up, day rail follows the swipe The iOS app pulls every file of a build into WebKit's cache so it can start offline. It did so four at a time at normal priority, for all 1,900 files of every new build including all 27 translations, and a page opened meanwhile queued behind it: right after a server update, a first visit to Vacay took five to seven seconds. The warm-up now runs two at a time at low priority, takes only the user's language and English, and walks a build once. The day rail in the trip header lit the new day only after the pager's snap had landed and the plan had re-rendered, a second or two after the swipe. The pager now reports the day a swipe heads for as soon as its page is the nearer one, and the rail and its pill move with the finger; the plan still switches when the snap lands. --- .../src/mobile/components/MDayPager.test.tsx | 16 ++++++ client/src/mobile/components/MDayPager.tsx | 45 +++++++++++++-- client/src/mobile/dayPreviewStore.ts | 17 ++++++ client/src/mobile/mobile.css | 10 ++-- client/src/mobile/routeTransition.ts | 2 +- client/src/mobile/screens/trip/MTripShell.tsx | 14 +++-- .../screens/trip/plan/MPlanTimeline.tsx | 3 + .../screens/trip/roadtrip/MRoadtripTab.tsx | 3 + client/src/native/nativeApp.ts | 3 +- client/src/native/offlineShell.test.ts | 32 +++++++++++ client/src/native/offlineShell.ts | 57 ++++++++++++++++--- client/src/utils/lazyWithRetry.ts | 24 ++++++++ 12 files changed, 204 insertions(+), 22 deletions(-) create mode 100644 client/src/mobile/dayPreviewStore.ts diff --git a/client/src/mobile/components/MDayPager.test.tsx b/client/src/mobile/components/MDayPager.test.tsx index 60b064a6e..e394c6f88 100644 --- a/client/src/mobile/components/MDayPager.test.tsx +++ b/client/src/mobile/components/MDayPager.test.tsx @@ -82,6 +82,22 @@ describe('MDayPager', () => { expect(screen.getByRole('status')).toHaveTextContent('day 3 of 4'); }); + it('previews the day a swipe heads for while the strip still moves, and takes it back', () => { + const onPreview = vi.fn(); + const { strip, onSelectDay } = setup(2, { onPreview }); + + place(strip, 3, true); + fireEvent.scroll(strip); + fireEvent.scroll(strip); + expect(onPreview).toHaveBeenCalledTimes(1); + expect(onPreview).toHaveBeenLastCalledWith(3); + expect(onSelectDay).not.toHaveBeenCalled(); + + place(strip, 2, true); + fireEvent.scroll(strip); + expect(onPreview).toHaveBeenLastCalledWith(null); + }); + it('asks once, however many events report the same landing', () => { const { strip, onSelectDay } = setup(2); diff --git a/client/src/mobile/components/MDayPager.tsx b/client/src/mobile/components/MDayPager.tsx index b40d80478..c87489f0b 100644 --- a/client/src/mobile/components/MDayPager.tsx +++ b/client/src/mobile/components/MDayPager.tsx @@ -47,6 +47,12 @@ export interface MDayPagerProps { * (Vacay's month editor and year grid) rather than over the whole screen. */ inFlow?: boolean; + /** + * The day a swipe is heading for, as soon as its page is the nearer one, and + * null when the swipe falls back: lets a day rail follow the finger before + * the snap lands and onSelectDay fires. + */ + onPreview?: (dayId: number | null) => void; } interface Page { @@ -84,6 +90,7 @@ export default function MDayPager({ locked = false, describeDay, inFlow = false, + onPreview, }: MDayPagerProps) { const stripRef = useRef(null); const [announcement, setAnnouncement] = useState(''); @@ -91,8 +98,8 @@ export default function MDayPager({ const windowKey = pages.map((p) => p.key).join(','); // The handlers below are attached once, so they read the props through here. - const latest = useRef({ days, onSelectDay, describeDay, selectedDayId }); - latest.current = { days, onSelectDay, describeDay, selectedDayId }; + const latest = useRef({ days, onSelectDay, describeDay, selectedDayId, onPreview }); + latest.current = { days, onSelectDay, describeDay, selectedDayId, onPreview }; /** The day a landed swipe asked for, until the selection catches up. Stops a * late scroll event from selecting it twice. */ const requested = useRef(null); @@ -126,6 +133,31 @@ export default function MDayPager({ if (!strip) return; let timer = 0; let touching = false; + let previewed: number | null = null; + + // The nearer page while the strip moves: a page past the middle is where the + // swipe will land unless the finger turns back. + const preview = () => { + const notify = latest.current.onPreview; + if (!notify) return; + const left = strip.getBoundingClientRect().left; + let nearest: HTMLElement | null = null; + let distance = Infinity; + for (const child of Array.from(strip.children) as HTMLElement[]) { + const d = Math.abs(child.getBoundingClientRect().left - left); + if (d < distance) { + distance = d; + nearest = child; + } + } + if (!nearest) return; + const raw = nearest.hasAttribute('data-page-active') ? '' : nearest.dataset.dayId; + const dayId = raw ? Number(raw) : null; + const next = dayId != null && Number.isFinite(dayId) ? dayId : null; + if (next === previewed) return; + previewed = next; + notify(next); + }; const settle = () => { if (touching) return; @@ -140,6 +172,7 @@ export default function MDayPager({ const dayId = raw ? Number(raw) : NaN; if (!Number.isFinite(dayId) || requested.current === dayId) return; requested.current = dayId; + previewed = null; const s = latest.current; tickHaptic(); s.onSelectDay(dayId); @@ -162,14 +195,18 @@ export default function MDayPager({ later(); }; - strip.addEventListener('scroll', later, { passive: true }); + const onScroll = () => { + preview(); + later(); + }; + strip.addEventListener('scroll', onScroll, { passive: true }); strip.addEventListener('scrollend', onScrollEnd); strip.addEventListener('touchstart', onTouchStart, { passive: true }); strip.addEventListener('touchend', onTouchEnd, { passive: true }); strip.addEventListener('touchcancel', onTouchEnd, { passive: true }); return () => { window.clearTimeout(timer); - strip.removeEventListener('scroll', later); + strip.removeEventListener('scroll', onScroll); strip.removeEventListener('scrollend', onScrollEnd); strip.removeEventListener('touchstart', onTouchStart); strip.removeEventListener('touchend', onTouchEnd); diff --git a/client/src/mobile/dayPreviewStore.ts b/client/src/mobile/dayPreviewStore.ts new file mode 100644 index 000000000..a8ce64c87 --- /dev/null +++ b/client/src/mobile/dayPreviewStore.ts @@ -0,0 +1,17 @@ +import { create } from 'zustand'; + +/** + * The day a swipe is heading for, before the pager has settled on it. The day + * rail in the trip header lights that chip at once, the way a native tab strip + * follows the finger, while the plan itself switches only when the snap lands + * (MDayPager's onSelectDay). Null when no swipe is under way. + */ +interface DayPreviewState { + dayId: number | null; + setDayId: (dayId: number | null) => void; +} + +export const useDayPreviewStore = create((set) => ({ + dayId: null, + setDayId: (dayId) => set((s) => (s.dayId === dayId ? s : { dayId })), +})); diff --git a/client/src/mobile/mobile.css b/client/src/mobile/mobile.css index 6a435fcb3..58e2ec802 100644 --- a/client/src/mobile/mobile.css +++ b/client/src/mobile/mobile.css @@ -453,23 +453,23 @@ } } :root[data-route-transition='forward']::view-transition-old(root) { - animation: m-vt-out-leading 0.4s cubic-bezier(0.32, 0.72, 0, 1) both; + animation: m-vt-out-leading 0.3s cubic-bezier(0.32, 0.72, 0, 1) both; } :root[data-route-transition='forward']::view-transition-new(root) { - animation: m-vt-in-trailing 0.4s cubic-bezier(0.32, 0.72, 0, 1) both; + animation: m-vt-in-trailing 0.3s cubic-bezier(0.32, 0.72, 0, 1) both; box-shadow: -16px 0 40px -12px rgb(0 0 0 / 0.35); } :root[data-route-transition='back']::view-transition-old(root) { z-index: 1; - animation: m-vt-out-trailing 0.34s cubic-bezier(0.32, 0.72, 0, 1) both; + animation: m-vt-out-trailing 0.26s cubic-bezier(0.32, 0.72, 0, 1) both; box-shadow: -16px 0 40px -12px rgb(0 0 0 / 0.35); } :root[data-route-transition='back']::view-transition-new(root) { - animation: m-vt-in-leading 0.34s cubic-bezier(0.32, 0.72, 0, 1) both; + animation: m-vt-in-leading 0.26s cubic-bezier(0.32, 0.72, 0, 1) both; } :root[data-route-transition='tab']::view-transition-old(root), :root[data-route-transition='tab']::view-transition-new(root) { - animation-duration: 0.18s; + animation-duration: 0.15s; } @media (prefers-reduced-motion: reduce) { ::view-transition-group(*), diff --git a/client/src/mobile/routeTransition.ts b/client/src/mobile/routeTransition.ts index 84c7ffdde..6296bb61d 100644 --- a/client/src/mobile/routeTransition.ts +++ b/client/src/mobile/routeTransition.ts @@ -18,7 +18,7 @@ import type { Location, NavigationType } from 'react-router'; */ export type RouteTransitionKind = 'forward' | 'back' | 'tab'; -const SETTLE_MS = 800; +const SETTLE_MS = 300; let skipNext = false; let current: ViewTransition | null = null; diff --git a/client/src/mobile/screens/trip/MTripShell.tsx b/client/src/mobile/screens/trip/MTripShell.tsx index 95526dd92..1b196b242 100644 --- a/client/src/mobile/screens/trip/MTripShell.tsx +++ b/client/src/mobile/screens/trip/MTripShell.tsx @@ -28,6 +28,7 @@ import { canManageDocSync } from '../../../components/Files/docsync/useDocSync' import { useDocSyncOffered } from '../../../components/Files/docsync/useDocSyncOffered' import type { Day, Trip } from '../../../types' import { getIntlLanguage } from '@trek/shared' +import { useDayPreviewStore } from '../../dayPreviewStore' /** * Mobile trip screen frame. Owns the chrome the design shares across every @@ -271,11 +272,16 @@ export default function MTripShell({ // The opening day is chosen while the splash still covers the shell (#2880), // so the rail itself is a dependency: the chip is lined up when the rail // appears, in place rather than gliding across a rail nobody has seen yet. + // The rail lights the day a swipe is heading for before the plan switches (dayPreviewStore). + const previewDayId = useDayPreviewStore(s => s.dayId) + const clearDayPreview = useDayPreviewStore(s => s.setDayId) + useEffect(() => { clearDayPreview(null) }, [planner.selectedDayId, clearDayPreview]) + const railDayId = previewDayId ?? planner.selectedDayId const chipRefs = useRef(new Map()) const [dayRail, setDayRail] = useState(null) const alignedRailRef = useRef(null) useLayoutEffect(() => { - const chip = planner.selectedDayId != null ? chipRefs.current.get(planner.selectedDayId) : undefined + const chip = railDayId != null ? chipRefs.current.get(railDayId) : undefined if (!chip || !dayRail) return const firstView = alignedRailRef.current !== dayRail alignedRailRef.current = dayRail @@ -290,7 +296,7 @@ export default function MTripShell({ inline: 'center', block: 'nearest', }) - }, [planner.selectedDayId, days, dayRail]) + }, [railDayId, days, dayRail]) // The active day's pill glides to the next chip rather than jumping there. // A booking document shared to TREK, and this trip picked for it: open the import. const sharedTripId = useSharedImportStore(s => s.tripId) @@ -300,7 +306,7 @@ export default function MTripShell({ planner.setShowBookingImport(true) // eslint-disable-next-line react-hooks/exhaustive-deps }, [sharedTripId, tripId]) - const dayPill = useActivePill(dayRail, '[aria-current="true"]', [planner.selectedDayId, days, dayRail, language]) + const dayPill = useActivePill(dayRail, '[aria-current="true"]', [railDayId, days, dayRail, language]) const trTab = planner.activeTab @@ -515,7 +521,7 @@ export default function MTripShell({ /> )} {days.map((day, idx) => { - const active = day.id === planner.selectedDayId + const active = day.id === railDayId const isToday = day.id === todayDayId const tint = dayTints[day.id] return ( diff --git a/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx b/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx index b286fba16..65f040688 100644 --- a/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx +++ b/client/src/mobile/screens/trip/plan/MPlanTimeline.tsx @@ -26,6 +26,7 @@ import type { ReactNode } from 'react' import { useSettingsStore } from '../../../../store/settingsStore' import MRouteAppsSheet, { openRouteTarget } from './MRouteAppsSheet' import MDayPager from '../../../components/MDayPager' +import { useDayPreviewStore } from '../../../dayPreviewStore' /** * Plan-tab timeline of the mobile trip screen: the UP-NEXT card in go mode, @@ -60,6 +61,7 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) { const isTouch = useIsTouch() useTouchDragBridge(editing && isTouch) const [dragging, setDragging] = useState(false) + const setDayPreview = useDayPreviewStore(s => s.setDayId) return (
@@ -72,6 +74,7 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) { // skipFit, exactly like the chip tap in plan view: the map underneath stays // mounted, and re-framing it here would move it somewhere nobody asked for. onSelectDay={dayId => planner.handleSelectDay(dayId, true)} + onPreview={setDayPreview} locked={dragging || legMenu.menu != null} describeDay={(i, n) => t('mobileTrip.dayAnnounce', { current: i + 1, total: n })} renderDay={(dayId, active) => ( diff --git a/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx b/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx index 44d7f7b66..56e964e5b 100644 --- a/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx +++ b/client/src/mobile/screens/trip/roadtrip/MRoadtripTab.tsx @@ -24,6 +24,7 @@ import { bookendBooking } from '../../../../components/Roadtrip/nightBookend' import { getDayOrder } from '../../../../utils/dayOrder' import { undatedRides } from '@trek/shared/roadtrip' import type { Reservation, TranslationFn } from '../../../../types' +import { useDayPreviewStore } from '../../../dayPreviewStore' /** * The road trip tab: one day of the drive, as a chain or on the map. @@ -39,6 +40,7 @@ import type { Reservation, TranslationFn } from '../../../../types' * scroll, the day tints, the label format and the second tap that opens the day sheet. */ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) { + const setDayPreview = useDayPreviewStore(s => s.setDayId) const { t, days } = planner const rt = useMRoadtrip(planner) const corridor = useMRtCorridor(planner, shell) @@ -107,6 +109,7 @@ export default function MRoadtripTab({ planner, shell }: MTripTabPanelProps) { // skipFit: the map underneath stays mounted, and the stage's own focus points // frame it as soon as the selection moves. onSelectDay={dayId => planner.handleSelectDay(dayId, true)} + onPreview={setDayPreview} locked={!!shell.sheet} describeDay={(i, n) => t('mobileTrip.dayAnnounce', { current: i + 1, total: n })} renderDay={dayId => ( diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts index 059f1c231..5c14c10c1 100644 --- a/client/src/native/nativeApp.ts +++ b/client/src/native/nativeApp.ts @@ -3,6 +3,7 @@ import { Keyboard } from '@capacitor/keyboard'; import { SplashScreen } from '@capacitor/splash-screen'; import { StatusBar, Style } from '@capacitor/status-bar'; import { closeTopOverlay } from '../mobile/overlayStack'; +import { useSettingsStore } from '../store/settingsStore'; import { isEffectivelyOffline } from '../sync/networkMode'; import { checkAppUpdate, loadNativeCapabilities } from './capabilities'; import { installNativeGeolocation } from './geolocation'; @@ -64,7 +65,7 @@ export function startNativeApp(): void { if (isEffectivelyOffline()) return; // Not refreshed this time is no harm: the next launch tries again. An app // older than the offline copy has no such method, which is no failure. - keepOfflineShellFresh().catch((err: unknown) => { + keepOfflineShellFresh(fetch, useSettingsStore.getState().settings.language).catch((err: unknown) => { if (!isUnimplemented(err)) reportNativeFailure(err); }); }, OFFLINE_SHELL_DELAY_MS); diff --git a/client/src/native/offlineShell.test.ts b/client/src/native/offlineShell.test.ts index 2c479d514..735c58183 100644 --- a/client/src/native/offlineShell.test.ts +++ b/client/src/native/offlineShell.test.ts @@ -17,6 +17,7 @@ const manifest = { beforeEach(() => { vi.mocked(TrekShell.refreshOfflineCopy).mockReset().mockResolvedValue({ saved: true }); + window.localStorage.clear(); }); describe('manifestFiles', () => { @@ -67,4 +68,35 @@ describe('keepOfflineShellFresh', () => { await keepOfflineShellFresh(fetchImpl); expect(fetchImpl).toHaveBeenCalledTimes(1); }); + + it('fetches at low priority, only the own language, and once per build', async () => { + const withLocales = { + ...manifest, + '../shared/dist/i18n/de/index.mjs': { file: 'assets/de-aaaa1111.js' }, + '../shared/dist/i18n/fr/index.mjs': { file: 'assets/fr-bbbb2222.js' }, + '../shared/dist/i18n/en/index.mjs': { file: 'assets/en-cccc3333.js' }, + }; + const inits: (RequestInit | undefined)[] = []; + const fetched: string[] = []; + const fetchImpl = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + if (url === '/asset-manifest.json') return new Response(JSON.stringify(withLocales)); + fetched.push(url); + inits.push(init); + return new Response('x'); + }) as unknown as typeof fetch; + + await keepOfflineShellFresh(fetchImpl, 'de'); + expect(fetched).toContain('/assets/de-aaaa1111.js'); + expect(fetched).toContain('/assets/en-cccc3333.js'); + expect(fetched).not.toContain('/assets/fr-bbbb2222.js'); + expect(inits.every((i) => (i as { priority?: string } | undefined)?.priority === 'low')).toBe(true); + + const before = fetched.length; + await keepOfflineShellFresh(fetchImpl, 'de'); + expect(fetched.length).toBe(before); + + await keepOfflineShellFresh(fetchImpl, 'fr'); + expect(fetched).toContain('/assets/fr-bbbb2222.js'); + }); }); diff --git a/client/src/native/offlineShell.ts b/client/src/native/offlineShell.ts index f509ba160..e30b9b1d3 100644 --- a/client/src/native/offlineShell.ts +++ b/client/src/native/offlineShell.ts @@ -11,7 +11,16 @@ import { TrekShell } from './trekShell'; */ const MANIFEST_URL = '/asset-manifest.json'; -const CONCURRENCY = 4; +/** + * Few at a time and at low priority: the warm-up runs while the user already + * moves through the app, and the page they open must never queue behind it. + * Measured on a phone: four at normal priority held a first visit to Vacay + * back by five to seven seconds right after a server update. + */ +const CONCURRENCY = 2; +/** The build whose files are all in the cache; a launch on the same build skips the walk. */ +const WARMED_KEY = 'trek.offlineShellBuild'; +const LOCALE_KEY = /\/i18n\/([^/]+)\/index\.[cm]?js$/; interface ManifestChunk { file?: string; @@ -19,10 +28,18 @@ interface ManifestChunk { assets?: string[]; } -export function manifestFiles(manifest: unknown): string[] { +/** + * Every file of the build, without the translations of other languages: only + * the user's own and English (the fallback) are needed offline, the other 25 + * would cost several megabytes per build for nothing. + */ +export function manifestFiles(manifest: unknown, language?: string): string[] { if (typeof manifest !== 'object' || manifest === null) return []; + const keep = new Set(['en', language ?? 'en']); const files = new Set(); - for (const chunk of Object.values(manifest as Record)) { + for (const [key, chunk] of Object.entries(manifest as Record)) { + const locale = LOCALE_KEY.exec(key)?.[1]; + if (locale && !keep.has(locale)) continue; if (typeof chunk?.file === 'string') files.add(chunk.file); for (const list of [chunk?.css, chunk?.assets]) { if (Array.isArray(list)) list.forEach((f) => typeof f === 'string' && files.add(f)); @@ -31,24 +48,50 @@ export function manifestFiles(manifest: unknown): string[] { return [...files]; } -async function warmCache(files: string[], fetchFile: (path: string) => Promise): Promise { +/** True when every file was fetched. */ +async function warmCache(files: string[], fetchFile: (path: string) => Promise): Promise { const queue = [...files]; + let complete = true; const worker = async (): Promise => { for (let path = queue.shift(); path !== undefined; path = queue.shift()) { try { await fetchFile(`/${path}`); } catch { // One missing chunk must not stop the rest; the next launch tries again. + complete = false; } } }; await Promise.all(Array.from({ length: CONCURRENCY }, worker)); + return complete; } -export async function keepOfflineShellFresh(fetchImpl: typeof fetch = fetch): Promise { +function warmedBuild(): string | null { + try { + return window.localStorage.getItem(WARMED_KEY); + } catch { + return null; + } +} + +function rememberWarmed(build: string): void { + try { + window.localStorage.setItem(WARMED_KEY, build); + } catch { + // Not remembered: the next launch walks the files again, from the cache. + } +} + +export async function keepOfflineShellFresh(fetchImpl: typeof fetch = fetch, language?: string): Promise { await TrekShell.refreshOfflineCopy(); const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' }); if (!response.ok) return; - const files = manifestFiles(await response.json()); - await warmCache(files, (path) => fetchImpl(path).then((r) => r.blob())); + const files = manifestFiles(await response.json(), language); + // The build and the language together: a new language needs its own chunk. + const build = `${[...files].sort().find((f) => /index-[^/]+\.js$/.test(f)) ?? files.length}:${language ?? 'en'}`; + if (warmedBuild() === build) return; + const complete = await warmCache(files, (path) => + fetchImpl(path, { priority: 'low' } as RequestInit).then((r) => r.blob()) + ); + if (complete) rememberWarmed(build); } diff --git a/client/src/utils/lazyWithRetry.ts b/client/src/utils/lazyWithRetry.ts index 22a4b502e..454d94806 100644 --- a/client/src/utils/lazyWithRetry.ts +++ b/client/src/utils/lazyWithRetry.ts @@ -44,9 +44,33 @@ export function retryUrlFor(error: unknown): string | null { return busted.href; } +/** Every route loader, so the phone can fetch them ahead while idle (preloadLazyRoutes). */ +const loaders: (() => Promise)[] = []; + +/** + * Fetches every lazily loaded page in the background, a few at a time, so + * opening one later does not wait for the network. A loader that fails is + * simply tried again when the page is opened. Skipped where the user asked to + * save data. + */ +export function preloadLazyRoutes(): void { + const connection = (navigator as { connection?: { saveData?: boolean } }).connection; + if (connection?.saveData) return; + const queue = [...loaders]; + const next = () => { + const load = queue.shift(); + if (!load) return; + void load() + .catch(() => {}) + .then(next); + }; + for (let i = 0; i < 3; i++) next(); +} + export function lazyWithRetry>( load: () => Promise<{ default: T }> ): LazyExoticComponent { + loaders.push(load); return lazy(() => load() .catch((error: unknown) => {