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.
This commit is contained in:
Maurice
2026-11-06 15:37:55 +01:00
parent 431cc226e3
commit e3541535e2
12 changed files with 204 additions and 22 deletions
@@ -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);
+41 -4
View File
@@ -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<HTMLDivElement>(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<number | null>(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);
+17
View File
@@ -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<DayPreviewState>((set) => ({
dayId: null,
setDayId: (dayId) => set((s) => (s.dayId === dayId ? s : { dayId })),
}));
+5 -5
View File
@@ -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(*),
+1 -1
View File
@@ -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;
+10 -4
View File
@@ -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<number, HTMLButtonElement>())
const [dayRail, setDayRail] = useState<HTMLDivElement | null>(null)
const alignedRailRef = useRef<HTMLDivElement | null>(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 (
@@ -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 (
<div className="absolute inset-0">
@@ -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) => (
@@ -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 => (
+2 -1
View File
@@ -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);
+32
View File
@@ -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');
});
});
+50 -7
View File
@@ -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<string>();
for (const chunk of Object.values(manifest as Record<string, ManifestChunk>)) {
for (const [key, chunk] of Object.entries(manifest as Record<string, ManifestChunk>)) {
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<unknown>): Promise<void> {
/** True when every file was fetched. */
async function warmCache(files: string[], fetchFile: (path: string) => Promise<unknown>): Promise<boolean> {
const queue = [...files];
let complete = true;
const worker = async (): Promise<void> => {
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<void> {
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<void> {
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);
}
+24
View File
@@ -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<unknown>)[] = [];
/**
* 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<T extends ComponentType<any>>(
load: () => Promise<{ default: T }>
): LazyExoticComponent<T> {
loaders.push(load);
return lazy(() =>
load()
.catch((error: unknown) => {