feat(mobile): haptics, iOS keyboard inset, composer scroll, hardware back button

This commit is contained in:
Erwan Leboucher committed 2026-07-20 20:46:38 +02:00
1 parent 5d85477342
commit 5cc5bd7f7e
13 files changed
+211 -1

No files matched your search

@@ -4,6 +4,9 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<!-- Haptic feedback (navigator.vibrate) -->
<uses-permission android:name="android.permission.VIBRATE" />
<!-- WebRTC calls (camera/mic) -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
@@ -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()
+32
View File
@@ -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<crate::BrowserEngine>
});
}
// 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<AnyObject> = msg_send![cls, alloc];
let generator: Retained<AnyObject> = 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<AnyObject> = msg_send![cls, alloc];
let generator: Retained<AnyObject> = msg_send![allocated, initWithStyle: intensity];
let _: () = msg_send![&*generator, prepare];
let _: () = msg_send![&*generator, impactOccurred];
}
}
}
pub fn hide_form_accessory_bar(window: &WebviewWindow<crate::BrowserEngine>) {
let _ = window.with_webview(|webview| unsafe {
let webview: *mut AnyObject = webview.inner().cast();
+2
View File
@@ -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)]
@@ -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 {
@@ -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);
+8
View File
@@ -450,6 +450,14 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
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' }}
/>
</Scroll>
@@ -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<HTMLInputElement>(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');
@@ -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);
+53
View File
@@ -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]);
}
+21
View File
@@ -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<HapticKind, number> = {
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(() => {});
}
}
+42
View File
@@ -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();
}
+4
View File
@@ -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();