From 5cc5bd7f7efc9f194e100b5184ce28d8d1487743 Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Mon, 20 Jul 2026 10:10:31 +0200 Subject: [PATCH] feat(mobile): haptics, iOS keyboard inset, composer scroll, hardware back button --- .../android/app/src/main/AndroidManifest.xml | 3 ++ .../java/moe/sable/client/MainActivity.kt | 28 ++++++++++ src-tauri/src/ios.rs | 32 +++++++++++ src-tauri/src/lib.rs | 2 + src/app/components/SwipeableChatWrapper.tsx | 2 + .../components/SwipeableMessageWrapper.tsx | 7 ++- src/app/components/editor/Editor.tsx | 8 +++ .../components/image-viewer/ImageViewer.tsx | 7 +++ src/app/components/page/MobileNavDrawer.tsx | 3 ++ src/app/utils/androidBack.ts | 53 +++++++++++++++++++ src/app/utils/haptics.ts | 21 ++++++++ src/app/utils/tauriNative.ts | 42 +++++++++++++++ src/index.tsx | 4 ++ 13 files changed, 211 insertions(+), 1 deletion(-) create mode 100644 src/app/utils/androidBack.ts create mode 100644 src/app/utils/haptics.ts create mode 100644 src/app/utils/tauriNative.ts diff --git a/src-tauri/gen/android/app/src/main/AndroidManifest.xml b/src-tauri/gen/android/app/src/main/AndroidManifest.xml index a8d3a0936..69ae2e369 100644 --- a/src-tauri/gen/android/app/src/main/AndroidManifest.xml +++ b/src-tauri/gen/android/app/src/main/AndroidManifest.xml @@ -4,6 +4,9 @@ + + + diff --git a/src-tauri/gen/android/app/src/main/java/moe/sable/client/MainActivity.kt b/src-tauri/gen/android/app/src/main/java/moe/sable/client/MainActivity.kt index 7130a13a3..1210a6554 100644 --- a/src-tauri/gen/android/app/src/main/java/moe/sable/client/MainActivity.kt +++ b/src-tauri/gen/android/app/src/main/java/moe/sable/client/MainActivity.kt @@ -2,12 +2,18 @@ package moe.sable.client import android.graphics.Color import android.os.Bundle +import android.webkit.WebView +import androidx.activity.OnBackPressedCallback import androidx.activity.enableEdgeToEdge import androidx.core.view.WindowCompat class MainActivity : TauriActivity() { private external fun nativeInitStatusBar() + // Route the hardware back button through the web app (see onWebViewCreate). + override val handleBackNavigation: Boolean = false + private var webView: WebView? = null + override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) @@ -15,6 +21,28 @@ class MainActivity : TauriActivity() { runCatching { nativeInitStatusBar() } } + override fun onWebViewCreate(webView: WebView) { + this.webView = webView + onBackPressedDispatcher.addCallback( + this, + object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + val wv = this@MainActivity.webView + if (wv == null) { + moveTaskToBack(true) + return + } + // If the web app didn't consume the back press, background the app. + wv.evaluateJavascript( + "(typeof window.__sableAndroidBack === 'function' && window.__sableAndroidBack() === true)" + ) { result -> + if (result != "true") moveTaskToBack(true) + } + } + } + ) + } + override fun onDestroy() { if (instance === this) instance = null super.onDestroy() diff --git a/src-tauri/src/ios.rs b/src-tauri/src/ios.rs index 26ab66caf..6bb47393a 100644 --- a/src-tauri/src/ios.rs +++ b/src-tauri/src/ios.rs @@ -5,6 +5,7 @@ use std::ffi::CString; +use objc2::rc::{Allocated, Retained}; use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel}; use objc2::{msg_send, sel}; use tauri::webview::WebviewWindow; @@ -23,6 +24,37 @@ pub fn enable_swipe_back_navigation(window: &WebviewWindow }); } +// UIFeedbackGenerator must run on the main thread, where Tauri schedules mobile +// commands. +#[tauri::command] +pub fn haptic_feedback(style: String) { + unsafe { + if style == "selection" { + let Some(cls) = AnyClass::get(c"UISelectionFeedbackGenerator") else { + return; + }; + let allocated: Allocated = msg_send![cls, alloc]; + let generator: Retained = msg_send![allocated, init]; + let _: () = msg_send![&*generator, prepare]; + let _: () = msg_send![&*generator, selectionChanged]; + } else { + // UIImpactFeedbackStyle: light = 0, medium = 1, heavy = 2. + let intensity: isize = match style.as_str() { + "medium" => 1, + "heavy" => 2, + _ => 0, + }; + let Some(cls) = AnyClass::get(c"UIImpactFeedbackGenerator") else { + return; + }; + let allocated: Allocated = msg_send![cls, alloc]; + let generator: Retained = msg_send![allocated, initWithStyle: intensity]; + let _: () = msg_send![&*generator, prepare]; + let _: () = msg_send![&*generator, impactOccurred]; + } + } +} + pub fn hide_form_accessory_bar(window: &WebviewWindow) { let _ = window.with_webview(|webview| unsafe { let webview: *mut AnyObject = webview.inner().cast(); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 088b4ce3f..e5b37fb55 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -327,6 +327,8 @@ pub fn run() { mobile::set_status_bar_color, #[cfg(target_os = "android")] mobile::set_navigation_bar_color, + #[cfg(target_os = "ios")] + ios::haptic_feedback, #[cfg(desktop)] desktop::download::save_download, #[cfg(desktop)] diff --git a/src/app/components/SwipeableChatWrapper.tsx b/src/app/components/SwipeableChatWrapper.tsx index 1ed0ecf30..854197705 100644 --- a/src/app/components/SwipeableChatWrapper.tsx +++ b/src/app/components/SwipeableChatWrapper.tsx @@ -3,6 +3,7 @@ import { animate, motion, useMotionValue } from 'framer-motion'; import { useDrag } from '@use-gesture/react'; import { useSetting } from '$state/hooks/settings'; import { settingsAtom, RightSwipeAction } from '$state/settings'; +import { haptic } from '$utils/haptics'; import { mobileOrTablet } from '$utils/user-agent'; interface SwipeableChatWrapperProps { @@ -48,6 +49,7 @@ export function SwipeableChatWrapper({ const velocityThreshold = 0.5; if (val < -swipeThreshold || (vx > velocityThreshold && dx < 0 && val < 0)) { + haptic('light'); if (rightSwipeAction === RightSwipeAction.Members) { onOpenMembers?.(); } else { diff --git a/src/app/components/SwipeableMessageWrapper.tsx b/src/app/components/SwipeableMessageWrapper.tsx index 43ab00434..72e5bdf5b 100644 --- a/src/app/components/SwipeableMessageWrapper.tsx +++ b/src/app/components/SwipeableMessageWrapper.tsx @@ -5,6 +5,7 @@ import { useMemo, useState } from 'react'; import { useAtomValue } from 'jotai'; import { config } from 'folds'; import { ArrowBendUpLeftIcon, getPhosphorIconSize } from '$components/icons/phosphor'; +import { haptic } from '$utils/haptics'; import { mobileOrTablet } from '$utils/user-agent'; import { RightSwipeAction, settingsAtom } from '$state/settings'; @@ -19,7 +20,11 @@ function ActiveSwipeWrapper({ children, onReply }: { children: ReactNode; onRepl if (active) { const val = mx < 0 ? mx : 0; x.set(Math.max(-80, val)); - if (mx < -50 !== isReady) setIsReady(mx < -50); + const nextReady = mx < -50; + if (nextReady !== isReady) { + setIsReady(nextReady); + if (nextReady) haptic('selection'); + } } else { if (mx < -50) onReply(); x.set(0); diff --git a/src/app/components/editor/Editor.tsx b/src/app/components/editor/Editor.tsx index 076cae68e..881d19a6d 100644 --- a/src/app/components/editor/Editor.tsx +++ b/src/app/components/editor/Editor.tsx @@ -450,6 +450,14 @@ export const CustomEditor = forwardRef( if (next && next !== editableRef.current && next.isContentEditable) return; ReactEditor.focus(editor); }} + // Once the virtual keyboard has settled, make sure the composer is + // not left hidden behind it. + onFocus={() => { + if (!mobileOrTablet()) return; + window.setTimeout(() => { + rootRef.current?.scrollIntoView({ block: 'nearest' }); + }, 300); + }} style={{ boxShadow: 'none' }} /> diff --git a/src/app/components/image-viewer/ImageViewer.tsx b/src/app/components/image-viewer/ImageViewer.tsx index ab3fde562..8f141ce17 100644 --- a/src/app/components/image-viewer/ImageViewer.tsx +++ b/src/app/components/image-viewer/ImageViewer.tsx @@ -27,6 +27,7 @@ import { sizedIcon, } from '$components/icons/phosphor'; import { useImageGestures } from '$hooks/useImageGestures'; +import { useAndroidBackHandler } from '$utils/androidBack'; import { useSetting } from '$state/hooks/settings'; import { isPixelatedRendering, settingsAtom } from '$state/settings'; import { downloadMedia } from '$utils/matrix'; @@ -51,6 +52,12 @@ export const ImageViewer = as<'div', ImageViewerProps>( const zoomInputRef = useRef(null); const [pixelatedImageRendering] = useSetting(settingsAtom, 'pixelatedImageRendering'); + // Android back closes the viewer instead of navigating away. + useAndroidBackHandler(() => { + requestClose(); + return true; + }); + const [isImageReady, setIsImageReady] = useState(false); const [isEditingZoom, setIsEditingZoom] = useState(false); const [zoomInput, setZoomInput] = useState('100'); diff --git a/src/app/components/page/MobileNavDrawer.tsx b/src/app/components/page/MobileNavDrawer.tsx index 39ba12a45..963db0b3f 100644 --- a/src/app/components/page/MobileNavDrawer.tsx +++ b/src/app/components/page/MobileNavDrawer.tsx @@ -18,6 +18,7 @@ import { SPACE_ROOM_PATH, } from '$pages/paths'; import { resolveSection } from '$pages/pathUtils'; +import { haptic } from '$utils/haptics'; import { isRoomAlias, isRoomId } from '$utils/matrix'; import { PersistentRoomHost } from './PersistentRoomHost'; @@ -212,6 +213,7 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra draggingRef.current = false; const opened = width + ox > width * OPEN_FRACTION || (vx > VELOCITY_THRESHOLD && dx > 0); if (opened) { + haptic('light'); panelIntentRef.current = 0; setPanelIntent(0); settle(0); @@ -252,6 +254,7 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra const lastRoomId = lastRoom?.[section.key]; if (lastRoomId) { const roomPath = section.getRoomPath(lastRoomId); + haptic('light'); panelIntentRef.current = 1; setPanelIntent(1); settle(-width); diff --git a/src/app/utils/androidBack.ts b/src/app/utils/androidBack.ts new file mode 100644 index 000000000..7f6b96d77 --- /dev/null +++ b/src/app/utils/androidBack.ts @@ -0,0 +1,53 @@ +import { useEffect, useRef } from 'react'; +import { isTauri } from '@tauri-apps/api/core'; +import { type as osType } from '@tauri-apps/plugin-os'; + +// Returns true if it consumed the back event (e.g. closed an overlay). +export type AndroidBackHandler = () => boolean; + +const handlers: AndroidBackHandler[] = []; + +export function pushAndroidBackHandler(handler: AndroidBackHandler): () => void { + handlers.push(handler); + return () => { + const index = handlers.lastIndexOf(handler); + if (index !== -1) handlers.splice(index, 1); + }; +} + +function routerBack(): boolean { + const idx = (window.history.state as { idx?: number } | null)?.idx ?? 0; + if (idx > 0) { + window.history.back(); + return true; + } + return false; +} + +function runAndroidBack(): boolean { + for (let i = handlers.length - 1; i >= 0; i -= 1) { + if (handlers[i]?.()) return true; + } + return routerBack(); +} + +declare global { + interface Window { + __sableAndroidBack?: () => boolean; + } +} + +export function installAndroidBackBridge(): void { + if (!isTauri() || osType() !== 'android') return; + window.__sableAndroidBack = runAndroidBack; +} + +export function useAndroidBackHandler(handler: AndroidBackHandler, enabled = true): void { + const handlerRef = useRef(handler); + handlerRef.current = handler; + + useEffect(() => { + if (!enabled) return undefined; + return pushAndroidBackHandler(() => handlerRef.current()); + }, [enabled]); +} diff --git a/src/app/utils/haptics.ts b/src/app/utils/haptics.ts new file mode 100644 index 000000000..460b3172e --- /dev/null +++ b/src/app/utils/haptics.ts @@ -0,0 +1,21 @@ +import { invoke, isTauri } from '@tauri-apps/api/core'; +import { type as osType } from '@tauri-apps/plugin-os'; + +export type HapticKind = 'light' | 'medium' | 'heavy' | 'selection'; + +const ANDROID_MS: Record = { + light: 8, + medium: 12, + heavy: 18, + selection: 5, +}; + +export function haptic(kind: HapticKind = 'light'): void { + if (!isTauri()) return; + const os = osType(); + if (os === 'android') { + navigator.vibrate?.(ANDROID_MS[kind]); + } else if (os === 'ios') { + invoke('haptic_feedback', { style: kind }).catch(() => {}); + } +} diff --git a/src/app/utils/tauriNative.ts b/src/app/utils/tauriNative.ts new file mode 100644 index 000000000..a8d9788bd --- /dev/null +++ b/src/app/utils/tauriNative.ts @@ -0,0 +1,42 @@ +import { isTauri } from '@tauri-apps/api/core'; +import { type as osType } from '@tauri-apps/plugin-os'; + +const KEYBOARD_HEIGHT = '--keyboard-height'; + +function installIosKeyboardInset(): () => void { + let frame = 0; + + const update = () => { + frame = 0; + const viewport = window.visualViewport; + const height = viewport ? window.innerHeight - viewport.height - viewport.offsetTop : 0; + document.documentElement.style.setProperty( + KEYBOARD_HEIGHT, + `${Math.max(0, Math.round(height))}px` + ); + }; + + const schedule = () => { + if (frame) cancelAnimationFrame(frame); + frame = requestAnimationFrame(update); + }; + + update(); + window.visualViewport?.addEventListener('resize', schedule); + window.visualViewport?.addEventListener('scroll', schedule); + window.addEventListener('orientationchange', schedule); + + return () => { + if (frame) cancelAnimationFrame(frame); + window.visualViewport?.removeEventListener('resize', schedule); + window.visualViewport?.removeEventListener('scroll', schedule); + window.removeEventListener('orientationchange', schedule); + }; +} + +export function installTauriNativeBehaviors(): void { + if (!isTauri()) return; + + const os = osType(); + if (os === 'ios') installIosKeyboardInset(); +} diff --git a/src/index.tsx b/src/index.tsx index 036d41cbb..cc5c5ec8d 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -24,6 +24,8 @@ import { initTauriMediaSession } from './app/utils/tauriMediaAuth'; import { registerAppServiceWorker } from './serviceWorkerBootstrap'; import { hasServiceWorker } from './app/utils/platform'; import { installIosPwaViewportHeight } from './app/utils/iosPwaViewport'; +import { installTauriNativeBehaviors } from './app/utils/tauriNative'; +import { installAndroidBackBridge } from './app/utils/androidBack'; enableMapSet(); installConsolePasteScamWarning(); @@ -32,6 +34,8 @@ const log = createLogger('index'); document.body.classList.add(configClass, varsClass); installIosPwaViewportHeight(); +installTauriNativeBehaviors(); +installAndroidBackBridge(); registerAppServiceWorker();