feat(native): swipe rows, long-press menus, placeholders while loading, fading pictures, iOS bounce and app icon quick actions

Packing items, tasks and expenses swipe sideways to their actions, as in
Mail or Reminders: done or open one way, delete and edit the other, the
first one run by a full swipe. They are second ways to what each row
already offers; an expense still asks before it goes.

A long press on a trip card lifts it and opens its menu with the card's own
actions. Plain confirmations in MConfirmSheet now also ask through the
system where the app can.

Lists, the atlas and a journey show grey placeholders in their shape while
loading instead of a spinner in an empty screen (MSkeleton); buttons keep
theirs. A picture still loading fades in once it is there; one from the
cache shows at once. In the iOS app the page bounces at its ends again,
except on screens with pull-to-refresh, whose pull it would race; Android
keeps its stretch off.

On iOS a long press on the app icon offers "New trip" and the trip coming
up by its name, set by the UI in its language (TrekShell.setQuickActions,
feature quickActions), and a tap opens it, also from a cold start.

The app's own CSS moves out of index.css into native/nativeApp.css, which
had outgrown its size budget.
This commit is contained in:
Maurice
2026-11-09 09:37:36 +01:00
parent c9a91bbdad
commit 80c04df4fc
44 changed files with 1315 additions and 120 deletions
+66
View File
@@ -0,0 +1,66 @@
import { afterEach, describe, expect, it } from 'vitest';
import { fadeInImages } from './imageFade';
let stop: (() => void) | null = null;
afterEach(() => {
stop?.();
stop = null;
document.body.innerHTML = '';
});
/** Lets the MutationObserver deliver what was just added. */
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
function loadingImage(): HTMLImageElement {
const img = document.createElement('img');
Object.defineProperty(img, 'complete', { value: false, configurable: true });
return img;
}
describe('fadeInImages', () => {
it('holds a loading picture back and fades it in once it has loaded', async () => {
stop = fadeInImages();
const img = loadingImage();
document.body.appendChild(img);
await settle();
expect(img.hasAttribute('data-fading')).toBe(true);
img.dispatchEvent(new Event('load'));
expect(img.hasAttribute('data-fading')).toBe(false);
expect(img.hasAttribute('data-faded')).toBe(true);
});
it('shows a picture that failed, so it never stays invisible', async () => {
stop = fadeInImages();
const img = loadingImage();
document.body.appendChild(img);
await settle();
img.dispatchEvent(new Event('error'));
expect(img.hasAttribute('data-fading')).toBe(false);
});
it('shows a picture from the cache at once, and finds pictures inside what was added', async () => {
stop = fadeInImages();
const wrap = document.createElement('div');
const cached = document.createElement('img');
Object.defineProperty(cached, 'complete', { value: true });
const fresh = loadingImage();
wrap.append(cached, fresh);
document.body.appendChild(wrap);
await settle();
expect(cached.hasAttribute('data-fading')).toBe(false);
expect(fresh.hasAttribute('data-fading')).toBe(true);
});
it('leaves map tiles and opted-out pictures alone', async () => {
stop = fadeInImages();
document.body.innerHTML = '<div class="leaflet-container"></div><div data-no-fade></div>';
const tile = loadingImage();
const own = loadingImage();
document.body.children[0]?.appendChild(tile);
document.body.children[1]?.appendChild(own);
await settle();
expect(tile.hasAttribute('data-fading')).toBe(false);
expect(own.hasAttribute('data-fading')).toBe(false);
});
});
+39
View File
@@ -0,0 +1,39 @@
/**
* Pictures that fade in once they are there, instead of building up line by
* line or popping in late, the way a native app shows a cover or a photo.
*
* Only an image that is still loading when it reaches the page fades: it waits
* at opacity 0 (data-fading), and as it loads or fails it is shown with a short
* fade (data-faded, index.css). One that is already in the cache shows at once,
* so nothing on a screen opened a second time flickers. A failed image is shown
* too, so a picture never stays invisible. Map tiles fade by themselves and are
* left alone, as is anything inside [data-no-fade]. Only the app calls this.
*/
const SKIP = '.leaflet-container, .maplibregl-map, [data-no-fade]';
function watch(img: HTMLImageElement): void {
if (img.complete || img.hasAttribute('data-fading') || img.closest(SKIP)) return;
img.setAttribute('data-fading', '');
const show = () => {
img.removeEventListener('load', show);
img.removeEventListener('error', show);
img.removeAttribute('data-fading');
img.setAttribute('data-faded', '');
};
img.addEventListener('load', show);
img.addEventListener('error', show);
}
function scan(node: Node): void {
if (node instanceof HTMLImageElement) watch(node);
else if (node instanceof Element) node.querySelectorAll('img').forEach(watch);
}
export function fadeInImages(root: Element = document.body): () => void {
const observer = new MutationObserver((records) => {
for (const record of records) record.addedNodes.forEach(scan);
});
observer.observe(root, { childList: true, subtree: true });
return () => observer.disconnect();
}
+83
View File
@@ -0,0 +1,83 @@
/*
* What the UI does differently inside the iOS and Android app, keyed on the
* attributes native/nativeApp.ts puts on <html> there (data-native-app, and
* data-touch-input while a finger drives it). A browser never has them, so
* none of this reaches it. Loaded after index.css (main.tsx).
*/
/* Inside the iOS and Android app (native/nativeApp.ts sets the attribute): a long
press on a label, card or image does nothing, as in a native app, instead of
starting a text selection, a magnifier or a "save image" callout. What the user
types into stays selectable, or editing, pasting and moving the caret would break;
text worth copying opts in with .trek-selectable. A browser keeps its default. */
html[data-native-app] body {
-webkit-user-select: none;
user-select: none;
-webkit-touch-callout: none;
}
html[data-native-app] :is(input, textarea, select, [contenteditable]:not([contenteditable='false']), .trek-selectable),
html[data-native-app] :is([contenteditable]:not([contenteditable='false']), .trek-selectable) * {
-webkit-user-select: text;
user-select: text;
-webkit-touch-callout: default;
}
html[data-native-app] img {
-webkit-user-drag: none;
}
/* A picture still loading waits unseen and fades in once it is there
(native/imageFade.ts). An animation rather than a transition, so an image's
own transitions (a hover zoom, a crossfade) stay as they are. */
html[data-native-app] img[data-fading] {
opacity: 0;
}
@keyframes trek-image-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@media (prefers-reduced-motion: no-preference) {
html[data-native-app]:not([data-reduce-motion]) img[data-faded] {
animation: trek-image-in 0.24s ease-out;
}
}
/* The press a native button shows the moment a finger lands on it. Most of the
UI says nothing until the finger lifts, which reads as lag. Only what has no
press of its own (no active: class), only the innermost pressed control, not
the card around a pressed button, and after a 60 ms wait, so a finger that
lands on a row to scroll the list does not flash it. Draggable rows show
their own pick-up; data-no-press opts a control out. */
html[data-native-app]
:is(button, a[href], [role='button'], [role='tab'], [role='menuitem'], [role='option'], summary):not(:disabled):not(
[aria-disabled='true']
):not([class*='active:']):not([draggable='true']):not([data-no-press]):not([data-pressing]):not(
:has(:is(button, a[href], [role='button']):active)
):active {
opacity: 0.55;
transition: opacity 0s linear 60ms;
}
/* A card held for its menu lifts a little under the finger
(mobile/components/useLongPress.ts), as a native context menu does. */
html[data-native-app] [data-long-press] {
transition: transform 0.3s cubic-bezier(0.32, 0.72, 0, 1);
}
html[data-native-app] [data-long-press][data-pressing] {
transform: scale(0.97);
}
/* A tap focuses a button on Android, and a focus: ring (rather than
focus-visible:) then stays round it, which no native control shows. Focus
from a hardware keyboard is focus-visible and keeps its ring. */
html[data-touch-input]
:is(button, a, [role='button'], [role='tab'], [role='menuitem'], [role='option'], [tabindex]):focus:not(
:focus-visible
) {
outline: none;
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
}
+3
View File
@@ -31,6 +31,8 @@ vi.mock('./sharedFiles', () => ({ startSharedFiles: vi.fn(async () => {}) }));
vi.mock('./push', () => ({ startNativePush: vi.fn(async () => {}), openPushTarget: vi.fn() }));
vi.mock('../mobile/overlayStack', () => ({ closeTopOverlay: vi.fn(() => false) }));
vi.mock('./touchInput', () => ({ trackTouchInput: vi.fn() }));
vi.mock('./quickActions', () => ({ startQuickActions: vi.fn() }));
vi.mock('./imageFade', () => ({ fadeInImages: vi.fn() }));
vi.mock('./keyboardFields', () => ({ prepareKeyboardFields: vi.fn() }));
function backButtonHandler(): (event: { canGoBack: boolean }) => void {
@@ -48,6 +50,7 @@ beforeEach(() => {
vi.mocked(keepOfflineShellFresh).mockResolvedValue();
document.documentElement.classList.remove('dark');
document.documentElement.removeAttribute('data-native-app');
document.documentElement.removeAttribute('data-native-ios');
});
afterEach(() => {
+8
View File
@@ -7,11 +7,13 @@ import { useSettingsStore } from '../store/settingsStore';
import { isEffectivelyOffline } from '../sync/networkMode';
import { checkAppUpdate, loadNativeCapabilities } from './capabilities';
import { installNativeGeolocation } from './geolocation';
import { fadeInImages } from './imageFade';
import { keepFieldInView } from './keepFieldInView';
import { prepareKeyboardFields } from './keyboardFields';
import { keepOfflineShellFresh } from './offlineShell';
import { isNativeApp, isNativeIos } from './platform';
import { openPushTarget, startNativePush } from './push';
import { startQuickActions } from './quickActions';
import { reportNativeFailure } from './reportFailure';
import { startSharedFiles } from './sharedFiles';
import { trackTouchInput } from './touchInput';
@@ -30,10 +32,14 @@ export function startNativeApp(): void {
// Marks the app for index.css: no text selection or long-press callout on the
// UI itself, as in any native app. Fields stay selectable there.
document.documentElement.setAttribute('data-native-app', '');
// iOS only: the page may bounce at its ends there (mobile.css).
if (isNativeIos()) document.documentElement.setAttribute('data-native-ios', '');
// No hover left behind by a tap, a press that shows, no focus ring after a tap.
trackTouchInput();
// The keyboard's return key, capitalisation and autocorrect fit the field.
prepareKeyboardFields();
// Pictures fade in once loaded instead of building up.
fadeInImages();
followThemeInStatusBar();
@@ -45,6 +51,8 @@ export function startNativeApp(): void {
void startSharedFiles();
// Taps on TREK notifications open the place they point at.
void loadNativeCapabilities().then(() => startNativePush());
// A quick action on the app icon opens its page, also the one the app was launched with.
void loadNativeCapabilities().then(() => startQuickActions());
// A widget or Live Activity tap opens com.liketrek.trek://navigate/<path>.
void App.addListener('appUrlOpen', ({ url }) => {
+66
View File
@@ -0,0 +1,66 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Trip } from '../types';
import { hasNativeFeature } from './capabilities';
import { isNativeApp } from './platform';
import { openPushTarget } from './push';
import { publishQuickActions, quickActionsFor, startQuickActions } from './quickActions';
import { TrekShell } from './trekShell';
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() }));
vi.mock('./platform', () => ({ isNativeApp: vi.fn() }));
vi.mock('./push', () => ({ openPushTarget: vi.fn() }));
vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() }));
vi.mock('./trekShell', () => ({
TrekShell: { setQuickActions: vi.fn(async () => {}), takeQuickAction: vi.fn(), addListener: vi.fn() },
}));
const t = ((key: string) =>
({ 'dashboard.newTrip': 'New Trip', 'dashboard.nextTrip': 'Next trip', 'native.widget.today': 'Today' })[key] ??
key) as never;
const trip = (start: string, end: string) =>
({ id: 7, title: 'Lisbon', start_date: start, end_date: end }) as unknown as Trip;
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(isNativeApp).mockReturnValue(true);
vi.mocked(hasNativeFeature).mockReturnValue(true);
});
describe('quickActionsFor', () => {
it('offers "New trip" alone without a trip', () => {
expect(quickActionsFor(null, '2026-11-09', t)).toEqual([
{ type: 'newTrip', title: 'New Trip', icon: 'add', path: '/dashboard?create=1' },
]);
});
it('adds the trip coming up by its name', () => {
expect(quickActionsFor(trip('2026-12-01', '2026-12-05'), '2026-11-09', t)[1]).toEqual({
type: 'trip',
title: 'Lisbon',
subtitle: 'Next trip',
icon: 'trip',
path: '/trips/7',
});
});
it('calls a trip that runs today "Today"', () => {
expect(quickActionsFor(trip('2026-11-08', '2026-11-10'), '2026-11-09', t)[1]?.subtitle).toBe('Today');
});
});
describe('the binary', () => {
it('gets the actions only where it has the feature', async () => {
await publishQuickActions([]);
expect(TrekShell.setQuickActions).toHaveBeenCalledWith({ items: [] });
vi.mocked(hasNativeFeature).mockReturnValue(false);
await publishQuickActions([]);
expect(TrekShell.setQuickActions).toHaveBeenCalledTimes(1);
});
it('opens the action the app was launched with, and listens for the next ones', async () => {
vi.mocked(TrekShell.takeQuickAction).mockResolvedValue({ path: '/trips/7' });
await startQuickActions();
expect(openPushTarget).toHaveBeenCalledWith('/trips/7');
expect(TrekShell.addListener).toHaveBeenCalledWith('quickAction', expect.any(Function));
});
});
+53
View File
@@ -0,0 +1,53 @@
import type { TranslationFn, Trip } from '../types';
import { hasNativeFeature } from './capabilities';
import { isNativeApp } from './platform';
import { openPushTarget } from './push';
import { reportNativeFailure } from './reportFailure';
import { type NativeQuickAction, TrekShell } from './trekShell';
/**
* The quick actions a long press on the app icon shows, as in every iOS app:
* "New trip", and the trip coming up (or running today) by its name. Set by
* the UI, so they speak the app's language and follow the trips, and a tap
* opens the path each carries, the way a tap on a notification does. Only
* where the binary reports the feature `quickActions`.
*/
export function quickActionsActive(): boolean {
return isNativeApp() && hasNativeFeature('quickActions');
}
/** The actions for the trip the dashboard leads with (`hero`), or "New trip" alone without one. */
export function quickActionsFor(hero: Trip | null, today: string, t: TranslationFn): NativeQuickAction[] {
const items: NativeQuickAction[] = [
{ type: 'newTrip', title: t('dashboard.newTrip'), icon: 'add', path: '/dashboard?create=1' },
];
if (hero) {
const running = !!hero.start_date && hero.start_date <= today && (hero.end_date ?? hero.start_date) >= today;
items.push({
type: 'trip',
title: hero.title,
subtitle: running ? t('native.widget.today') : t('dashboard.nextTrip'),
icon: 'trip',
path: `/trips/${hero.id}`,
});
}
return items;
}
export async function publishQuickActions(items: NativeQuickAction[]): Promise<void> {
if (!quickActionsActive()) return;
await TrekShell.setQuickActions({ items }).catch(reportNativeFailure);
}
/** Opens the action the app was launched with, and every one chosen while it runs. */
export async function startQuickActions(): Promise<void> {
if (!quickActionsActive()) return;
void TrekShell.addListener('quickAction', ({ path }) => openPushTarget(path));
try {
const { path } = await TrekShell.takeQuickAction();
if (path) openPushTarget(path);
} catch (err) {
reportNativeFailure(err);
}
}
+21
View File
@@ -142,6 +142,27 @@ export interface TrekShellPlugin {
event: 'keyCommand',
listener: (payload: { id: string }) => void
): Promise<{ remove: () => Promise<void> }>;
/** Feature quickActions (iOS): the actions a long press on the app icon shows, in the UI's language. */
setQuickActions(options: { items: NativeQuickAction[] }): Promise<void>;
/** Feature quickActions: the action the app was launched with, before the UI ran. */
takeQuickAction(): Promise<{ path: string | null }>;
/** Feature quickActions: an action chosen while the app was running. */
addListener(
event: 'quickAction',
listener: (payload: { path: string }) => void
): Promise<{ remove: () => Promise<void> }>;
}
/** One quick action on the app icon: what it says, and the path in the UI it opens. */
export interface NativeQuickAction {
/** Stable name, e.g. "newTrip". */
type: string;
title: string;
subtitle?: string;
/** 'add' or 'trip'. */
icon: 'add' | 'trip';
/** A path of this server's UI, starting with "/". */
path: string;
}
/** What Google Play Billing answers a restore with (Android, feature playBilling), beside iOS's `jws`. */