Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(mobile): the chat's composer stays above the keyboard, and its pictures open large

Maurice236b4c34ac55
diff --git a/client/src/hooks/useKeyboardInset.test.ts b/client/src/hooks/useKeyboardInset.test.ts
index 95445a560..7b1e6ae68 100644
--- a/client/src/hooks/useKeyboardInset.test.ts
+++ b/client/src/hooks/useKeyboardInset.test.ts
@@ -1,7 +1,21 @@
-// FE-HOOK-KBINSET-001 to FE-HOOK-KBINSET-004
+// FE-HOOK-KBINSET-001 to FE-HOOK-KBINSET-006
import { act, renderHook } from '@testing-library/react';
-import { useKeyboardInset } from './useKeyboardInset';
+import { _resetNativeKeyboard, useKeyboardInset } from './useKeyboardInset';
+
+const native = vi.hoisted(() => ({
+ app: false,
+ listeners: new Map<string, (info: { keyboardHeight: number }) => void>(),
+}));
+vi.mock('../native/platform', () => ({ isNativeApp: () => native.app }));
+vi.mock('@capacitor/keyboard', () => ({
+ Keyboard: {
+ addListener: (event: string, listener: (info: { keyboardHeight: number }) => void) => {
+ native.listeners.set(event, listener);
+ return Promise.resolve({ remove: () => Promise.resolve() });
+ },
+ },
+}));
class FakeVisualViewport extends EventTarget {
height = 800;
@@ -18,6 +32,9 @@ beforeEach(() => {
afterEach(() => {
vi.unstubAllGlobals();
+ _resetNativeKeyboard();
+ native.app = false;
+ native.listeners.clear();
});
function keyboard(height: number, offsetTop = 0) {
@@ -57,4 +74,18 @@ describe('useKeyboardInset', () => {
const { result } = renderHook(() => useKeyboardInset());
expect(result.current).toBe(0);
});
+
+ it('FE-HOOK-KBINSET-005: in the app, the keyboard the app reports counts, though the viewport did not shrink', () => {
+ native.app = true;
+ const { result } = renderHook(() => useKeyboardInset());
+ act(() => native.listeners.get('keyboardWillShow')?.({ keyboardHeight: 336.4 }));
+ expect(result.current).toBe(336);
+ act(() => native.listeners.get('keyboardWillHide')?.({ keyboardHeight: 0 }));
+ expect(result.current).toBe(0);
+ });
+
+ it('FE-HOOK-KBINSET-006: in a browser nothing listens for the app keyboard', () => {
+ renderHook(() => useKeyboardInset());
+ expect(native.listeners.size).toBe(0);
+ });
});
diff --git a/client/src/hooks/useKeyboardInset.ts b/client/src/hooks/useKeyboardInset.ts
index 42732fde2..e37662d42 100644
--- a/client/src/hooks/useKeyboardInset.ts
+++ b/client/src/hooks/useKeyboardInset.ts
@@ -1,29 +1,65 @@
+import { Keyboard } from '@capacitor/keyboard';
import { useSyncExternalStore } from 'react';
+import { isNativeApp } from '../native/platform';
+
+/**
+ * The keyboard's height as the app reports it (@capacitor/keyboard). The app
+ * resizes the body for the keyboard (KeyboardResize.Body in capacitor.config),
+ * which leaves the visual viewport as it was and does nothing for a screen built
+ * of fixed layers, as the trip shell is, so there only the app can say how much
+ * the keyboard covers.
+ */
+let nativeHeight = 0;
+let followingNative = false;
+const nativeListeners = new Set<() => void>();
+
+function setNativeHeight(height: number): void {
+ nativeHeight = Math.max(0, Math.round(height));
+ for (const listener of nativeListeners) listener();
+}
+
+function followNativeKeyboard(): void {
+ if (followingNative || !isNativeApp()) return;
+ followingNative = true;
+ void Keyboard.addListener('keyboardWillShow', ({ keyboardHeight }) => setNativeHeight(keyboardHeight));
+ void Keyboard.addListener('keyboardWillHide', () => setNativeHeight(0));
+}
/** How far the on-screen keyboard reaches into the layout viewport, in px; 0 when none is up. */
function readInset(): number {
const viewport = window.visualViewport;
- if (!viewport) return 0;
- return Math.max(0, Math.round(window.innerHeight - viewport.height - viewport.offsetTop));
+ const fromViewport = viewport
+ ? Math.max(0, Math.round(window.innerHeight - viewport.height - viewport.offsetTop))
+ : 0;
+ return Math.max(fromViewport, nativeHeight);
}
function subscribe(onChange: () => void): () => void {
+ followNativeKeyboard();
+ nativeListeners.add(onChange);
const viewport = window.visualViewport;
- if (!viewport) return () => undefined;
- viewport.addEventListener('resize', onChange);
- viewport.addEventListener('scroll', onChange);
+ viewport?.addEventListener('resize', onChange);
+ viewport?.addEventListener('scroll', onChange);
return () => {
- viewport.removeEventListener('resize', onChange);
- viewport.removeEventListener('scroll', onChange);
+ nativeListeners.delete(onChange);
+ viewport?.removeEventListener('resize', onChange);
+ viewport?.removeEventListener('scroll', onChange);
};
}
/**
* The height the phone's keyboard covers at the bottom of the screen, read
- * off the visual viewport. A full-screen view pads its bottom by it, so a
- * composer at the foot stays above the keys instead of under them: iOS
- * Safari lays the keyboard over the page without resizing it.
+ * off the visual viewport, and in the app off the keyboard itself. A
+ * full-screen view pads its bottom by it, so a composer at the foot stays above
+ * the keys instead of under them: iOS Safari lays the keyboard over the page
+ * without resizing it, and the app resizes only the body.
*/
export function useKeyboardInset(): number {
return useSyncExternalStore(subscribe, readInset, () => 0);
}
+
+/** Test helper: forgets the keyboard the app reported and lets it be followed afresh. */
+export function _resetNativeKeyboard(): void {
+ nativeHeight = 0;
+ followingNative = false;
+}
diff --git a/client/src/mobile/components/MImageViewer.tsx b/client/src/mobile/components/MImageViewer.tsx
new file mode 100644
index 000000000..b419a76ac
--- /dev/null
+++ b/client/src/mobile/components/MImageViewer.tsx
@@ -0,0 +1,73 @@
+import { X } from 'lucide-react';
+import { useEffect, useState, type ReactElement } from 'react';
+import { createPortal } from 'react-dom';
+import { useTranslation } from '../../i18n';
+import { lockBodyScroll } from '../../utils/bodyScrollLock';
+
+function sheetRoot(): HTMLElement {
+ return document.getElementById('m-sheet-root') ?? document.body;
+}
+
+/**
+ * One image full screen, for a picture shown small in a list (a chat
+ * attachment). A tap on the image zooms in, and the zoomed image pans with the
+ * finger as any scrolled page does; a tap beside it or the X closes the view,
+ * as Escape does with a keyboard. The page's own pinch zoom is off in the app,
+ * so the zoom is the viewer's.
+ */
+export default function MImageViewer({
+ src,
+ alt,
+ onClose,
+}: {
+ src: string;
+ alt: string;
+ onClose: () => void;
+}): ReactElement {
+ const { t } = useTranslation();
+ const [zoomed, setZoomed] = useState(false);
+
+ useEffect(() => lockBodyScroll(), []);
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') onClose();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [onClose]);
+
+ return createPortal(
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-label={alt}
+ className="m-root fixed inset-0 z-[65] bg-black/[.92]"
+ onClick={onClose}
+ >
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label={t('collab.chat.closeImage')}
+ className="absolute end-4 top-[calc(var(--m-safe-top,12px)+4px)] z-10 flex h-10 w-10 items-center justify-center rounded-full bg-white/15 text-white"
+ >
+ <X size={20} strokeWidth={2} />
+ </button>
+ <div
+ className={`h-full w-full ${zoomed ? 'overflow-auto' : 'flex items-center justify-center overflow-hidden p-4'}`}
+ >
+ <img
+ src={src}
+ alt={alt}
+ onClick={(e) => {
+ e.stopPropagation();
+ setZoomed((z) => !z);
+ }}
+ className={
+ zoomed ? 'block w-[250%] max-w-none cursor-zoom-out' : 'max-h-full max-w-full cursor-zoom-in object-contain'
+ }
+ />
+ </div>
+ </div>,
+ sheetRoot()
+ );
+}
diff --git a/client/src/mobile/screens/trip/tabs/MCollabChat.tsx b/client/src/mobile/screens/trip/tabs/MCollabChat.tsx
index 17786fe9a..850dacda1 100644
--- a/client/src/mobile/screens/trip/tabs/MCollabChat.tsx
+++ b/client/src/mobile/screens/trip/tabs/MCollabChat.tsx
@@ -6,6 +6,8 @@ import { edgeFadeClass, useEdgeFade } from '../../../components/useEdgeFade'
import CollabAssistantBadge from '../../../../components/Collab/CollabAssistantBadge'
import { useCollabChatData } from '../../../../components/Collab/useCollabChatData'
import { useAuthStore } from '../../../../store/authStore'
+import { useKeyboardInset } from '../../../../hooks/useKeyboardInset'
+import MImageViewer from '../../../components/MImageViewer'
import { useTranslation } from '../../../../i18n'
import type { TripPlanner } from '../MTripShell'
import { pressHaptic } from '../../../../native/haptics'
@@ -55,10 +57,18 @@ export default function MCollabChat({ planner }: MCollabChatProps) {
const {
messages, loading, hasMore, loadingMore, text, replyTo, setReplyTo, sending, images,
- scrollRef, textareaRef, checkAtBottom, handleLoadMore, handleTextChange, addImageFiles, handleSend,
+ scrollRef, textareaRef, isAtBottom, scrollToBottom, checkAtBottom, handleLoadMore, handleTextChange, addImageFiles, handleSend,
deleteMessage, reactToMessage,
} = useCollabChatData({ tripId, t, toast, toastLoadMoreErrors: true, canSend: canEdit })
+ // The trip shell is a fixed layer the app's keyboard does not shrink, so the
+ // composer is lifted by the keyboard itself; reading the latest message, the
+ // list follows it up.
+ const keyboard = useKeyboardInset()
+ useEffect(() => {
+ if (keyboard > 0 && isAtBottom.current) scrollToBottom()
+ }, [keyboard, isAtBottom, scrollToBottom])
const [popover, setPopover] = useState<{ msg: ChatMessage; x: number; y: number } | null>(null)
+ const [viewing, setViewing] = useState<{ src: string; alt: string } | null>(null)
const [list, setList] = useState<HTMLDivElement | null>(null)
const listFade = useEdgeFade(list, 'y')
const imageInputRef = useRef<HTMLInputElement>(null)
@@ -80,7 +90,10 @@ export default function MCollabChat({ planner }: MCollabChatProps) {
}
return (
- <div className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[calc(var(--m-safe-top,12px)+58px)] wide:mx-auto wide:w-full wide:max-w-[808px] wide:px-6 wide:pb-[calc(var(--bottom-nav-h,0px)+12px)]">
+ <div
+ className="flex h-full flex-col px-4 pb-[var(--bottom-nav-h,84px)] pt-[calc(var(--m-safe-top,12px)+58px)] wide:mx-auto wide:w-full wide:max-w-[808px] wide:px-6 wide:pb-[calc(var(--bottom-nav-h,0px)+12px)]"
+ style={keyboard > 0 ? { paddingBottom: keyboard + 8 } : undefined}
+ >
{loading ? (
<div className="flex flex-1 items-center justify-center">
<Loader2 size={22} strokeWidth={2} className="animate-spin text-m-faint" />
@@ -147,6 +160,7 @@ export default function MCollabChat({ planner }: MCollabChatProps) {
t={t}
onOpenActions={(x, y) => setPopover({ msg, x, y })}
onReactBadgeTap={emoji => canEdit && handleReact(msg.id, emoji)}
+ onOpenImage={setViewing}
/>
)}
</div>
@@ -219,6 +233,7 @@ export default function MCollabChat({ planner }: MCollabChatProps) {
)}
</div>
+ {viewing && <MImageViewer src={viewing.src} alt={viewing.alt} onClose={() => setViewing(null)} />}
{popover && (
<MessageActionsPopover
x={popover.x}
@@ -237,7 +252,7 @@ export default function MCollabChat({ planner }: MCollabChatProps) {
/* ------------------------------------------------------------------ */
-function ChatBubbleRow({ msg, own, showHeader, isLastInGroup, marginTop, is12h, canEdit, t, onOpenActions, onReactBadgeTap }: {
+function ChatBubbleRow({ msg, own, showHeader, isLastInGroup, marginTop, is12h, canEdit, t, onOpenActions, onReactBadgeTap, onOpenImage }: {
msg: ChatMessage
own: boolean
showHeader: boolean
@@ -248,6 +263,7 @@ function ChatBubbleRow({ msg, own, showHeader, isLastInGroup, marginTop, is12h,
t: TripPlanner['t']
onOpenActions: (x: number, y: number) => void
onReactBadgeTap: (emoji: string) => void
+ onOpenImage: (image: { src: string; alt: string }) => void
}) {
const pressTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
const firedRef = useRef(false)
@@ -323,7 +339,7 @@ function ChatBubbleRow({ msg, own, showHeader, isLastInGroup, marginTop, is12h,
</span>
)}
- <button
+ {bubbleShown(msg, bigEmoji, hasReply) && <button
type="button"
aria-label={canEdit ? t('collab.chat.messageOptions') : undefined}
onPointerDown={onPointerDown}
@@ -348,12 +364,18 @@ function ChatBubbleRow({ msg, own, showHeader, isLastInGroup, marginTop, is12h,
</div>
)}
<span dir="auto" className="whitespace-pre-wrap break-words">{msg.text}</span>
- {msg.attachments?.map(att => (
- <img key={att.id} src={att.url} alt={att.original_name || ''} className="mt-2 max-h-52 w-full rounded-[10px] object-cover" />
- ))}
</div>
)}
- </button>
+ </button>}
+
+ {/* Below the bubble rather than in it: the bubble is the long-press target,
+ and an image is tapped to be seen large (MImageViewer). */}
+ <ChatImages
+ attachments={msg.attachments}
+ t={t}
+ press={{ onPointerDown, onPointerMove, clearPress, fired: firedRef }}
+ onOpen={onOpenImage}
+ />
{msg.reactions.length > 0 && (
<div className="mt-[-4px] flex flex-wrap gap-[3px] px-1">
@@ -381,6 +403,50 @@ function ChatBubbleRow({ msg, own, showHeader, isLastInGroup, marginTop, is12h,
)
}
+/** A message has a bubble unless it is a picture alone. */
+function bubbleShown(msg: ChatMessage, bigEmoji: boolean, hasReply: boolean): boolean {
+ return bigEmoji || hasReply || !!msg.text?.trim()
+}
+
+/** A message's pictures, each opened large on a tap; a long press opens the message's actions, as on the bubble. */
+function ChatImages({ attachments, t, press, onOpen }: {
+ attachments: ChatMessage['attachments']
+ t: TripPlanner['t']
+ press: {
+ onPointerDown: (e: React.PointerEvent) => void
+ onPointerMove: (e: React.PointerEvent) => void
+ clearPress: () => void
+ fired: React.RefObject<boolean>
+ }
+ onOpen: (image: { src: string; alt: string }) => void
+}) {
+ if (!attachments?.length) return null
+ return (
+ <>
+ {attachments.map(att => {
+ const alt = att.original_name || t('collab.chat.attachedImage')
+ return (
+ <button
+ key={att.id}
+ type="button"
+ onPointerDown={press.onPointerDown}
+ onPointerMove={press.onPointerMove}
+ onPointerUp={press.clearPress}
+ onPointerCancel={press.clearPress}
+ onClick={() => {
+ if (!press.fired.current) onOpen({ src: att.url, alt })
+ }}
+ aria-label={alt}
+ className="mt-1 block w-full max-w-[260px] overflow-hidden rounded-[12px]"
+ >
+ <img src={att.url} alt="" className="max-h-52 w-full object-cover" />
+ </button>
+ )
+ })}
+ </>
+ )
+}
+
function MessageActionsPopover({ x, y, canDeleteOwn, t, onReact, onReply, onDelete, onClose }: {
x: number
y: number
diff --git a/client/tests/unit/mobile/trip/MCollabChat.test.tsx b/client/tests/unit/mobile/trip/MCollabChat.test.tsx
index e2df1bc41..a5c702969 100644
--- a/client/tests/unit/mobile/trip/MCollabChat.test.tsx
+++ b/client/tests/unit/mobile/trip/MCollabChat.test.tsx
@@ -11,7 +11,7 @@ import { resetAllStores, seedStore } from '../../../helpers/store'
import { server } from '../../../helpers/msw/server'
import { act, fireEvent, render, screen, waitFor } from '../../../helpers/render'
-// FE-MOB-CCHAT-001 to FE-MOB-CCHAT-035
+// FE-MOB-CCHAT-001 to FE-MOB-CCHAT-037
const ME = 7
@@ -567,4 +567,35 @@ describe('MCollabChat', () => {
unmount()
expect(removeListener).toHaveBeenCalledWith(handler)
})
+
+ it('FE-MOB-CCHAT-036: a picture opens large on a tap, zooms on a second, and closes again', async () => {
+ serveMessages([
+ chatMsg(1, {
+ text: 'The beach',
+ attachments: [{ id: 9, url: '/uploads/collab/beach.jpg', original_name: 'beach.jpg', mime_type: 'image/jpeg' }],
+ }),
+ ])
+ await renderChat()
+ fireEvent.click(screen.getByRole('button', { name: 'beach.jpg' }))
+ const viewer = screen.getByRole('dialog', { name: 'beach.jpg' })
+ const image = viewer.querySelector('img') as HTMLImageElement
+ expect(image).toHaveAttribute('src', '/uploads/collab/beach.jpg')
+ fireEvent.click(image)
+ expect(image).toHaveClass('max-w-none')
+ expect(screen.getByRole('dialog', { name: 'beach.jpg' })).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Close image' }))
+ expect(screen.queryByRole('dialog', { name: 'beach.jpg' })).not.toBeInTheDocument()
+ })
+
+ it('FE-MOB-CCHAT-037: a picture sent alone leaves no empty bubble beside it', async () => {
+ serveMessages([
+ chatMsg(1, { text: '', attachments: [{ id: 9, url: '/uploads/collab/a.jpg', original_name: 'a.jpg' }] }),
+ chatMsg(2, { text: 'Nice' }),
+ ])
+ await renderChat()
+ expect(screen.getByRole('button', { name: 'a.jpg' })).toBeInTheDocument()
+ expect(screen.getAllByText('Nice')).toHaveLength(1)
+ expect(document.querySelectorAll('.whitespace-pre-wrap')).toHaveLength(1)
+ })
})