Improve mobile room performance (#1231)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

<!-- Please include a summary of the change. Please also include
relevant motivation and context. List any dependencies that are required
for this change. -->

Fix some thread blocking on room switches and unnecessary swipe
rerenders

#### Type of change

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [ ] My code follows the style guidelines of this project
- [ ] I have performed a self-review of my own code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
7w1 authored and GitHub committed 2026-07-22 22:05:24 -05:00
commit 9f44c4c3ff
11 files changed
+104 -33

No files matched your search

+20 -8
View File
@@ -16,9 +16,9 @@ interface MobileSwipeDownModalProps {
}
export function MobileSwipeDownModal({ children, requestClose }: MobileSwipeDownModalProps) {
const containerRef = useRef<HTMLDivElement>(null);
const touchStartY = useRef<number | null>(null);
const [touchYDiff, setTouchYDiff] = useState(0);
const date = new Date();
const touchYDiff = useRef(0);
const startTime = useRef(0);
const [mounted, setMounted] = useState(false);
@@ -28,7 +28,7 @@ export function MobileSwipeDownModal({ children, requestClose }: MobileSwipeDown
const handleTouchStart = (e: React.TouchEvent) => {
touchStartY.current = e.touches[0]?.clientY ?? null;
startTime.current = date.getTime();
startTime.current = Date.now();
};
const handleTouchMove = (e: React.TouchEvent) => {
@@ -38,16 +38,27 @@ export function MobileSwipeDownModal({ children, requestClose }: MobileSwipeDown
// Only allow pulling down
if (diff > 0) {
setTouchYDiff(diff);
touchYDiff.current = diff;
if (containerRef.current) {
containerRef.current.style.transform = `translateY(${diff}px)`;
containerRef.current.style.transition = 'none';
}
}
};
const handleTouchEnd = () => {
const endTime = date.getTime();
if (touchYDiff > 100 || (endTime - startTime.current < 600 && touchYDiff > 20)) {
const endTime = Date.now();
if (
touchYDiff.current > 100 ||
(endTime - startTime.current < 600 && touchYDiff.current > 20)
) {
requestClose();
} else {
setTouchYDiff(0);
touchYDiff.current = 0;
if (containerRef.current) {
containerRef.current.style.transform = '';
containerRef.current.style.transition = 'transform 0.2s ease-out';
}
}
touchStartY.current = null;
};
@@ -76,9 +87,10 @@ export function MobileSwipeDownModal({ children, requestClose }: MobileSwipeDown
onTouchEnd={(e: React.TouchEvent) => e.stopPropagation()}
>
<Box
ref={containerRef}
className={css.MessageMobileOptionsContainer}
style={{
transform: touchYDiff > 0 ? `translateY(${touchYDiff}px)` : undefined,
transform: touchYDiff.current > 0 ? `translateY(${touchYDiff.current}px)` : undefined,
transition: touchStartY.current === null ? 'transform 0.2s ease-out' : 'none',
}}
onClick={(e: React.MouseEvent) => e.stopPropagation()}
@@ -107,6 +107,7 @@ export function SwipeableChatWrapper({
flexDirection: 'column',
flexGrow: 1,
height: '100%',
willChange: 'transform',
}}
>
{children}
+13 -7
View File
@@ -1,7 +1,7 @@
import { useMotionValue, useSpring, useTransform, motion } from 'framer-motion';
import { useMotionValue, useTransform, motion, animate } from 'framer-motion';
import { useDrag } from '@use-gesture/react';
import type { ReactNode } from 'react';
import { useMemo, useState } from 'react';
import { useMemo, useRef, useState } from 'react';
import { useAtomValue } from 'jotai';
import { config } from 'folds';
import { ArrowBendUpLeftIcon, getPhosphorIconSize } from '$components/icons/phosphor';
@@ -11,23 +11,27 @@ import { RightSwipeAction, settingsAtom } from '$state/settings';
function ActiveSwipeWrapper({ children, onReply }: { children: ReactNode; onReply: () => void }) {
const x = useMotionValue(0);
const springX = useSpring(x, { stiffness: 300, damping: 35 });
const [isReady, setIsReady] = useState(false);
const isReadyRef = useRef(false);
const iconOpacity = useTransform(x, [0, -8], [0, 1]);
const bind = useDrag(
({ active, movement: [mx] }) => {
({ first, active, movement: [mx] }) => {
if (first) x.stop();
if (active) {
const val = mx < 0 ? mx : 0;
x.set(Math.max(-80, val));
const nextReady = mx < -50;
if (nextReady !== isReady) {
if (nextReady !== isReadyRef.current) {
isReadyRef.current = nextReady;
setIsReady(nextReady);
if (nextReady) haptic('selection');
}
} else {
if (mx < -50) onReply();
x.set(0);
animate(x, 0, { type: 'spring', stiffness: 300, damping: 35 });
isReadyRef.current = false;
setIsReady(false);
}
},
@@ -66,7 +70,9 @@ function ActiveSwipeWrapper({ children, onReply }: { children: ReactNode; onRepl
/>
</motion.div>
</div>
<motion.div style={{ x: springX, position: 'relative', zIndex: 1 }}>{children}</motion.div>
<motion.div style={{ x, position: 'relative', zIndex: 1, willChange: 'transform' }}>
{children}
</motion.div>
</div>
);
}
@@ -104,6 +104,7 @@ export function SwipeableOverlayWrapper({
flexDirection: 'column',
flexGrow: 1,
height: '100%',
willChange: 'transform',
}}
>
{children}
+15 -4
View File
@@ -1,5 +1,6 @@
import type { ReactNode } from 'react';
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { startTransition, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import type { AnimationPlaybackControls } from 'framer-motion';
import { animate, motion, useDragControls, useMotionValue, useReducedMotion } from 'framer-motion';
import { useAtomValue, useSetAtom } from 'jotai';
import { matchPath, useLocation, useNavigate } from 'react-router-dom';
@@ -72,6 +73,7 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra
const [width, setWidth] = useState(0);
const x = useMotionValue(0);
const dragControls = useDragControls();
const settleAnimRef = useRef<AnimationPlaybackControls | null>(null);
const initialIntent = contentOpen ? 1 : 0;
const [panelIntent, setPanelIntent] = useState(initialIntent);
@@ -92,11 +94,14 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra
const settle = useCallback(
(target: number) => {
settleAnimRef.current?.stop();
settleAnimRef.current = null;
if (reduceMotion) {
x.jump(target);
return;
}
animate(x, target, {
settleAnimRef.current = animate(x, target, {
type: 'spring',
stiffness: SETTLE_STIFFNESS,
damping: SETTLE_DAMPING,
@@ -130,12 +135,16 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra
if (width > 0 && !reduceMotion) {
settle(target);
} else {
settleAnimRef.current?.stop();
settleAnimRef.current = null;
x.jump(target);
}
}
}, [contentOpen, width, x, settle, reduceMotion]);
useLayoutEffect(() => {
settleAnimRef.current?.stop();
settleAnimRef.current = null;
const target = panelIntentRef.current === 1 ? -width : 0;
x.jump(target);
}, [width, x]);
@@ -171,6 +180,8 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra
dragMomentum={false}
onDragStart={() => {
x.stop();
settleAnimRef.current?.stop();
settleAnimRef.current = null;
if (panelIntentRef.current === 0 && !roomArmed) setRoomArmed(true);
}}
onDragEnd={(_event, info) => {
@@ -187,7 +198,7 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra
if (section?.getRoomPath && matchedRoomId && isRoomRoute) {
setLastRoom((prev) => ({ ...prev, [section.key]: matchedRoomId }));
}
if (section) navigate(section.listPath);
if (section) startTransition(() => navigate(section.listPath));
} else {
settle(-width);
}
@@ -205,7 +216,7 @@ export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDra
panelIntentRef.current = 1;
setPanelIntent(1);
settle(-width);
navigate(roomPath);
startTransition(() => navigate(roomPath));
} else {
settle(0);
}
+3 -7
View File
@@ -413,12 +413,8 @@ export function RoomNavItem({
navigateRoom(room.roomId);
}
} else {
if (isMobile) {
navigate(linkPath);
} else {
// Keep heavy room mounts off the urgent path on desktop.
startTransition(() => navigate(linkPath));
}
// Render the room off the urgent path so the tap doesn't freeze the UI on mount.
startTransition(() => navigate(linkPath));
}
};
@@ -441,7 +437,7 @@ export function RoomNavItem({
if (dx > 10 || dy > 10) return; // was a drag, not a tap
if (room.isCallRoom()) return; // call rooms use onClick
evt.preventDefault();
navigate(linkPath);
startTransition(() => navigate(linkPath));
};
const handleChatButtonClick = (evt: MouseEvent<HTMLButtonElement>) => {
+16 -6
View File
@@ -1,9 +1,10 @@
import { useAtomValue } from 'jotai';
import { useMemo } from 'react';
import { atom, useAtomValue } from 'jotai';
import { matchPath, useLocation, useParams } from 'react-router-dom';
import { getCanonicalAliasRoomId, isRoomAlias } from '$utils/matrix';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { resolveSection } from '$pages/pathUtils';
import { lastVisitedRoomAtom } from '$state/room/lastRoom';
import { lastVisitedRoomSectionAtom } from '$state/room/lastRoom';
export const useSelectedRoom = (): string | undefined => {
const mx = useMatrixClient();
@@ -18,14 +19,23 @@ export const useSelectedRoom = (): string | undefined => {
return roomId;
};
const emptyLastRoomAtom = atom<string | undefined>(undefined);
export const useSelectedOrLastRoom = (): string | undefined => {
const selectedRoomId = useSelectedRoom();
const location = useLocation();
const lastVisitedRoom = useAtomValue(lastVisitedRoomAtom);
if (selectedRoomId) return selectedRoomId;
const section = resolveSection(location.pathname);
const listMatch = section && matchPath({ path: section.listPath, end: true }, location.pathname);
return listMatch ? lastVisitedRoom[section.key] : undefined;
const sectionKey = section?.key;
const sectionAtom = useMemo(
() => (sectionKey ? lastVisitedRoomSectionAtom(sectionKey) : emptyLastRoomAtom),
[sectionKey]
);
const lastRoomId = useAtomValue(sectionAtom);
if (selectedRoomId) return selectedRoomId;
return listMatch ? lastRoomId : undefined;
};
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { rememberTauriSsoNonce } from '$pages/auth/SSOTauri';
import { persistOauthContext } from '$pages/auth/login/oidcLoginUtil';
import { mapDeepLinkToLoginPath } from './TauriDeepLinkBridge';
vi.mock('@tauri-apps/api/core', () => ({
@@ -8,8 +9,18 @@ vi.mock('@tauri-apps/api/core', () => ({
beforeEach(() => {
localStorage.clear();
sessionStorage.clear();
});
const rememberOidcState = (state: string) => {
persistOauthContext(state, {
issuer: 'https://issuer.example',
clientId: 'client',
redirectUri: 'moe.sable.app:/login',
homeserverUrl: 'https://hs.example',
});
};
describe('mapDeepLinkToLoginPath', () => {
it('accepts an SSO callback whose nonce matches the stored one', () => {
rememberTauriSsoNonce('nonce-1');
@@ -33,17 +44,25 @@ describe('mapDeepLinkToLoginPath', () => {
});
it('passes an OIDC callback through unchanged', () => {
rememberOidcState('s1');
const path = mapDeepLinkToLoginPath('moe.sable.app:/login?code=c1&state=s1');
expect(path).toContain('code=c1');
expect(path).toContain('state=s1');
});
it('passes normalized moe.sable.app://login OIDC callback through', () => {
rememberOidcState('s1');
const path = mapDeepLinkToLoginPath('moe.sable.app://login?code=c1&state=s1');
expect(path).toContain('code=c1');
expect(path).toContain('state=s1');
});
it('rejects a stale OIDC callback after its pending context was consumed', () => {
expect(
mapDeepLinkToLoginPath('moe.sable.app:/login?code=already-used&state=old-state')
).toBeUndefined();
});
it('returns undefined for an unrelated url', () => {
expect(mapDeepLinkToLoginPath('https://example.com/whatever')).toBeUndefined();
});
+8 -1
View File
@@ -7,7 +7,7 @@ import {
parseTauriSsoCallback,
takeTauriSsoNonce,
} from '$pages/auth/SSOTauri';
import { getOauthContextServer } from '$pages/auth/login/oidcLoginUtil';
import { getOauthContextServer, hasOauthContext } from '$pages/auth/login/oidcLoginUtil';
import { getLoginPath, withSearchParam } from './pathUtils';
const log = createLogger('TauriDeepLinkBridge');
@@ -27,6 +27,13 @@ export const mapDeepLinkToLoginPath = (rawUrl: string): string | undefined => {
const oidcCallback = parseTauriOidcCallback(rawUrl);
if (oidcCallback) {
// Tauri can return the deep link that originally opened the app again after a WebView
// reload. OAuth callback state is single-use, so ignore callbacks whose pending context
// has already been consumed instead of navigating to a misleading login error.
if (!hasOauthContext(oidcCallback.state)) {
log.warn('Rejected stale OIDC deep-link callback: no pending OAuth context');
return undefined;
}
const loginPath = getLoginPath(getOauthContextServer(oidcCallback.state));
return 'code' in oidcCallback
? withSearchParam(loginPath, {
@@ -75,6 +75,9 @@ export const getOauthContextServer = (state: string): string | undefined => {
}
};
export const hasOauthContext = (state: string): boolean =>
sessionStorage.getItem(oauthContextKey(state)) !== null;
export const startOidcLogin = async (
authMetadata: ValidatedAuthMetadata,
homeserverUrl: string,
+5
View File
@@ -1,3 +1,4 @@
import { atom } from 'jotai';
import {
atomWithLocalStorage,
getLocalStorageItem,
@@ -13,3 +14,7 @@ const lastVisitedRoomBaseAtom = atomWithLocalStorage<Record<string, string>>(
);
export const lastVisitedRoomAtom = lastVisitedRoomBaseAtom;
/** Returns a read-only derived atom for a single section's last-visited room. */
export const lastVisitedRoomSectionAtom = (sectionKey: string) =>
atom((get) => get(lastVisitedRoomAtom)[sectionKey]);