Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

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

Mauriced06168d94a2a
diff --git a/client/android/app/capacitor.build.gradle b/client/android/app/capacitor.build.gradle
index 0fae6fad5..da95d6401 100644
--- a/client/android/app/capacitor.build.gradle
+++ b/client/android/app/capacitor.build.gradle
@@ -9,7 +9,9 @@ android {
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
+ implementation project(':capacitor-action-sheet')
implementation project(':capacitor-app')
+ implementation project(':capacitor-dialog')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-haptics')
implementation project(':capacitor-keyboard')
diff --git a/client/android/capacitor.settings.gradle b/client/android/capacitor.settings.gradle
index 108993d73..47693acf9 100644
--- a/client/android/capacitor.settings.gradle
+++ b/client/android/capacitor.settings.gradle
@@ -2,9 +2,15 @@
include ':capacitor-android'
project(':capacitor-android').projectDir = new File('../../node_modules/@capacitor/android/capacitor')
+include ':capacitor-action-sheet'
+project(':capacitor-action-sheet').projectDir = new File('../../node_modules/@capacitor/action-sheet/android')
+
include ':capacitor-app'
project(':capacitor-app').projectDir = new File('../../node_modules/@capacitor/app/android')
+include ':capacitor-dialog'
+project(':capacitor-dialog').projectDir = new File('../../node_modules/@capacitor/dialog/android')
+
include ':capacitor-filesystem'
project(':capacitor-filesystem').projectDir = new File('../../node_modules/@capacitor/filesystem/android')
diff --git a/client/ios/App/App/TrekBridgeViewController.swift b/client/ios/App/App/TrekBridgeViewController.swift
index 88136187a..69e00f541 100644
--- a/client/ios/App/App/TrekBridgeViewController.swift
+++ b/client/ios/App/App/TrekBridgeViewController.swift
@@ -50,6 +50,9 @@ class TrekBridgeViewController: CAPBridgeViewController {
// draws its own (mobile/components/MEdgeBack.tsx, feature "edgeBack"):
// the page follows the finger and an open sheet closes first.
webView?.allowsBackForwardNavigationGestures = false
+ // A long press on a link would lift a preview of the page it points to,
+ // which no native list does; the press means "drag" or nothing here.
+ webView?.allowsLinkPreview = false
}
/// Kept alive here: the content controller holds it, but only for as long as it is registered.
diff --git a/client/ios/App/CapApp-SPM/Package.swift b/client/ios/App/CapApp-SPM/Package.swift
index ac9dff196..31e1a3a87 100644
--- a/client/ios/App/CapApp-SPM/Package.swift
+++ b/client/ios/App/CapApp-SPM/Package.swift
@@ -12,7 +12,9 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/ionic-team/capacitor-swift-pm.git", exact: "8.5.2"),
+ .package(name: "CapacitorActionSheet", path: "../../../../node_modules/@capacitor/action-sheet"),
.package(name: "CapacitorApp", path: "../../../../node_modules/@capacitor/app"),
+ .package(name: "CapacitorDialog", path: "../../../../node_modules/@capacitor/dialog"),
.package(name: "CapacitorFilesystem", path: "../../../../node_modules/@capacitor/filesystem"),
.package(name: "CapacitorHaptics", path: "../../../../node_modules/@capacitor/haptics"),
.package(name: "CapacitorKeyboard", path: "../../../../node_modules/@capacitor/keyboard"),
@@ -26,7 +28,9 @@ let package = Package(
dependencies: [
.product(name: "Capacitor", package: "capacitor-swift-pm"),
.product(name: "Cordova", package: "capacitor-swift-pm"),
+ .product(name: "CapacitorActionSheet", package: "CapacitorActionSheet"),
.product(name: "CapacitorApp", package: "CapacitorApp"),
+ .product(name: "CapacitorDialog", package: "CapacitorDialog"),
.product(name: "CapacitorFilesystem", package: "CapacitorFilesystem"),
.product(name: "CapacitorHaptics", package: "CapacitorHaptics"),
.product(name: "CapacitorKeyboard", package: "CapacitorKeyboard"),
diff --git a/client/package.json b/client/package.json
index f9e842e1f..e7a9b8de9 100644
--- a/client/package.json
+++ b/client/package.json
@@ -53,9 +53,11 @@
},
"dependencies": {
"@assistant-ui/react": "0.15.25",
+ "@capacitor/action-sheet": "^8.1.1",
"@capacitor/android": "^8.5.0",
"@capacitor/app": "^8.1.1",
"@capacitor/core": "^8.5.0",
+ "@capacitor/dialog": "^8.0.1",
"@capacitor/filesystem": "^8.1.3",
"@capacitor/haptics": "^8.0.2",
"@capacitor/ios": "^8.5.0",
diff --git a/client/postcss.config.js b/client/postcss.config.js
index 2e7af2b7f..81984497d 100644
--- a/client/postcss.config.js
+++ b/client/postcss.config.js
@@ -1,6 +1,8 @@
+import autoprefixer from 'autoprefixer';
+import tailwindcss from 'tailwindcss';
+import touchHover from './postcss/touchHover.js';
+
export default {
- plugins: {
- tailwindcss: {},
- autoprefixer: {},
- },
-}
+ // touchHover last: it guards the :hover rules Tailwind has just written too.
+ plugins: [tailwindcss(), autoprefixer(), touchHover()],
+};
diff --git a/client/postcss/touchHover.js b/client/postcss/touchHover.js
new file mode 100644
index 000000000..782bc64df
--- /dev/null
+++ b/client/postcss/touchHover.js
@@ -0,0 +1,49 @@
+/**
+ * Hover styles only while a pointer drives the UI.
+ *
+ * A finger has no hover, yet WebKit and Chrome apply :hover to whatever was
+ * tapped and keep it there until the next tap lands somewhere else. In the
+ * iOS and Android app that left buttons and rows tinted after every tap, a
+ * tell of a web page that no native app has. The app marks <html> with
+ * data-touch-input while a finger is in use (src/native/touchInput.ts), and
+ * this plugin makes every :hover rule, Tailwind's and our own, wait for that
+ * mark to be gone. A browser never sets it, so nothing changes there, and an
+ * iPad with a trackpad clears it on the first pointer move.
+ *
+ * The condition sits on the hovered element itself, wrapped in :where(), so a
+ * rule keeps its specificity and still wins or loses where it did before. A
+ * :hover after a pseudo-element (::-webkit-slider-thumb:hover) stays as it is:
+ * nothing may follow it there, and a rule with an invalid selector is dropped
+ * whole.
+ */
+
+export const TOUCH_INPUT_ATTR = 'data-touch-input';
+const GUARD = `:where(:root:not([${TOUCH_INPUT_ATTR}]) *)`;
+// :hover itself, not the escaped `hover\:` inside a Tailwind class name, and not :hover-something.
+const HOVER = /(?<!\\):hover(?![\w-])/g;
+const COMPOUND_START = /[\s>+~(,]/;
+
+function compoundBefore(selector, index) {
+ let i = index - 1;
+ while (i >= 0 && !COMPOUND_START.test(selector[i])) i--;
+ return selector.slice(i + 1, index);
+}
+
+export function guardHover(selector) {
+ if (selector.includes(GUARD)) return selector;
+ return selector.replace(HOVER, (match, offset) =>
+ compoundBefore(selector, offset).includes('::') ? match : `${match}${GUARD}`
+ );
+}
+
+export default function touchHover() {
+ return {
+ postcssPlugin: 'trek-touch-hover',
+ Rule(rule) {
+ if (!rule.selector.includes(':hover')) return;
+ const next = rule.selectors.map(guardHover);
+ if (next.some((s, i) => s !== rule.selectors[i])) rule.selectors = next;
+ },
+ };
+}
+touchHover.postcss = true;
diff --git a/client/src/components/shared/ConfirmDialog.test.tsx b/client/src/components/shared/ConfirmDialog.test.tsx
index a82dd401e..720e4b423 100644
--- a/client/src/components/shared/ConfirmDialog.test.tsx
+++ b/client/src/components/shared/ConfirmDialog.test.tsx
@@ -1,7 +1,11 @@
import { render, screen, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
+import { waitFor } from '@testing-library/react';
import ConfirmDialog from './ConfirmDialog';
import Modal from './Modal';
+import { askNatively, canAskNatively } from '../../native/nativeDialogs';
+
+vi.mock('../../native/nativeDialogs', () => ({ canAskNatively: vi.fn(() => false), askNatively: vi.fn() }));
describe('ConfirmDialog', () => {
const onClose = vi.fn();
@@ -181,4 +185,51 @@ describe('ConfirmDialog', () => {
expect(onConfirm).not.toHaveBeenCalled();
});
});
+
+ describe('in the app, the system asks', () => {
+ afterEach(() => {
+ vi.mocked(canAskNatively).mockReturnValue(false);
+ vi.mocked(askNatively).mockReset();
+ });
+
+ it('FE-COMP-CONFIRM-NATIVE-001: asks once through the system, with the action in red, and confirms on yes', async () => {
+ vi.mocked(canAskNatively).mockReturnValue(true);
+ vi.mocked(askNatively).mockResolvedValue(true);
+ render(<ConfirmDialog isOpen onClose={onClose} onConfirm={onConfirm} title="Delete place" message="Gone for good." />);
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(onConfirm).toHaveBeenCalledOnce();
+ expect(askNatively).toHaveBeenCalledTimes(1);
+ expect(askNatively).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'Delete place', message: 'Gone for good.', danger: true }),
+ );
+ expect(screen.queryByText('Gone for good.')).toBeNull();
+ });
+
+ it('FE-COMP-CONFIRM-NATIVE-002: a no only closes', async () => {
+ vi.mocked(canAskNatively).mockReturnValue(true);
+ vi.mocked(askNatively).mockResolvedValue(false);
+ render(<ConfirmDialog isOpen onClose={onClose} onConfirm={onConfirm} message="Sure?" />);
+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
+ expect(onConfirm).not.toHaveBeenCalled();
+ });
+
+ it('FE-COMP-CONFIRM-NATIVE-003: falls back to the HTML card when the system cannot ask', async () => {
+ vi.mocked(canAskNatively).mockReturnValue(true);
+ vi.mocked(askNatively).mockResolvedValue(null);
+ render(<ConfirmDialog isOpen onClose={onClose} onConfirm={onConfirm} message="Sure?" />);
+ expect(await screen.findByText('Sure?')).toBeTruthy();
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it('FE-COMP-CONFIRM-NATIVE-004: keeps a question with a list under it in HTML', () => {
+ vi.mocked(canAskNatively).mockReturnValue(true);
+ render(
+ <ConfirmDialog isOpen onClose={onClose} onConfirm={onConfirm} message="Sure?">
+ <ul><li>three places</li></ul>
+ </ConfirmDialog>,
+ );
+ expect(screen.getByText('three places')).toBeTruthy();
+ expect(askNatively).not.toHaveBeenCalled();
+ });
+ });
});
diff --git a/client/src/components/shared/ConfirmDialog.tsx b/client/src/components/shared/ConfirmDialog.tsx
index bb7f494dd..1c283d3ff 100644
--- a/client/src/components/shared/ConfirmDialog.tsx
+++ b/client/src/components/shared/ConfirmDialog.tsx
@@ -5,6 +5,7 @@ import { useTranslation } from '../../i18n'
import { useIsPhone } from '../../mobile/useIsPhone'
import { DialogTile, NEUTRAL_TINT, fs } from './DialogShell'
import { useLastOpen, usePresence } from './usePresence'
+import { useNativeQuestion } from '../../native/useNativeQuestion'
interface ConfirmDialogProps {
isOpen: boolean
@@ -30,10 +31,25 @@ function runConfirm(onConfirm: () => void): void {
}
export default function ConfirmDialog(props: ConfirmDialogProps) {
- const { mounted, closing } = usePresence(props.isOpen)
+ const { t } = useTranslation()
+ // In the app the system asks (native/nativeDialogs.ts); a list under the question needs the HTML card.
+ const question = props.children
+ ? null
+ : {
+ title: props.title || t('common.confirm'),
+ message: props.message,
+ confirmLabel: props.confirmLabel || t('common.delete'),
+ cancelLabel: props.cancelLabel || t('common.cancel'),
+ danger: props.danger ?? true,
+ }
+ const html = useNativeQuestion(props.isOpen, question, (yes) => {
+ if (yes) runConfirm(props.onConfirm)
+ props.onClose()
+ })
+ const { mounted, closing } = usePresence(props.isOpen && html)
// The question stays readable while it fades, even when its owner clears the subject on close.
const shown = useLastOpen(props, props.isOpen)
- return mounted ? <ConfirmDialogFrame {...shown} isOpen={props.isOpen} closing={closing} /> : null
+ return mounted ? <ConfirmDialogFrame {...shown} isOpen={props.isOpen && html} closing={closing} /> : null
}
function ConfirmDialogFrame({
diff --git a/client/src/components/shared/CustomDateTimePicker.tsx b/client/src/components/shared/CustomDateTimePicker.tsx
index 8fe1ce2da..ce334a9e9 100644
--- a/client/src/components/shared/CustomDateTimePicker.tsx
+++ b/client/src/components/shared/CustomDateTimePicker.tsx
@@ -9,6 +9,7 @@ import { useDateFormat } from '../../hooks/useDateFormat';
import { useRemeasureSignal } from '../../hooks/useAnchoredPosition';
import { useWeekStartDay } from '../../hooks/useWeekStartDay';
import { leadingBlanks, weekdayLabels } from '../../utils/calendarWeek';
+import { selectionHaptic } from '../../native/haptics';
function daysInMonth(year: number, month: number): number {
return new Date(year, month + 1, 0).getDate();
@@ -178,6 +179,7 @@ export function CustomDatePicker({
const d = String(day).padStart(2, '0');
const iso = `${y}-${m}-${d}`;
if (isOutOfRange(iso)) return;
+ if (iso !== value) selectionHaptic();
onChange(iso);
setOpen(false);
};
diff --git a/client/src/components/shared/CustomSelect.tsx b/client/src/components/shared/CustomSelect.tsx
index af68a67be..704ca44f5 100644
--- a/client/src/components/shared/CustomSelect.tsx
+++ b/client/src/components/shared/CustomSelect.tsx
@@ -3,6 +3,7 @@ import { createPortal } from 'react-dom'
import { ChevronDown, Check } from 'lucide-react'
import { useAnchoredPosition, scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
import { useTranslation } from '../../i18n'
+import { selectionHaptic } from '../../native/haptics'
interface SelectOption {
// Callers use both string keys and numeric ids (e.g. day/place ids) as values, and
@@ -261,7 +262,7 @@ export default function CustomSelect({
type="text"
value={search}
onChange={e => setSearch(e.target.value)}
- placeholder={t('common.search')}
+ enterKeyHint="search" placeholder={t('common.search')}
aria-label={t('common.search')}
style={{
width: '100%', border: '1px solid var(--border-secondary)', borderRadius: 6,
@@ -305,7 +306,7 @@ export default function CustomSelect({
<button
key={option.value}
type="button"
- onClick={() => { onChange(option.value); closeMenu() }}
+ onClick={() => { if (!isSelected) selectionHaptic(); onChange(option.value); closeMenu() }}
style={{
width: '100%', display: 'flex', alignItems: 'center', gap: 8,
padding: '7px 10px', borderRadius: 6,
diff --git a/client/src/index.css b/client/src/index.css
index 9cbc91073..7b661f685 100644
--- a/client/src/index.css
+++ b/client/src/index.css
@@ -411,6 +411,34 @@ html[data-native-app] img {
-webkit-user-drag: none;
}
+/* 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(
+ :has(:is(button, a[href], [role='button']):active)
+ ):active {
+ opacity: 0.55;
+ transition: opacity 0s linear 60ms;
+}
+
+/* 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;
+}
+
/* Tabular-nums global für Time/Date/Currency/Counter */
time, .tabular-nums, [data-tabular],
input[type="number"], input[type="time"], input[type="date"], input[type="datetime-local"] {
diff --git a/client/src/mobile/components/MChip.tsx b/client/src/mobile/components/MChip.tsx
index 5669ad7cd..662ca4912 100644
--- a/client/src/mobile/components/MChip.tsx
+++ b/client/src/mobile/components/MChip.tsx
@@ -1,4 +1,5 @@
import { ReactNode } from 'react'
+import { selectionHaptic } from '../../native/haptics'
interface MChipProps {
active?: boolean
@@ -22,10 +23,15 @@ interface MChipProps {
/** Small pill chip: --m-act when active, neutral --m-ic surface otherwise. */
export default function MChip({ active = false, onClick, size = 'sm', pressable = false, className = '', children }: MChipProps) {
+ // A chip that is one choice of a picker clicks as it changes, like a native segmented control.
+ const press = onClick && (() => {
+ if (pressable) selectionHaptic()
+ onClick()
+ })
return (
<button
type="button"
- onClick={onClick}
+ onClick={press}
aria-pressed={pressable ? active : undefined}
className={`inline-flex flex-none items-center gap-[6px] rounded-full font-semibold ${
size === 'tap' ? 'px-[13px] py-[10px] text-[0.8125rem]' : 'px-3 py-[7px] text-[0.75rem]'
diff --git a/client/src/mobile/components/MSheet.tsx b/client/src/mobile/components/MSheet.tsx
index 8b9a948cc..53714ebfa 100644
--- a/client/src/mobile/components/MSheet.tsx
+++ b/client/src/mobile/components/MSheet.tsx
@@ -7,6 +7,7 @@ import { keepTabInside, useModalFocus } from './modalFocus'
import { useSheetDrag } from './useSheetDrag'
import { useOverlay } from '../overlayStack'
import { tickHaptic } from '../../native/haptics'
+import { useNativeQuestion } from '../../native/useNativeQuestion'
export type MSheetVariant = 'card' | 'bottom' | 'drawer'
export type MSheetMaterial = 'glass' | 'bar-glass' | 'opaque'
@@ -185,6 +186,18 @@ export default function MSheet({
}: MSheetProps) {
const { t } = useTranslation()
const { asking, markStart, requestClose, wouldAsk, keepEditing, discard, reset } = useDiscardGuard(discardGuard, onClose)
+ // In the app the system asks whether to throw the changes away; the card below is the browser's.
+ const askInSheet = useNativeQuestion(
+ asking,
+ {
+ title: t('common.unsavedTitle'),
+ message: t('common.unsavedMessage'),
+ confirmLabel: t('common.discard'),
+ cancelLabel: t('common.keepEditing'),
+ danger: true,
+ },
+ (yes) => (yes ? discard() : keepEditing()),
+ )
const [rendered, setRendered] = useState(open)
// Once the enter animation has played it is removed again: its forwards
// fill would otherwise override the inline drag transform for good.
@@ -305,7 +318,7 @@ export default function MSheet({
/>
)}
{children}
- {asking && (
+ {asking && askInSheet && (
<div className="absolute inset-0 z-10 grid place-items-center bg-[color:var(--m-dim)] p-5 backdrop-blur-[2px]">
<div role="alertdialog" aria-label={t('common.unsavedTitle')} className="w-full max-w-[320px] rounded-[22px] border border-[color:var(--m-shbr)] bg-[color:var(--m-sheetop)] p-5">
<div className="text-subtitle font-semibold text-m-ink">{t('common.unsavedTitle')}</div>
diff --git a/client/src/mobile/screens/admin/MAdminPaddleRegionsPanel.tsx b/client/src/mobile/screens/admin/MAdminPaddleRegionsPanel.tsx
index af0a35e1c..14f8fbba0 100644
--- a/client/src/mobile/screens/admin/MAdminPaddleRegionsPanel.tsx
+++ b/client/src/mobile/screens/admin/MAdminPaddleRegionsPanel.tsx
@@ -197,6 +197,7 @@ function CatalogSearch({ admin }: { admin: Admin }) {
onChange={(e) => search.setQuery(e.target.value)}
autoComplete="off"
aria-label={t('admin.paddleRegions.search')}
+ enterKeyHint="search"
placeholder={t('admin.paddleRegions.searchPlaceholder')}
className="h-[42px] w-full rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] pe-3 ps-[34px] text-[length:calc(13px*var(--fs-scale-body,1))] text-m-ink outline-none placeholder:text-m-faint"
/>
diff --git a/client/src/mobile/screens/admin/MAdminPluginsPanel.tsx b/client/src/mobile/screens/admin/MAdminPluginsPanel.tsx
index 991be710a..ee27a6bfc 100644
--- a/client/src/mobile/screens/admin/MAdminPluginsPanel.tsx
+++ b/client/src/mobile/screens/admin/MAdminPluginsPanel.tsx
@@ -217,7 +217,7 @@ export default function MAdminPluginsPanel() {
<Search size={15} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-m-faint" />
<input
value={q} onChange={e => setQ(e.target.value)} type="search"
- placeholder={t('admin.plugins.searchPlaceholder')}
+ enterKeyHint="search" placeholder={t('admin.plugins.searchPlaceholder')}
className="h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] ps-9 pe-3 text-[0.84375rem] text-m-ink outline-none placeholder:text-m-faint focus:border-[color:var(--m-faint)]"
/>
</div>
diff --git a/client/src/mobile/screens/atlas/MAtlasSearch.tsx b/client/src/mobile/screens/atlas/MAtlasSearch.tsx
index 24e3e5c82..a4e259164 100644
--- a/client/src/mobile/screens/atlas/MAtlasSearch.tsx
+++ b/client/src/mobile/screens/atlas/MAtlasSearch.tsx
@@ -75,7 +75,7 @@ export default function MAtlasSearch({
if (e.key === 'Escape') onClose()
if (e.key === 'Enter' && rows.length > 0) onSelect(rows[0].code)
}}
- placeholder={t('atlas.searchCountry')}
+ enterKeyHint="search" placeholder={t('atlas.searchCountry')}
className="min-w-0 flex-1 bg-transparent font-geist text-[0.9375rem] font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
/>
</label>
diff --git a/client/src/mobile/screens/collections/MCollAddSheet.tsx b/client/src/mobile/screens/collections/MCollAddSheet.tsx
index 6cbab86df..a5b6ffddb 100644
--- a/client/src/mobile/screens/collections/MCollAddSheet.tsx
+++ b/client/src/mobile/screens/collections/MCollAddSheet.tsx
@@ -72,7 +72,7 @@ export default function MCollAddSheet({ open, collectionId, collectionName, list
value={query}
onChange={e => setQuery(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); void search() } }}
- placeholder={t('collections.addPlaceSearch')}
+ enterKeyHint="search" placeholder={t('collections.addPlaceSearch')}
className="min-w-0 flex-1 bg-transparent font-[inherit] text-[0.8125rem] text-m-ink outline-none placeholder:text-m-faint"
/>
<button
diff --git a/client/src/mobile/screens/collections/MCollEditSheet.tsx b/client/src/mobile/screens/collections/MCollEditSheet.tsx
index b529838ed..f43997c5a 100644
--- a/client/src/mobile/screens/collections/MCollEditSheet.tsx
+++ b/client/src/mobile/screens/collections/MCollEditSheet.tsx
@@ -76,7 +76,7 @@ export default function MCollEditSheet({ target, onClose, onCreated, onRequestDe
value={coverQuery}
onChange={e => setCoverQuery(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); void searchCover() } }}
- placeholder={t('dashboard.unsplashSearchPlaceholder')}
+ enterKeyHint="search" placeholder={t('dashboard.unsplashSearchPlaceholder')}
className={`${INPUT_CLS} min-w-0 flex-1`}
/>
<button
diff --git a/client/src/mobile/screens/collections/MCollTripPickerSheet.tsx b/client/src/mobile/screens/collections/MCollTripPickerSheet.tsx
index 8159e376b..656e87324 100644
--- a/client/src/mobile/screens/collections/MCollTripPickerSheet.tsx
+++ b/client/src/mobile/screens/collections/MCollTripPickerSheet.tsx
@@ -32,7 +32,7 @@ export default function MCollTripPickerSheet({ open, count, onCopy, onClose, t }
<input
value={search}
onChange={e => setSearch(e.target.value)}
- placeholder={t('collections.copyToTripSearch')}
+ enterKeyHint="search" placeholder={t('collections.copyToTripSearch')}
className="min-w-0 flex-1 bg-transparent font-geist text-[0.78125rem] text-m-ink outline-none placeholder:text-m-faint"
/>
</div>
diff --git a/client/src/mobile/screens/collections/MCollections.tsx b/client/src/mobile/screens/collections/MCollections.tsx
index 092c5c3be..01ffdb7c6 100644
--- a/client/src/mobile/screens/collections/MCollections.tsx
+++ b/client/src/mobile/screens/collections/MCollections.tsx
@@ -271,7 +271,7 @@ export default function MCollections() {
<input
value={c.search}
onChange={e => c.setSearch(e.target.value)}
- placeholder={t('collections.search')}
+ enterKeyHint="search" placeholder={t('collections.search')}
className="min-w-0 flex-1 bg-transparent font-geist text-[0.78125rem] text-m-ink outline-none placeholder:text-m-faint"
/>
</div>
diff --git a/client/src/mobile/screens/dashboard/MNewTripSheet.tsx b/client/src/mobile/screens/dashboard/MNewTripSheet.tsx
index af1261743..2859f8700 100644
--- a/client/src/mobile/screens/dashboard/MNewTripSheet.tsx
+++ b/client/src/mobile/screens/dashboard/MNewTripSheet.tsx
@@ -413,7 +413,7 @@ function CoverField({ cover, title }: { cover: ReturnType<typeof useTripCoverPic
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); void cover.search() } }}
- placeholder={t('dashboard.unsplashSearchPlaceholder')}
+ enterKeyHint="search" placeholder={t('dashboard.unsplashSearchPlaceholder')}
aria-label={t('dashboard.unsplashSearchPlaceholder')}
className={SHEET_FIELD}
/>
diff --git a/client/src/mobile/screens/journey/MJourneyEntrySheet.tsx b/client/src/mobile/screens/journey/MJourneyEntrySheet.tsx
index 85114a86a..d9e753a0c 100644
--- a/client/src/mobile/screens/journey/MJourneyEntrySheet.tsx
+++ b/client/src/mobile/screens/journey/MJourneyEntrySheet.tsx
@@ -555,7 +555,7 @@ export default function MJourneyEntrySheet({
readOnly={readOnly}
onChange={e => searchLocation(e.target.value)}
onFocus={() => { if (locationResults.length > 0) setShowLocationResults(true) }}
- placeholder={t('journey.editor.searchLocation')}
+ enterKeyHint="search" placeholder={t('journey.editor.searchLocation')}
className="min-w-0 flex-1 bg-transparent font-geist text-[0.75rem] text-m-ink outline-none placeholder:text-m-faint"
/>
{locationLat != null && <MapPin size={13} className="flex-none text-m-muted" />}
diff --git a/client/src/mobile/screens/trip/places/MPlacesBrowser.tsx b/client/src/mobile/screens/trip/places/MPlacesBrowser.tsx
index b91441b15..db45385a4 100644
--- a/client/src/mobile/screens/trip/places/MPlacesBrowser.tsx
+++ b/client/src/mobile/screens/trip/places/MPlacesBrowser.tsx
@@ -188,7 +188,7 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
<input
value={search}
onChange={e => updateSearch(e.target.value)}
- placeholder={t('places.search')}
+ enterKeyHint="search" placeholder={t('places.search')}
className="box-border min-w-0 flex-1 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[13px] py-[10px] text-[0.8125rem] font-medium text-m-ink outline-none placeholder:text-m-faint"
/>
<button
diff --git a/client/src/mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx b/client/src/mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx
index ef12a9615..87f926211 100644
--- a/client/src/mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx
+++ b/client/src/mobile/screens/trip/places/MPlacesSaveToCollectionSheet.tsx
@@ -39,7 +39,7 @@ export default function MPlacesSaveToCollectionSheet({ open, tripId, placeIds, o
<input
value={search}
onChange={e => setSearch(e.target.value)}
- placeholder={t('common.search')}
+ enterKeyHint="search" placeholder={t('common.search')}
className="mt-2 box-border w-full rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[13px] py-[10px] text-[0.8125rem] font-medium text-m-ink outline-none placeholder:text-m-faint"
/>
)}
diff --git a/client/src/mobile/screens/trip/plan/useMPlanDragReorder.test.ts b/client/src/mobile/screens/trip/plan/useMPlanDragReorder.test.ts
index 736cea1b4..789777ce3 100644
--- a/client/src/mobile/screens/trip/plan/useMPlanDragReorder.test.ts
+++ b/client/src/mobile/screens/trip/plan/useMPlanDragReorder.test.ts
@@ -1,9 +1,12 @@
import { describe, it, expect, vi } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { useMPlanDragReorder } from './useMPlanDragReorder'
+import { pressHaptic, selectionHaptic, tickHaptic } from '../../../../native/haptics'
import type { MergedItem } from '../../../../utils/dayMerge'
import type { PlanRow } from './planTimelineModel'
+vi.mock('../../../../native/haptics', () => ({ pressHaptic: vi.fn(), selectionHaptic: vi.fn(), tickHaptic: vi.fn() }))
+
const items = [
{ type: 'place', data: { id: 1 } },
{ type: 'place', data: { id: 2 } },
@@ -113,4 +116,21 @@ describe('useMPlanDragReorder', () => {
expect(() => act(() => { result.current.dragPropsFor(rowFor(0))!.onDragStart(broken) })).not.toThrow()
expect(result.current.draggingKey).toBe('row-0')
})
+
+ it('FE-MOB-DRAG-011: lifts with a bump, clicks once per new slot and ticks on the drop', () => {
+ vi.mocked(pressHaptic).mockClear()
+ vi.mocked(selectionHaptic).mockClear()
+ vi.mocked(tickHaptic).mockClear()
+ const { result, onMove } = setup()
+ act(() => { result.current.dragPropsFor(rowFor(0))!.onDragStart(dragEvent()) })
+ expect(pressHaptic).toHaveBeenCalledTimes(1)
+ act(() => { result.current.dragPropsFor(rowFor(0))!.onDragOver(dragEvent()) })
+ expect(selectionHaptic).not.toHaveBeenCalled()
+ act(() => { result.current.dragPropsFor(rowFor(2))!.onDragOver(dragEvent()) })
+ act(() => { result.current.dragPropsFor(rowFor(2))!.onDragOver(dragEvent()) })
+ expect(selectionHaptic).toHaveBeenCalledTimes(1)
+ act(() => { result.current.dragPropsFor(rowFor(2))!.onDrop(dragEvent()) })
+ expect(tickHaptic).toHaveBeenCalledTimes(1)
+ expect(onMove).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/client/src/mobile/screens/trip/plan/useMPlanDragReorder.ts b/client/src/mobile/screens/trip/plan/useMPlanDragReorder.ts
index 604088c40..d4964aaad 100644
--- a/client/src/mobile/screens/trip/plan/useMPlanDragReorder.ts
+++ b/client/src/mobile/screens/trip/plan/useMPlanDragReorder.ts
@@ -1,4 +1,5 @@
import { useCallback, useRef, useState, type DragEvent } from 'react'
+import { pressHaptic, selectionHaptic, tickHaptic } from '../../../../native/haptics'
import type { MergedItem } from '../../../../utils/dayMerge'
import type { PlanRow } from './planTimelineModel'
@@ -57,9 +58,12 @@ export function useMPlanDragReorder({ merged, dayId, onMove, enabled }: DragReor
// The bridge's DataTransfer is a shim on browsers that refuse `new DataTransfer()`,
// so the source also rides along in a ref — same as the desktop sidebar does.
const sourceRef = useRef<MergedItem | null>(null)
+ // The row last passed over, so the finger feels each new slot once, as in a native list.
+ const overRef = useRef<string | null>(null)
const clear = useCallback(() => {
sourceRef.current = null
+ overRef.current = null
setDraggingKey(null)
setDropBeforeKey(null)
}, [])
@@ -73,6 +77,8 @@ export function useMPlanDragReorder({ merged, dayId, onMove, enabled }: DragReor
draggable: true,
onDragStart: (e: DragEvent) => {
sourceRef.current = item
+ overRef.current = row.key
+ pressHaptic()
setDraggingKey(row.key)
try {
e.dataTransfer.setData('planRowKey', row.key)
@@ -84,6 +90,10 @@ export function useMPlanDragReorder({ merged, dayId, onMove, enabled }: DragReor
// preventDefault is how a drop target says yes — the bridge reads it too.
e.preventDefault()
e.stopPropagation()
+ if (overRef.current !== row.key) {
+ overRef.current = row.key
+ selectionHaptic()
+ }
setDropBeforeKey(prev => (prev === row.key ? prev : row.key))
},
onDrop: (e: DragEvent) => {
@@ -94,6 +104,7 @@ export function useMPlanDragReorder({ merged, dayId, onMove, enabled }: DragReor
if (!source || source === item) return
const to = merged.indexOf(item)
if (to < 0) return
+ tickHaptic()
onMove(source, to)
},
onDragEnd: clear,
diff --git a/client/src/mobile/screens/trip/sheets/MLinkedCosts.tsx b/client/src/mobile/screens/trip/sheets/MLinkedCosts.tsx
index 302bdff0e..85f02765a 100644
--- a/client/src/mobile/screens/trip/sheets/MLinkedCosts.tsx
+++ b/client/src/mobile/screens/trip/sheets/MLinkedCosts.tsx
@@ -106,7 +106,7 @@ export default function MLinkedCosts({ reservationId = null, placeId = null, hin
{unlinked.length >= SEARCH_FROM && (
<div className="mx-1 mb-1 mt-1 flex items-center gap-2 rounded-[10px] bg-[color:var(--m-ic)] px-[10px] py-[7px]">
<Search size={13} strokeWidth={2} className="flex-none text-m-faint" />
- <input value={query} onChange={e => setQuery(e.target.value)} placeholder={t('common.search')}
+ <input value={query} onChange={e => setQuery(e.target.value)} enterKeyHint="search" placeholder={t('common.search')}
className="min-w-0 flex-1 bg-transparent text-[0.78125rem] text-m-ink outline-none placeholder:text-m-faint" />
</div>
)}
diff --git a/client/src/mobile/screens/trip/sheets/PlPlaceSearch.tsx b/client/src/mobile/screens/trip/sheets/PlPlaceSearch.tsx
index 008503278..2a4637ad0 100644
--- a/client/src/mobile/screens/trip/sheets/PlPlaceSearch.tsx
+++ b/client/src/mobile/screens/trip/sheets/PlPlaceSearch.tsx
@@ -110,7 +110,7 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggest
}
}}
onBlur={() => setTimeout(() => setSuggestions([]), 150)}
- placeholder={t('places.mapsSearchPlaceholder')}
+ enterKeyHint="search" placeholder={t('places.mapsSearchPlaceholder')}
className={`${FIELD_CLS} flex-1`}
/>
<button
diff --git a/client/src/mobile/screens/trip/tabs/MCostsTab.tsx b/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
index bc0baecc1..2002611be 100644
--- a/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
+++ b/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
@@ -338,7 +338,7 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
type="text"
value={search}
onChange={e => setSearch(e.target.value)}
- placeholder={t('costs.searchPlaceholder')}
+ enterKeyHint="search" placeholder={t('costs.searchPlaceholder')}
aria-label={t('costs.searchPlaceholder')}
className="mt-2 block w-full rounded-full border border-[color:var(--m-rowbr)] bg-m-card px-[13px] py-[10px] font-[inherit] text-[0.8125rem] font-medium text-m-ink outline-none placeholder:text-m-faint"
/>
diff --git a/client/src/mobile/screens/trip/tabs/MPackingListTab.tsx b/client/src/mobile/screens/trip/tabs/MPackingListTab.tsx
index 156bf086b..db9acfa7a 100644
--- a/client/src/mobile/screens/trip/tabs/MPackingListTab.tsx
+++ b/client/src/mobile/screens/trip/tabs/MPackingListTab.tsx
@@ -1,4 +1,5 @@
import { useMemo, useState } from 'react'
+import { selectionHaptic } from '../../../../native/haptics'
import type { LucideIcon } from 'lucide-react'
import {
Briefcase, Check, CheckCheck, ChevronDown, ChevronUp, HandHelping, Minus,
@@ -671,7 +672,10 @@ function PackingItemRow({ item, planner, currentUserId, editMode, canEdit, bagTr
const ownerMember = planner.tripMembers.find(m => m.id === item.owner_id)
const ownerAvatarUrl = ownerMember?.avatar_url ?? (item.owner_id === me?.id ? me?.avatar_url ?? null : null)
- const toggle = () => tripActions.togglePackingItem(tripId, item.id, !item.checked)
+ const toggle = () => {
+ selectionHaptic()
+ return tripActions.togglePackingItem(tripId, item.id, !item.checked)
+ }
// Multi-piece items count their pieces into the bag (#2296).
const quantity = item.quantity || 1
const packed = packedOf(item)
diff --git a/client/src/mobile/screens/trip/tabs/MTodoListTab.tsx b/client/src/mobile/screens/trip/tabs/MTodoListTab.tsx
index d4ef542ce..e93cf8796 100644
--- a/client/src/mobile/screens/trip/tabs/MTodoListTab.tsx
+++ b/client/src/mobile/screens/trip/tabs/MTodoListTab.tsx
@@ -1,4 +1,5 @@
import { useState } from 'react'
+import { selectionHaptic } from '../../../../native/haptics'
import { Calendar, Check, ChevronRight, Flag, Plus } from 'lucide-react'
import MDancingTrek from '../../../components/MDancingTrek'
import MChipStrip from '../../../components/MChipStrip'
@@ -45,7 +46,10 @@ export default function MTodoListTab({ planner }: { planner: TripPlanner }) {
const openCreate = () => { setEditingItemId(null); setCreatingTask(true) }
const openEdit = (id: number) => { setCreatingTask(false); setEditingItemId(id) }
const closeSheet = () => { setCreatingTask(false); setEditingItemId(null) }
- const toggleItem = (id: number, checked: boolean) => tripActions.toggleTodoItem(tripId, id, checked)
+ const toggleItem = (id: number, checked: boolean) => {
+ selectionHaptic()
+ return tripActions.toggleTodoItem(tripId, id, checked)
+ }
const filterPill = (active: boolean) =>
`flex flex-none items-center gap-[5px] whitespace-nowrap rounded-full px-[11px] py-[6px] text-[0.71875rem] font-semibold ${
diff --git a/client/src/native/keyboardFields.test.ts b/client/src/native/keyboardFields.test.ts
new file mode 100644
index 000000000..e7efef78f
--- /dev/null
+++ b/client/src/native/keyboardFields.test.ts
@@ -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);
+ });
+});
diff --git a/client/src/native/keyboardFields.ts b/client/src/native/keyboardFields.ts
new file mode 100644
index 000000000..3a7777f1f
--- /dev/null
+++ b/client/src/native/keyboardFields.ts
@@ -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);
+ };
+}
diff --git a/client/src/native/nativeApp.test.ts b/client/src/native/nativeApp.test.ts
index f847a79d7..de73e5751 100644
--- a/client/src/native/nativeApp.test.ts
+++ b/client/src/native/nativeApp.test.ts
@@ -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);
diff --git a/client/src/native/nativeApp.ts b/client/src/native/nativeApp.ts
index 48084eda8..db4818ca5 100644
--- a/client/src/native/nativeApp.ts
+++ b/client/src/native/nativeApp.ts
@@ -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();
diff --git a/client/src/native/nativeDialogs.test.ts b/client/src/native/nativeDialogs.test.ts
new file mode 100644
index 000000000..f94368eae
--- /dev/null
+++ b/client/src/native/nativeDialogs.test.ts
@@ -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();
+ });
+});
diff --git a/client/src/native/nativeDialogs.ts b/client/src/native/nativeDialogs.ts
new file mode 100644
index 000000000..92ff7960c
--- /dev/null
+++ b/client/src/native/nativeDialogs.ts
@@ -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;
+ }
+}
diff --git a/client/src/native/touchInput.test.ts b/client/src/native/touchInput.test.ts
new file mode 100644
index 000000000..cf66bd347
--- /dev/null
+++ b/client/src/native/touchInput.test.ts
@@ -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);
+ });
+});
diff --git a/client/src/native/touchInput.ts b/client/src/native/touchInput.ts
new file mode 100644
index 000000000..4ef19574a
--- /dev/null
+++ b/client/src/native/touchInput.ts
@@ -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);
+ };
+}
diff --git a/client/src/native/useNativeQuestion.ts b/client/src/native/useNativeQuestion.ts
new file mode 100644
index 000000000..706d47bb1
--- /dev/null
+++ b/client/src/native/useNativeQuestion.ts
@@ -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;
+}
diff --git a/client/tests/unit/postcss/touchHover.test.ts b/client/tests/unit/postcss/touchHover.test.ts
new file mode 100644
index 000000000..29a441df2
--- /dev/null
+++ b/client/tests/unit/postcss/touchHover.test.ts
@@ -0,0 +1,39 @@
+import postcss from 'postcss';
+import { describe, expect, it } from 'vitest';
+import touchHover, { guardHover } from '../../../postcss/touchHover.js';
+
+const GUARD = ':where(:root:not([data-touch-input]) *)';
+const run = (css: string) => postcss([touchHover()]).process(css, { from: undefined }).css;
+
+describe('touchHover', () => {
+ it('makes a hover rule wait for the touch mark to be gone, keeping its specificity', () => {
+ expect(guardHover('.btn:hover')).toBe(`.btn:hover${GUARD}`);
+ expect(guardHover('.row:hover > .icon')).toBe(`.row:hover${GUARD} > .icon`);
+ });
+
+ it("guards Tailwind's escaped class names on their real :hover only", () => {
+ expect(guardHover('.hover\\:bg-red:hover')).toBe(`.hover\\:bg-red:hover${GUARD}`);
+ expect(guardHover('.group:hover .group-hover\\:opacity-100')).toBe(
+ `.group:hover${GUARD} .group-hover\\:opacity-100`
+ );
+ });
+
+ it('guards every :hover of a selector, inside :is() too', () => {
+ expect(guardHover(':is(.dark .dark\\:hover\\:x:hover)')).toBe(`:is(.dark .dark\\:hover\\:x:hover${GUARD})`);
+ expect(guardHover('a:hover, b:focus')).toBe(`a:hover${GUARD}, b:focus`);
+ });
+
+ it('leaves :hover after a pseudo-element alone, where nothing may follow it', () => {
+ expect(guardHover('.m-range::-webkit-slider-thumb:hover')).toBe('.m-range::-webkit-slider-thumb:hover');
+ });
+
+ it('touches neither rules without :hover nor ones already guarded', () => {
+ expect(run('.a:focus { color: red }')).toBe('.a:focus { color: red }');
+ const once = run('.a:hover { color: red }');
+ expect(run(once)).toBe(once);
+ });
+
+ it('rewrites each selector of a list on its own', () => {
+ expect(run('.a:hover, .b { color: red }')).toBe(`.a:hover${GUARD}, .b { color: red }`);
+ });
+});
diff --git a/package-lock.json b/package-lock.json
index a01ec6c3b..98abfb6e6 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -32,9 +32,11 @@
"version": "5.1.1",
"dependencies": {
"@assistant-ui/react": "0.15.25",
+ "@capacitor/action-sheet": "^8.1.1",
"@capacitor/android": "^8.5.0",
"@capacitor/app": "^8.1.1",
"@capacitor/core": "^8.5.0",
+ "@capacitor/dialog": "^8.0.1",
"@capacitor/filesystem": "^8.1.3",
"@capacitor/haptics": "^8.0.2",
"@capacitor/ios": "^8.5.0",
@@ -2461,6 +2463,15 @@
"@keyv/serialize": "^1.1.1"
}
},
+ "node_modules/@capacitor/action-sheet": {
+ "version": "8.1.1",
+ "resolved": "https://registry.npmjs.org/@capacitor/action-sheet/-/action-sheet-8.1.1.tgz",
+ "integrity": "sha512-yHuGSR/FS2dDr9oBmy+Ql+y7/i5XsUAlENx5oRND5NtzsNLLiFxpNPGLWV27aU9uf9ICjI92VzH93Zh0g2FL1A==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@capacitor/core": ">=8.0.0"
+ }
+ },
"node_modules/@capacitor/android": {
"version": "8.5.3",
"resolved": "https://registry.npmjs.org/@capacitor/android/-/android-8.5.3.tgz",
@@ -2603,6 +2614,15 @@
"tslib": "^2.1.0"
}
},
+ "node_modules/@capacitor/dialog": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/@capacitor/dialog/-/dialog-8.0.1.tgz",
+ "integrity": "sha512-Dq0mZBsd++7CvPvpD2gfbUB44k/zCoe5K9IgYmMImQ4Yphu4/MxLVpFDFAqSya011UBBTGPrUQGVacIW3jDNkw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "@capacitor/core": ">=8.0.0"
+ }
+ },
"node_modules/@capacitor/filesystem": {
"version": "8.1.5",
"resolved": "https://registry.npmjs.org/@capacitor/filesystem/-/filesystem-8.1.5.tgz",