feat(native): the UI knows when it runs inside the app

Everything the server's UI does differently inside the iOS and Android app
lives under src/native and is inert in a browser.

Sign-in: SSO and the passkey button go through the system browser
(signInThroughBrowser), because identity providers refuse embedded
browsers and WebAuthn needs a domain association no build can have for
every server. The browser end is the new /native-handoff page: it signs
the user in if needed and hands the session over only after an explicit
tap, so a link carrying somebody else's challenge cannot pass a session
on silently. The verifier is hashed with @noble/hashes because
crypto.subtle is missing on the plain-http servers many home networks
use. An OIDC-only install no longer bounces to the IdP inside the
WebView, and passkey management is hidden in the app.

Downloads: the WebView cannot save a blob, so downloadBlob, downloadFile
and openFile write to the app cache and open the share sheet. The eight
places that built their own download anchor now use downloadBlob, which
they should have anyway.

The rest: "Change server" on the login page and in the account settings,
the splash hides after the first frame, Android's back button walks
history before it leaves the app, the status bar follows the scheme, and
on iOS the start page is refreshed and every chunk of the build (listed
in the new asset-manifest.json) is pulled into WebKit's cache so the app
can start without network.
This commit is contained in:
Maurice
2026-09-24 12:42:34 +02:00
parent c5765bbf15
commit ae0d4e4520
37 changed files with 1153 additions and 88 deletions
@@ -10,6 +10,7 @@ import { currencyDecimals } from '../../utils/formatters'
import { widgetTheme, fmtNum, calcPP, calcPD, calcPPD, hasCustomMemberSplit } from './BudgetPanel.helpers'
import { PIE_COLORS } from './BudgetPanel.constants'
import type { TripMember } from './BudgetPanelMemberChips'
import { downloadBlob } from '../../utils/fileDownload'
function useIsDark(): boolean {
const [dark, setDark] = useState<boolean>(() => typeof document !== 'undefined' && document.documentElement.classList.contains('dark'))
@@ -183,13 +184,8 @@ export function useBudgetPanel(tripId: number, tripMembers: TripMember[]) {
const bom = ''
const blob = new Blob([bom + rows.join('\r\n')], { type: 'text/csv;charset=utf-8;' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
const safeName = (trip?.title || 'trip').replace(/[^a-zA-Z0-9À-ɏ _-]/g, '').trim()
a.download = `budget-${safeName}.csv`
a.click()
URL.revokeObjectURL(url)
downloadBlob(blob, `budget-${safeName}.csv`)
}
const th: CSSProperties = { padding: '6px 8px', textAlign: 'center', fontSize: 11, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: '2px solid var(--border-primary)', whiteSpace: 'nowrap', background: 'var(--bg-secondary)' }
@@ -75,10 +75,10 @@ describe('downloads', () => {
expect(click).toHaveBeenCalledTimes(1)
expect(names).toEqual(['lisbon' + COLLECTION_FILE_EXTENSION])
expect(created[0].type).toBe('application/json')
expect(document.querySelector('a')).toBeNull()
expect(revoke).not.toHaveBeenCalled()
vi.runAllTimers()
expect(revoke).toHaveBeenCalledWith('blob:x')
expect(document.querySelector('a')).toBeNull()
})
it('FE-COLL-FILE-014: hands the browser a GPX under the list name', async () => {
@@ -6,6 +6,7 @@ import {
type CollectionGpxProblem,
type CollectionGpxReadResult,
} from '@trek/shared'
import { downloadBlob } from '../../utils/fileDownload'
/**
* The browser half of list export and import (#2198, #2301).
@@ -37,16 +38,7 @@ export function collectionFileName(name: string, extension = COLLECTION_FILE_EXT
}
function download(content: string, type: string, fileName: string): void {
const url = URL.createObjectURL(new Blob([content], { type }))
const a = document.createElement('a')
a.href = url
a.download = fileName
document.body.appendChild(a)
a.click()
a.remove()
// Revoked on the next tick: revoking synchronously can cancel the download
// in some browsers before it has started reading the blob.
setTimeout(() => URL.revokeObjectURL(url), 0)
downloadBlob(new Blob([content], { type }), fileName)
}
/** Hand the file to the browser as a download. */
@@ -7,6 +7,7 @@ import { useToast } from '../shared/Toast'
import type { Trip, Day, Place, Category, AssignmentsMap, Reservation, DayNote } from '../../types'
import { useSettingsStore } from '../../store/settingsStore'
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings'
import { downloadBlob } from '../../utils/fileDownload'
/**
* What a GPX download can carry. Worded by what someone wants on their device
@@ -67,18 +68,6 @@ export function TripExportModal({
const showServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false, tripId)
const fileBase = trip?.title || 'trip'
// Shared tail of every download: Firefox and Safari cancel the download when
// the object URL is revoked before they picked the blob up, hence the delay.
const saveBlob = (blob: Blob, filename: string) => {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
setTimeout(() => { URL.revokeObjectURL(url); a.remove() }, 100)
}
const exportPdf = async () => {
if (busy) return
setBusy('pdf')
@@ -107,7 +96,7 @@ export function TripExportModal({
try {
const res = await fetch(`/api/trips/${tripId}/export.ics`, { credentials: 'include' })
if (!res.ok) throw new Error()
saveBlob(await res.blob(), `${fileBase}.ics`)
downloadBlob(await res.blob(), `${fileBase}.ics`)
onClose()
} catch {
toast.error(t('planner.icsExportFailed'))
@@ -125,7 +114,7 @@ export function TripExportModal({
// "nothing happened" and "the download broke" look identical otherwise.
if (res.status === 404) { toast.info(t('dayplan.gpxEmpty')); return }
if (!res.ok) throw new Error()
saveBlob(await res.blob(), `${fileBase}.gpx`)
downloadBlob(await res.blob(), `${fileBase}.gpx`)
onClose()
} catch {
toast.error(t('dayplan.gpxFailed'))
@@ -598,7 +598,7 @@ describe('AccountTab – Backup codes', () => {
expect(createObjectURL).toHaveBeenCalledWith(expect.any(Blob));
expect(downloadName).toBe('trek-mfa-backup-codes.txt');
expect(revokeObjectURL).toHaveBeenCalledWith('blob:codes');
await waitFor(() => expect(revokeObjectURL).toHaveBeenCalledWith('blob:codes'));
expect(document.querySelector('a[download]')).toBeNull();
createObjectURL.mockRestore();
+9 -11
View File
@@ -10,6 +10,9 @@ import { getApiErrorMessage } from '../../types'
import type { UserWithOidc } from '../../types'
import Section from './Section'
import PasskeysSection from './PasskeysSection'
import NativeServerSection from './NativeServerSection'
import { isNativeApp } from '../../native/platform'
import { downloadBlob } from '../../utils/fileDownload'
const MFA_BACKUP_SESSION_KEY = 'trek_mfa_backup_codes_pending'
@@ -100,15 +103,7 @@ export default function AccountTab(): React.ReactElement {
const downloadBackupCodes = () => {
if (!backupCodesText) return
const blob = new Blob([backupCodesText + '\n'], { type: 'text/plain;charset=utf-8' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'trek-mfa-backup-codes.txt'
document.body.appendChild(a)
a.click()
a.remove()
URL.revokeObjectURL(url)
downloadBlob(new Blob([backupCodesText + '\n'], { type: 'text/plain;charset=utf-8' }), 'trek-mfa-backup-codes.txt')
}
const printBackupCodes = () => {
@@ -160,6 +155,7 @@ export default function AccountTab(): React.ReactElement {
return (
<>
<NativeServerSection />
<Section title={t('settings.account')} icon={User}>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('settings.username')}</label>
@@ -405,8 +401,10 @@ export default function AccountTab(): React.ReactElement {
</div>
</div>
{/* Passkeys */}
<PasskeysSection demoMode={demoMode} />
{/* Passkeys. Not in the app: WebAuthn in its WebView needs a domain
association no build can have for every server, so they are managed
in the browser (signing in with one works through it too). */}
{!isNativeApp() && <PasskeysSection demoMode={demoMode} />}
{/* Avatar */}
<div className="flex items-center gap-4">
@@ -0,0 +1,33 @@
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-004
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent } from '../../../tests/helpers/render'
import NativeServerSection from './NativeServerSection'
import MSettingsServer from '../../mobile/screens/settings/MSettingsServer'
import { nativeServerHost } from '../../native/platform'
import { TrekShell } from '../../native/trekShell'
vi.mock('../../native/platform', () => ({ nativeServerHost: vi.fn() }))
vi.mock('../../native/trekShell', () => ({ TrekShell: { resetServer: vi.fn() } }))
beforeEach(() => {
vi.mocked(TrekShell.resetServer).mockReset().mockResolvedValue()
})
describe.each([
['desktop', NativeServerSection],
['mobile', MSettingsServer],
])('the %s server section', (_shell, Section) => {
it('renders nothing in a browser', () => {
vi.mocked(nativeServerHost).mockReturnValue(null)
const { container } = render(<Section />)
expect(container).toBeEmptyDOMElement()
})
it('names the server and leads back to the address screen', () => {
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com')
render(<Section />)
expect(screen.getByText('This app is connected to trek.example.com.')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Change server' }))
expect(TrekShell.resetServer).toHaveBeenCalled()
})
})
@@ -0,0 +1,25 @@
import React from 'react'
import { Server } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { nativeServerHost } from '../../native/platform'
import { TrekShell } from '../../native/trekShell'
import Section from './Section'
/** Only inside the iOS/Android app: which server it talks to, and the way to another one. */
export default function NativeServerSection(): React.ReactElement | null {
const { t } = useTranslation()
const host = nativeServerHost()
if (!host) return null
return (
<Section title={t('native.settings.server')} icon={Server}>
<p className="text-body text-content-secondary">{t('native.settings.serverHint', { server: host })}</p>
<button
type="button"
onClick={() => { void TrekShell.resetServer() }}
className="rounded-lg border border-edge bg-surface-card px-4 py-2 text-body font-medium text-content hover:bg-surface-hover"
>
{t('native.changeServer')}
</button>
</Section>
)
}
+2 -10
View File
@@ -1,5 +1,6 @@
import type { BookPageSetup, BookSpread } from '@trek/shared'
import { bookElementSchema } from '@trek/shared'
import { downloadBlob } from '../../utils/fileDownload'
/**
* A spread as a file, so a design can leave the book it was made in.
@@ -202,16 +203,7 @@ export function importSpread(raw: unknown, page: BookPageSetup): BookSpread | nu
/** Hand the file to the browser as a download. */
export function downloadSpread(spread: BookSpread, page: BookPageSetup, name: string) {
const json = JSON.stringify(exportSpread(spread, page, name), null, 2)
const url = URL.createObjectURL(new Blob([json], { type: 'application/json' }))
const a = document.createElement('a')
a.href = url
a.download = `${slug(name) || 'spread'}.trekspread.json`
document.body.appendChild(a)
a.click()
a.remove()
// Revoked on the next tick: revoking synchronously can cancel the download
// in some browsers before it has started reading the blob.
setTimeout(() => URL.revokeObjectURL(url), 0)
downloadBlob(new Blob([json], { type: 'application/json' }), `${slug(name) || 'spread'}.trekspread.json`)
}
function slug(name: string): string {