feat(native): the app answers a finger like a native app, not like a web page

After a tap, WebKit and Chrome keep :hover on what was tapped and send a
made-up mouseover, so buttons and rows stayed tinted until the next tap.
While a finger drives the app <html> carries data-touch-input: a PostCSS
step guards every :hover rule with it (no specificity change), and the
made-up mouseover and mouseout stop before any handler. A trackpad or mouse
clears the mark and gets hover back; a browser never sets it.

A control without a press of its own dims the moment a finger lands on it,
after a 60 ms wait so a scroll does not flash rows, and only the innermost
pressed control. A focus: ring no longer stays round a tapped button.

Fields get a fitting return key ("done", "go" in a form, "search" on the
search fields), and addresses, codes and numbers are no longer capitalised
or corrected. Ticking off packing items and tasks, a picker chip, a select
option, a picked date and dragging a plan row now give the haptics a native
list gives.

Confirmations ask through the system where the binary has the new
@capacitor/action-sheet and @capacitor/dialog plugins: a sheet with the
action in red when it destroys something, an alert otherwise, also for
"discard changes" in a sheet. An older app, a browser and a question with a
list under it keep the HTML dialog, as does a system that could not ask.

iOS no longer lifts a page preview on a long press on a link.
This commit is contained in:
Maurice
2026-11-09 08:54:51 +01:00
parent d9baaa8957
commit d06168d94a
43 changed files with 818 additions and 26 deletions
+91
View File
@@ -0,0 +1,91 @@
import { afterEach, describe, expect, it } from 'vitest';
import { prepareField, prepareKeyboardFields } from './keyboardFields';
function field(html: string): HTMLInputElement {
document.body.innerHTML = html;
return document.body.querySelector('input')!;
}
afterEach(() => {
document.body.innerHTML = '';
});
describe('prepareField', () => {
it('gives a field outside a form a "done" key and leaves its text alone', () => {
const el = field('<input name="title">');
prepareField(el);
expect(el.getAttribute('enterkeyhint')).toBe('done');
expect(el.hasAttribute('autocapitalize')).toBe(false);
expect(el.hasAttribute('autocorrect')).toBe(false);
});
it('says "go" in a form, which Enter submits', () => {
const el = field('<form><input name="title"><button>Save</button></form>');
prepareField(el);
expect(el.getAttribute('enterkeyhint')).toBe('go');
});
it('turns capitals and corrections off for what a machine reads', () => {
for (const html of [
'<input type="email">',
'<input type="url">',
'<input inputmode="numeric">',
'<input autocomplete="one-time-code">',
'<input name="bookingCode">',
'<input id="api_token">',
'<input name="server-host">',
]) {
const el = field(html);
prepareField(el);
expect([
html,
el.getAttribute('autocapitalize'),
el.getAttribute('autocorrect'),
el.getAttribute('spellcheck'),
]).toEqual([html, 'none', 'off', 'false']);
}
});
it('does not take a word that only contains a machine word for one', () => {
for (const html of ['<input name="keyword">', '<input name="preferredName">', '<input id="pinnedNote">']) {
const el = field(html);
prepareField(el);
expect([html, el.hasAttribute('autocapitalize')]).toEqual([html, false]);
}
});
it('treats a search field as one, in its key and its text', () => {
const el = field('<input type="search">');
prepareField(el);
expect(el.getAttribute('enterkeyhint')).toBe('search');
expect(el.getAttribute('autocorrect')).toBe('off');
});
it('never overrides what a field says itself', () => {
const el = field('<input type="email" enterkeyhint="send" autocapitalize="words">');
prepareField(el);
expect(el.getAttribute('enterkeyhint')).toBe('send');
expect(el.getAttribute('autocapitalize')).toBe('words');
});
it('leaves textareas, checkboxes and read-only fields alone', () => {
document.body.innerHTML = '<textarea></textarea><input type="checkbox"><input readonly>';
for (const el of Array.from(document.body.children)) {
prepareField(el);
expect(el.hasAttribute('enterkeyhint')).toBe(false);
}
});
});
describe('prepareKeyboardFields', () => {
it('prepares a field as it is focused, and stops when told to', () => {
const stop = prepareKeyboardFields();
const a = field('<input name="title">');
a.focus();
expect(a.getAttribute('enterkeyhint')).toBe('done');
stop();
const b = field('<input name="other">');
b.focus();
expect(b.hasAttribute('enterkeyhint')).toBe(false);
});
});
+117
View File
@@ -0,0 +1,117 @@
/**
* The keyboard a field gets in the app: what its return key says, and whether
* it capitalises and corrects what is typed.
*
* Left alone, every field in a web view gets the return key of a text editor
* and the autocorrect of a letter, so an email address starts with a capital,
* a booking code is "corrected" into a word, and Enter on a search field reads
* "return". Before a field is focused (on the touch that focuses it, or on the
* focus itself when code moves it there) this fills in what the field does not
* say for itself:
*
* - enterkeyhint: "go" in a form, which Enter submits, "done" anywhere else.
* Search fields say "search" in their own markup.
* - autocapitalize, autocorrect and spellcheck off for addresses, codes,
* numbers and names a machine reads (email, URL, password, tel, number;
* autocomplete such as username or one-time-code; a name or id such as
* "code", "token" or "host").
*
* An attribute the field sets itself always wins, and textareas, which take
* Enter as a new line, keep the return key. Only the app calls this.
*/
const SKIP_TYPES = new Set([
'button',
'checkbox',
'color',
'date',
'datetime-local',
'file',
'hidden',
'image',
'month',
'radio',
'range',
'reset',
'submit',
'time',
'week',
]);
const MACHINE_TYPES = new Set(['email', 'url', 'password', 'tel', 'number']);
const MACHINE_MODES = new Set(['email', 'url', 'numeric', 'decimal', 'tel']);
const MACHINE_AUTOCOMPLETE =
/\b(username|email|url|one-time-code|current-password|new-password|tel|postal-code|cc-[a-z-]+)\b/;
const MACHINE_WORDS = new Set([
'code',
'token',
'key',
'apikey',
'secret',
'host',
'hostname',
'url',
'uri',
'domain',
'slug',
'username',
'email',
'mail',
'iban',
'bic',
'pin',
'otp',
'totp',
'ref',
'reference',
'server',
'port',
'ip',
]);
/** The words of an id or name: "bookingCode", "booking_code" and "booking-code" all give booking, code. */
function words(...values: (string | null)[]): string[] {
return values
.filter((v): v is string => !!v)
.flatMap((v) =>
v
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.toLowerCase()
.split(/[^a-z0-9]+/)
)
.filter(Boolean);
}
function readByMachine(el: HTMLInputElement): boolean {
if (MACHINE_TYPES.has(el.type)) return true;
if (MACHINE_MODES.has((el.getAttribute('inputmode') ?? '').toLowerCase())) return true;
if (MACHINE_AUTOCOMPLETE.test((el.getAttribute('autocomplete') ?? '').toLowerCase())) return true;
return words(el.name, el.id).some((w) => MACHINE_WORDS.has(w));
}
function setIfAbsent(el: Element, name: string, value: string) {
if (!el.hasAttribute(name)) el.setAttribute(name, value);
}
export function prepareField(target: EventTarget | null): void {
if (!(target instanceof HTMLInputElement) || SKIP_TYPES.has(target.type) || target.readOnly) return;
const el = target;
const search = el.type === 'search' || el.getAttribute('role') === 'searchbox';
setIfAbsent(el, 'enterkeyhint', search ? 'search' : el.form ? 'go' : 'done');
if (search || readByMachine(el)) {
setIfAbsent(el, 'autocapitalize', 'none');
setIfAbsent(el, 'autocorrect', 'off');
setIfAbsent(el, 'spellcheck', 'false');
}
}
export function prepareKeyboardFields(doc: Document = document): () => void {
// On the touch, before the focus: the keyboard is set up as the field takes it.
const onTouch = (e: Event) => prepareField(e.target instanceof Element ? e.target.closest('input') : null);
const onFocus = (e: FocusEvent) => prepareField(e.target);
doc.addEventListener('touchstart', onTouch, { capture: true, passive: true });
doc.addEventListener('focusin', onFocus, true);
return () => {
doc.removeEventListener('touchstart', onTouch, { capture: true });
doc.removeEventListener('focusin', onFocus, true);
};
}
+12
View File
@@ -7,9 +7,11 @@ import { closeTopOverlay } from '../mobile/overlayStack';
import { isEffectivelyOffline } from '../sync/networkMode';
import { checkAppUpdate } from './capabilities';
import { installNativeGeolocation } from './geolocation';
import { prepareKeyboardFields } from './keyboardFields';
import { scrollToTop, startNativeApp } from './nativeApp';
import { keepOfflineShellFresh } from './offlineShell';
import { isNativeApp, isNativeIos } from './platform';
import { trackTouchInput } from './touchInput';
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(), minimizeApp: vi.fn() } }));
vi.mock('@capacitor/keyboard', () => ({
@@ -28,6 +30,8 @@ vi.mock('./geolocation', () => ({ installNativeGeolocation: vi.fn() }));
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('./keyboardFields', () => ({ prepareKeyboardFields: vi.fn() }));
function backButtonHandler(): (event: { canGoBack: boolean }) => void {
const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'backButton');
@@ -57,6 +61,8 @@ describe('startNativeApp', () => {
expect(App.addListener).not.toHaveBeenCalled();
expect(StatusBar.setStyle).not.toHaveBeenCalled();
expect(document.documentElement.hasAttribute('data-native-app')).toBe(false);
expect(trackTouchInput).not.toHaveBeenCalled();
expect(prepareKeyboardFields).not.toHaveBeenCalled();
});
it('marks <html> so a long press selects no text in the app', () => {
@@ -64,6 +70,12 @@ describe('startNativeApp', () => {
expect(document.documentElement.hasAttribute('data-native-app')).toBe(true);
});
it('follows finger or pointer for hover, press and focus, and fits the keyboard to each field', () => {
startNativeApp();
expect(trackTouchInput).toHaveBeenCalledTimes(1);
expect(prepareKeyboardFields).toHaveBeenCalledTimes(1);
});
it("Android's back gesture closes an open sheet before it leaves the page", () => {
const back = vi.spyOn(window.history, 'back').mockImplementation(() => {});
vi.mocked(closeTopOverlay).mockReturnValueOnce(true);
+6
View File
@@ -8,11 +8,13 @@ import { isEffectivelyOffline } from '../sync/networkMode';
import { checkAppUpdate, loadNativeCapabilities } from './capabilities';
import { installNativeGeolocation } from './geolocation';
import { keepFieldInView } from './keepFieldInView';
import { prepareKeyboardFields } from './keyboardFields';
import { keepOfflineShellFresh } from './offlineShell';
import { isNativeApp, isNativeIos } from './platform';
import { openPushTarget, startNativePush } from './push';
import { reportNativeFailure } from './reportFailure';
import { startSharedFiles } from './sharedFiles';
import { trackTouchInput } from './touchInput';
import { APP_URL_SCHEME, isUnimplemented } from './trekShell';
/** Long enough that the warm-up never competes with the first screen's requests. */
@@ -28,6 +30,10 @@ 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', '');
// 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();
followThemeInStatusBar();
+68
View File
@@ -0,0 +1,68 @@
import { ActionSheet } from '@capacitor/action-sheet';
import { Capacitor } from '@capacitor/core';
import { Dialog } from '@capacitor/dialog';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { askNatively, canAskNatively } from './nativeDialogs';
import { isNativeApp } from './platform';
vi.mock('@capacitor/action-sheet', () => ({
ActionSheet: { showActions: vi.fn() },
ActionSheetButtonStyle: { Default: 'DEFAULT', Destructive: 'DESTRUCTIVE', Cancel: 'CANCEL' },
}));
vi.mock('@capacitor/dialog', () => ({ Dialog: { confirm: vi.fn() } }));
vi.mock('@capacitor/core', () => ({ Capacitor: { isPluginAvailable: vi.fn() } }));
vi.mock('./platform', () => ({ isNativeApp: vi.fn() }));
vi.mock('./reportFailure', () => ({ reportNativeFailure: vi.fn() }));
const question = { title: 'Delete place?', message: 'Gone for good.', confirmLabel: 'Delete', cancelLabel: 'Cancel' };
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(isNativeApp).mockReturnValue(true);
vi.mocked(Capacitor.isPluginAvailable).mockReturnValue(true);
});
describe('canAskNatively', () => {
it('needs the app and both plugins in its binary', () => {
expect(canAskNatively()).toBe(true);
vi.mocked(Capacitor.isPluginAvailable).mockImplementation((name) => name !== 'Dialog');
expect(canAskNatively()).toBe(false);
vi.mocked(isNativeApp).mockReturnValue(false);
expect(canAskNatively()).toBe(false);
});
});
describe('askNatively', () => {
it('asks a destroying question on a sheet with the action in red, yes only for that action', async () => {
vi.mocked(ActionSheet.showActions).mockResolvedValue({ index: 0 });
expect(await askNatively({ ...question, danger: true })).toBe(true);
expect(ActionSheet.showActions).toHaveBeenCalledWith({
title: 'Delete place?',
message: 'Gone for good.',
options: [
{ title: 'Delete', style: 'DESTRUCTIVE' },
{ title: 'Cancel', style: 'CANCEL' },
],
});
vi.mocked(ActionSheet.showActions).mockResolvedValue({ index: 1 });
expect(await askNatively({ ...question, danger: true })).toBe(false);
vi.mocked(ActionSheet.showActions).mockResolvedValue({ index: -1 });
expect(await askNatively({ ...question, danger: true })).toBe(false);
});
it('asks any other question in an alert', async () => {
vi.mocked(Dialog.confirm).mockResolvedValue({ value: true });
expect(await askNatively({ ...question, danger: false })).toBe(true);
expect(Dialog.confirm).toHaveBeenCalledWith({
title: 'Delete place?',
message: 'Gone for good.',
okButtonTitle: 'Delete',
cancelButtonTitle: 'Cancel',
});
});
it('answers null when the system cannot ask, so the HTML dialog takes over', async () => {
vi.mocked(ActionSheet.showActions).mockRejectedValue(new Error('not implemented'));
expect(await askNatively({ ...question, danger: true })).toBeNull();
});
});
+62
View File
@@ -0,0 +1,62 @@
import { ActionSheet, ActionSheetButtonStyle } from '@capacitor/action-sheet';
import { Capacitor } from '@capacitor/core';
import { Dialog } from '@capacitor/dialog';
import { isNativeApp } from './platform';
import { reportNativeFailure } from './reportFailure';
/**
* A yes-or-no question asked the way the phone asks it.
*
* Asked in HTML, "Delete this place?" is a card drawn by the page, and it
* looks like one. In the app it goes to the system instead: an action sheet
* with the action in red when it destroys something, an alert when it does
* not. That is what iOS and Android show in their own apps for the same
* question, with the system's own animation, sound and accessibility.
*
* Only where the binary carries both plugins: an app from before them keeps
* the HTML dialog, as does a browser.
*/
export interface NativeQuestion {
title: string;
message?: string;
confirmLabel: string;
cancelLabel: string;
/** Destroys or throws something away: the action shows in red, on a sheet. */
danger: boolean;
}
export function canAskNatively(): boolean {
return isNativeApp() && Capacitor.isPluginAvailable('ActionSheet') && Capacitor.isPluginAvailable('Dialog');
}
/**
* True when the user chose the action, false when they did not. Null when the
* system could not ask: the caller then shows its HTML dialog, so a question
* is never lost and nothing is done that was not confirmed.
*/
export async function askNatively(q: NativeQuestion): Promise<boolean | null> {
try {
if (q.danger) {
const { index } = await ActionSheet.showActions({
title: q.title,
message: q.message,
options: [
{ title: q.confirmLabel, style: ActionSheetButtonStyle.Destructive },
{ title: q.cancelLabel, style: ActionSheetButtonStyle.Cancel },
],
});
return index === 0;
}
const { value } = await Dialog.confirm({
title: q.title,
message: q.message ?? '',
okButtonTitle: q.confirmLabel,
cancelButtonTitle: q.cancelLabel,
});
return value;
} catch (err) {
reportNativeFailure(err);
return null;
}
}
+56
View File
@@ -0,0 +1,56 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { TOUCH_INPUT_ATTR, trackTouchInput } from './touchInput';
const root = document.documentElement;
let stop: (() => void) | null = null;
afterEach(() => {
stop?.();
stop = null;
});
function pointer(type: string, pointerType: string) {
const e = new Event(type, { bubbles: true }) as PointerEvent;
Object.defineProperty(e, 'pointerType', { value: pointerType });
window.dispatchEvent(e);
}
describe('trackTouchInput', () => {
it('starts as touch and follows the pointer that was used last', () => {
stop = trackTouchInput();
expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(true);
pointer('pointermove', 'mouse');
expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(false);
pointer('pointerdown', 'touch');
expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(true);
pointer('pointerdown', 'pen');
expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(true);
});
it('keeps the mouseover a tap makes up from reaching any handler', () => {
stop = trackTouchInput();
const el = document.createElement('button');
document.body.appendChild(el);
const seen = vi.fn();
el.addEventListener('mouseover', seen);
el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
expect(seen).not.toHaveBeenCalled();
pointer('pointermove', 'mouse');
el.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
expect(seen).toHaveBeenCalledTimes(1);
el.remove();
});
it('takes everything back when stopped', () => {
stop = trackTouchInput();
stop();
stop = null;
expect(root.hasAttribute(TOUCH_INPUT_ATTR)).toBe(false);
const seen = vi.fn();
document.body.addEventListener('mouseover', seen);
document.body.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
expect(seen).toHaveBeenCalledTimes(1);
document.body.removeEventListener('mouseover', seen);
});
});
+58
View File
@@ -0,0 +1,58 @@
/**
* Whether a finger or a pointer drives the app right now, for the styles that
* only make sense with one of them.
*
* After a tap, iOS and Android send the mouse events a mouse would have sent:
* mouseover first, which React reads as onMouseEnter, and WebKit sets :hover on
* the tapped element. Neither is ever taken back by a mouseout, so the tint a
* hover gives stays on the button until the next tap lands elsewhere, and on a
* phone that reads as a web page. While a finger is in use <html> carries
* data-touch-input: the build guards every :hover rule with it
* (postcss/touchHover.js), and the made-up mouseover and mouseout stop here
* before any handler sees them. A real pointer (an iPad trackpad or mouse)
* clears the mark on its first move, and hover works as on a computer.
*
* Only the app calls this. In a browser a tablet keeps tap-to-hover, which is
* how its users reach controls that show on hover.
*/
export const TOUCH_INPUT_ATTR = 'data-touch-input';
export function trackTouchInput(root: HTMLElement = document.documentElement, win: Window = window): () => void {
const setTouch = (on: boolean) => {
if (on === root.hasAttribute(TOUCH_INPUT_ATTR)) return;
if (on) root.setAttribute(TOUCH_INPUT_ATTR, '');
else root.removeAttribute(TOUCH_INPUT_ATTR);
};
// A phone starts with a finger; a trackpad says otherwise as soon as it moves.
setTouch(true);
const onPointerDown = (e: PointerEvent) => setTouch(e.pointerType !== 'mouse');
const onPointerMove = (e: PointerEvent) => {
if (e.pointerType === 'mouse') setTouch(false);
};
// Captured on the window, ahead of React's listener on the root and of every element's.
const swallow = (e: Event) => {
if (root.hasAttribute(TOUCH_INPUT_ATTR)) e.stopImmediatePropagation();
};
// WebKit applies :active on a phone only where a touchstart listener exists.
const noop = () => {};
const opts = { capture: true, passive: true } as const;
win.addEventListener('pointerdown', onPointerDown, opts);
win.addEventListener('pointerover', onPointerMove, opts);
win.addEventListener('pointermove', onPointerMove, opts);
win.addEventListener('mouseover', swallow, true);
win.addEventListener('mouseout', swallow, true);
win.document.addEventListener('touchstart', noop, { passive: true });
return () => {
win.removeEventListener('pointerdown', onPointerDown, opts);
win.removeEventListener('pointerover', onPointerMove, opts);
win.removeEventListener('pointermove', onPointerMove, opts);
win.removeEventListener('mouseover', swallow, true);
win.removeEventListener('mouseout', swallow, true);
win.document.removeEventListener('touchstart', noop);
root.removeAttribute(TOUCH_INPUT_ATTR);
};
}
+38
View File
@@ -0,0 +1,38 @@
import { useEffect, useRef, useState } from 'react';
import { askNatively, canAskNatively, type NativeQuestion } from './nativeDialogs';
/**
* Asks `question` through the system once each time `open` turns true, and
* hands the answer to `answer`. Returns whether the caller should draw its own
* HTML dialog instead: always in a browser or an app without the plugins, and
* when the system could not ask. A null question (one the system cannot show,
* such as one with a list under it) is always asked in HTML.
*/
export function useNativeQuestion(
open: boolean,
question: NativeQuestion | null,
answer: (yes: boolean) => void
): boolean {
const native = question !== null && canAskNatively();
const [failed, setFailed] = useState(false);
// Asked once per opening, also when StrictMode runs the effect twice.
const asked = useRef(false);
const latest = useRef({ question, answer });
latest.current = { question, answer };
useEffect(() => {
if (!open) {
asked.current = false;
setFailed(false);
return;
}
if (!native || asked.current || !latest.current.question) return;
asked.current = true;
void askNatively(latest.current.question).then((yes) => {
if (yes === null) setFailed(true);
else latest.current.answer(yes);
});
}, [open, native]);
return !native || failed;
}