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 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 = /(?+~(,]/; + +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(); + 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(); + 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(); + 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( + +
  • three places
+
, + ); + 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 ? : null + return mounted ? : 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({ '); + prepareField(el); + expect(el.getAttribute('enterkeyhint')).toBe('go'); + }); + + it('turns capitals and corrections off for what a machine reads', () => { + for (const html of [ + '', + '', + '', + '', + '', + '', + '', + ]) { + 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 ['', '', '']) { + 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(''); + 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(''); + 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 = ''; + 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(''); + a.focus(); + expect(a.getAttribute('enterkeyhint')).toBe('done'); + stop(); + const b = field(''); + 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 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 { + 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 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",