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
@@ -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')
+6
View File
@@ -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')
@@ -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.
+4
View File
@@ -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"),
+2
View File
@@ -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",
+7 -5
View File
@@ -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()],
};
+49
View File
@@ -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;
@@ -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();
});
});
});
+18 -2
View File
@@ -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({
@@ -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);
};
@@ -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,
+28
View File
@@ -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"] {
+7 -1
View File
@@ -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]'
+14 -1
View File
@@ -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>
@@ -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"
/>
@@ -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>
@@ -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>
@@ -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
@@ -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
@@ -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>
@@ -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>
@@ -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}
/>
@@ -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" />}
@@ -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
@@ -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"
/>
)}
@@ -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)
})
})
@@ -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,
@@ -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>
)}
@@ -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
@@ -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"
/>
@@ -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)
@@ -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 ${
+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;
}
@@ -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 }`);
});
});
+20
View File
@@ -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",