mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 06:37:33 +00:00
fix(native): start without the server on Android and keep the offline start on iOS
A tester with a server on his home network could not open the Android app
away from it: after closing the app and turning Wi-Fi off it stayed on the
address screen ("No server answered at this address").
- Android keeps the server's UI itself (TrekOfflineShell): the start page
and every file of the build, listed by native/offlineShell.ts from the
server's manifest and downloaded natively. A web view runs no service
worker on a plain-http server, the usual address of a server at home, so
the old "Android has the service worker" assumption did not hold.
- Without a network, or once the server failed to load twice, the web view
serves the copy under the server's origin with Capacitor's bridge; the UI
runs on its own offline data and the API answers again once the server
is back. The address screen opens the copy too (openOfflineCopy).
- The check an update asks for no longer locks the app out offline: on both
platforms a server out of reach is put back on its copy and checked on
the next launch that reaches it. iOS no longer throws its copy away when
the update check runs.
This commit is contained in:
@@ -10,7 +10,7 @@ import { installNativeGeolocation } from './geolocation';
|
||||
import { prepareKeyboardFields } from './keyboardFields';
|
||||
import { scrollToTop, startNativeApp } from './nativeApp';
|
||||
import { keepOfflineShellFresh } from './offlineShell';
|
||||
import { isNativeApp, isNativeIos } from './platform';
|
||||
import { isNativeAndroid, isNativeApp, isNativeIos } from './platform';
|
||||
import { openPushTarget } from './push';
|
||||
import { trackTouchInput } from './touchInput';
|
||||
|
||||
@@ -22,7 +22,7 @@ vi.mock('@capacitor/keyboard', () => ({
|
||||
}));
|
||||
vi.mock('@capacitor/splash-screen', () => ({ SplashScreen: { hide: vi.fn() } }));
|
||||
vi.mock('@capacitor/status-bar', () => ({ StatusBar: { setStyle: vi.fn() }, Style: { Dark: 'DARK', Light: 'LIGHT' } }));
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn() }));
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeIos: vi.fn(), isNativeAndroid: vi.fn() }));
|
||||
vi.mock('./offlineShell', () => ({ keepOfflineShellFresh: vi.fn() }));
|
||||
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn() }));
|
||||
vi.mock('./capabilities', () => ({
|
||||
@@ -50,6 +50,7 @@ beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(isNativeApp).mockReturnValue(true);
|
||||
vi.mocked(isNativeIos).mockReturnValue(false);
|
||||
vi.mocked(isNativeAndroid).mockReturnValue(false);
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
|
||||
vi.mocked(keepOfflineShellFresh).mockResolvedValue();
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(false);
|
||||
@@ -153,18 +154,19 @@ describe('startNativeApp', () => {
|
||||
startNativeApp();
|
||||
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(15_000);
|
||||
expect(keepOfflineShellFresh).toHaveBeenCalled();
|
||||
expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(false);
|
||||
});
|
||||
|
||||
it('skips the refresh while offline, and never on Android', () => {
|
||||
vi.mocked(isNativeIos).mockReturnValue(true);
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
|
||||
it('refreshes it on Android too, into the store of the app', () => {
|
||||
vi.mocked(isNativeAndroid).mockReturnValue(true);
|
||||
startNativeApp();
|
||||
vi.advanceTimersByTime(15_000);
|
||||
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
|
||||
expect(vi.mocked(keepOfflineShellFresh).mock.calls[0]?.[2]).toBe(true);
|
||||
});
|
||||
|
||||
vi.mocked(isNativeIos).mockReturnValue(false);
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
|
||||
it('skips the refresh while offline', () => {
|
||||
vi.mocked(isNativeIos).mockReturnValue(true);
|
||||
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
|
||||
startNativeApp();
|
||||
vi.advanceTimersByTime(15_000);
|
||||
expect(keepOfflineShellFresh).not.toHaveBeenCalled();
|
||||
|
||||
@@ -11,7 +11,7 @@ import { fadeInImages } from './imageFade';
|
||||
import { keepFieldInView } from './keepFieldInView';
|
||||
import { prepareKeyboardFields } from './keyboardFields';
|
||||
import { keepOfflineShellFresh } from './offlineShell';
|
||||
import { isNativeApp, isNativeIos } from './platform';
|
||||
import { isNativeAndroid, isNativeApp, isNativeIos } from './platform';
|
||||
import { openPushTarget, startNativePush } from './push';
|
||||
import { startQuickActions } from './quickActions';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
@@ -88,15 +88,20 @@ export function startNativeApp(): void {
|
||||
// The "‹ › Done" strip above the keyboard is a web form's, not an app's.
|
||||
void Keyboard.setAccessoryBarVisible({ isVisible: false });
|
||||
keepFieldInView(Keyboard);
|
||||
window.setTimeout(() => {
|
||||
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(fetch, useSettingsStore.getState().settings.language).catch((err: unknown) => {
|
||||
if (!isUnimplemented(err)) reportNativeFailure(err);
|
||||
});
|
||||
}, OFFLINE_SHELL_DELAY_MS);
|
||||
}
|
||||
|
||||
// The copy of the UI the app starts from without its server (offlineShell.ts):
|
||||
// iOS in WebKit's cache, Android in the app's own store.
|
||||
window.setTimeout(() => {
|
||||
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(fetch, useSettingsStore.getState().settings.language, isNativeAndroid()).catch(
|
||||
(err: unknown) => {
|
||||
if (!isUnimplemented(err)) reportNativeFailure(err);
|
||||
}
|
||||
);
|
||||
}, OFFLINE_SHELL_DELAY_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -99,4 +99,30 @@ describe('keepOfflineShellFresh', () => {
|
||||
await keepOfflineShellFresh(fetchImpl, 'fr');
|
||||
expect(fetched).toContain('/assets/fr-bbbb2222.js');
|
||||
});
|
||||
|
||||
it('on Android hands the list to the native store instead of fetching it here', async () => {
|
||||
vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: true });
|
||||
const fetchImpl = vi.fn(async (input: RequestInfo | URL) => {
|
||||
if (String(input) === '/asset-manifest.json') return new Response(JSON.stringify(manifest));
|
||||
throw new Error('the native side fetches the files');
|
||||
}) as unknown as typeof fetch;
|
||||
|
||||
await keepOfflineShellFresh(fetchImpl, 'en', true);
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
||||
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(1);
|
||||
const { files } = vi.mocked(TrekShell.refreshOfflineCopy).mock.calls[0][0] as { files: string[] };
|
||||
expect(files).toContain('assets/index-a1b2c3d4.js');
|
||||
expect(files).toContain('assets/AtlasPage-99887766.js');
|
||||
});
|
||||
|
||||
it('on Android asks again on the next launch while the store is incomplete', async () => {
|
||||
vi.mocked(TrekShell.refreshOfflineCopy).mockResolvedValue({ saved: true, complete: false });
|
||||
const fetchImpl = vi.fn(async () => new Response(JSON.stringify(manifest))) as unknown as typeof fetch;
|
||||
|
||||
await keepOfflineShellFresh(fetchImpl, 'en', true);
|
||||
await keepOfflineShellFresh(fetchImpl, 'en', true);
|
||||
|
||||
expect(TrekShell.refreshOfflineCopy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
/**
|
||||
* iOS only. WKWebView runs no service worker for a domain the app does not
|
||||
* list at build time, so the app stands in for it: the native side keeps a
|
||||
* copy of the start page (TrekShellPlugin.refreshOfflineCopy), and this pulls
|
||||
* every chunk of the current build into WebKit's HTTP cache. The server marks
|
||||
* them immutable, so a cold start without network can load the stored start
|
||||
* page under the server's origin and find all its scripts, including the lazy
|
||||
* routes nobody has opened yet.
|
||||
* The app's stand-in for a service worker, so it starts without its server (a
|
||||
* trip without reception, a server at home out of reach). WKWebView runs none
|
||||
* for a domain the app does not list at build time, and Android's web view
|
||||
* none on a plain-http server, the usual address of a server at home. So the
|
||||
* native side keeps a copy of the start page (TrekShellPlugin.refreshOfflineCopy)
|
||||
* and every chunk of the current build: iOS in WebKit's HTTP cache, which this
|
||||
* fills (the server marks the files immutable), Android in the app's own store,
|
||||
* which the native side fills from the list this hands it. A cold start without
|
||||
* the server then loads the stored start page under the server's origin and
|
||||
* finds all its scripts, including the lazy routes nobody has opened yet.
|
||||
*/
|
||||
|
||||
const MANIFEST_URL = '/asset-manifest.json';
|
||||
@@ -82,13 +85,23 @@ function rememberWarmed(build: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
export async function keepOfflineShellFresh(fetchImpl: typeof fetch = fetch, language?: string): Promise<void> {
|
||||
await TrekShell.refreshOfflineCopy();
|
||||
export async function keepOfflineShellFresh(
|
||||
fetchImpl: typeof fetch = fetch,
|
||||
language?: string,
|
||||
nativeStore = false
|
||||
): Promise<void> {
|
||||
if (!nativeStore) await TrekShell.refreshOfflineCopy();
|
||||
const response = await fetchImpl(MANIFEST_URL, { cache: 'no-store' });
|
||||
if (!response.ok) return;
|
||||
const files = manifestFiles(await response.json(), language);
|
||||
// The build and the language together: a new language needs its own chunk.
|
||||
const build = `${[...files].sort((a, b) => a.localeCompare(b)).find((f) => /index-[^/]+\.js$/.test(f)) ?? files.length}:${language ?? 'en'}`;
|
||||
if (nativeStore) {
|
||||
// The native side fetches only what its store lacks, and keeps the start page fresh each time.
|
||||
const { complete } = await TrekShell.refreshOfflineCopy({ files });
|
||||
if (complete) rememberWarmed(build);
|
||||
return;
|
||||
}
|
||||
if (warmedBuild() === build) return;
|
||||
const complete = await warmCache(files, (path) =>
|
||||
fetchImpl(path, { priority: 'low' } as RequestInit).then((r) => r.blob())
|
||||
|
||||
@@ -57,9 +57,14 @@ export interface TrekShellPlugin {
|
||||
* only for two minutes, as long as the server keeps its code. Not in iOS builds, nor in Android builds before 5.1.4.
|
||||
*/
|
||||
takeAuthCallback(): Promise<{ url: string | null }>;
|
||||
/** iOS: stores the server's start page for a cold start without network. */
|
||||
refreshOfflineCopy(): Promise<{ saved: boolean }>;
|
||||
/** iOS: loads that copy under the server's origin. False when there is none. */
|
||||
/**
|
||||
* Stores the server's start page for a start without the server. Android
|
||||
* also downloads the build's `files` the copy does not hold yet (an Android
|
||||
* build before the offline copy resolves `saved: false`); iOS keeps those in
|
||||
* WebKit's HTTP cache instead and ignores them.
|
||||
*/
|
||||
refreshOfflineCopy(options?: { files?: string[] }): Promise<{ saved: boolean; complete?: boolean }>;
|
||||
/** Starts on that copy under the server's origin. False when there is none. */
|
||||
openOfflineCopy(): Promise<{ opened: boolean }>;
|
||||
/** What this binary offers the UI (native/capabilities.ts). Missing before shell API 2. */
|
||||
getCapabilities(): Promise<NativeCapabilities>;
|
||||
|
||||
Reference in New Issue
Block a user