From e1711a68c28daf9e4bdab95cdd51375d4a6a9869 Mon Sep 17 00:00:00 2001 From: timiturn3r Date: Mon, 31 Aug 2026 13:35:39 +0100 Subject: [PATCH] feat(ui): add mobile slide-up sheet for buy and sell modals (#865) - Detect mobile viewport (< 768px) via useIsMobile and render buy/sell modals as BottomSheet - Provide slide-up CSS transform transition and drag handle for swipe-down to dismiss - Ensure max height leaves at least 80px visible at the top of the viewport on mobile - Continue rendering standard centered Dialog on desktop viewports (>= 768px) - Add comprehensive integration and unit tests for mobile BottomSheet --- src/components/common/TradeDialog.tsx | 341 +++++++++++------- .../TradeDialog.mobileBottomSheet.test.tsx | 265 ++++++++++++++ src/hooks/useIsMobile.ts | 3 +- 3 files changed, 472 insertions(+), 137 deletions(-) create mode 100644 src/components/common/__tests__/TradeDialog.mobileBottomSheet.test.tsx diff --git a/src/components/common/TradeDialog.tsx b/src/components/common/TradeDialog.tsx index ec805b98..9497313f 100644 --- a/src/components/common/TradeDialog.tsx +++ b/src/components/common/TradeDialog.tsx @@ -9,6 +9,14 @@ import { DialogHeader, DialogTitle, } from '@/components/ui/dialog'; +import { + BottomSheet, + BottomSheetContent, + BottomSheetDescription, + BottomSheetHandle, + BottomSheetTitle, +} from '@/components/ui/bottom-sheet'; +import { useIsMobile } from '@/hooks/useIsMobile'; import { cn } from '@/lib/utils'; import { formatNumber } from '@/utils/numberFormat.utils'; import { @@ -258,6 +266,201 @@ const TradeDialog: React.FC = ({ } }, [open, side, estimatedProceedsStroops, creatorName, parsedAmount]); + const isMobile = useIsMobile(); + + const bodyContent = ( + <> + {side === 'buy' && keyPriceStroops != null && ( +

+ Unit price:{' '} + + {formatDisplayKeyPrice(keyPriceStroops)} + +

+ )} + +
+
Amount
+ { + setAmountText(event.target.value); + setTouched(true); + }} + onBlur={handleBlur} + disabled={isSubmitting} + className={cn( + 'w-full rounded-xl border bg-white/[0.04] px-3 py-2 text-white outline-none transition-colors', + 'border-white/10 focus:border-amber-500/50 focus:ring-2 focus:ring-amber-500/15', + showError ? 'border-red-500/60' : '' + )} + aria-label="Trade amount" + aria-describedby={ + showError ? 'trade-amount-error' : undefined + } + aria-invalid={showError || undefined} + data-focus-order="1" + data-testid="trade-dialog-amount" + /> + {showError && ( + + )} +
+ + Holdings: {formatNumber(availableHoldings)} keys + + {side === 'sell' && + availableHoldings > 0 && + Number.isFinite(parsedAmount) && + parsedAmount > 0 && ( + availableHoldings + ? 'negative' + : 'neutral' + } + /> + )} +
+ {side === 'buy' && ( + + )} + {side === 'buy' && amountValid && ( + { + setPreviewError(null); + setPreviewLoading(true); + }} + /> + )} + {side === 'buy' && estimatedTotalStroops != null && ( +
+ Estimated total (approximate):{' '} + + {formatDisplayKeyPrice(estimatedTotalStroops)} + +
+ )} + {side === 'sell' && ( +
+ {estimatedProceedsStroops != null ? ( + <> + Estimated proceeds (approximate):{' '} + + {formatDisplayKeyPrice(estimatedProceedsStroops)} + + + ) : ( + <>Estimated proceeds unavailable + )} +
+ )} +
+ + ); + + const actionButtons = ( + <> + + + + ); + + if (isMobile) { + return ( + !isSubmitting && onOpenChange(next)} + > + { + event.preventDefault(); + amountInputRef.current?.focus(); + }} + onCloseAutoFocus={event => { + event.preventDefault(); + triggerElementRef.current?.focus(); + }} + onEscapeKeyDown={event => { + if (isSubmitting) event.preventDefault(); + }} + onInteractOutside={event => { + if (isSubmitting) event.preventDefault(); + }} + > + +
+ + {title} + + + {side === 'buy' + ? `Purchase creator keys for ${creatorName}.` + : `Sell creator keys for ${creatorName}.`} + +
+ + {bodyContent} + +
+ {actionButtons} +
+
+
+ ); + } + return ( = ({ - {side === 'buy' && keyPriceStroops != null && ( -

- Unit price:{' '} - - {formatDisplayKeyPrice(keyPriceStroops)} - -

- )} - -
-
Amount
- { - setAmountText(event.target.value); - setTouched(true); - }} - onBlur={handleBlur} - disabled={isSubmitting} - className={cn( - 'w-full rounded-xl border bg-white/[0.04] px-3 py-2 text-white outline-none transition-colors', - 'border-white/10 focus:border-amber-500/50 focus:ring-2 focus:ring-amber-500/15', - showError ? 'border-red-500/60' : '' - )} - aria-label="Trade amount" - aria-describedby={ - showError ? 'trade-amount-error' : undefined - } - aria-invalid={showError || undefined} - data-focus-order="1" - data-testid="trade-dialog-amount" - /> - {showError && ( - - )} -
- - Holdings: {formatNumber(availableHoldings)} keys - - {side === 'sell' && - availableHoldings > 0 && - Number.isFinite(parsedAmount) && - parsedAmount > 0 && ( - availableHoldings - ? 'negative' - : 'neutral' - } - /> - )} -
- {side === 'buy' && ( - - )} - {side === 'buy' && amountValid && ( - { - setPreviewError(null); - setPreviewLoading(true); - }} - /> - )} - {side === 'buy' && estimatedTotalStroops != null && ( -
- Estimated total (approximate):{' '} - - {formatDisplayKeyPrice(estimatedTotalStroops)} - -
- )} - {side === 'sell' && ( -
- {estimatedProceedsStroops != null ? ( - <> - Estimated proceeds (approximate):{' '} - - {formatDisplayKeyPrice(estimatedProceedsStroops)} - - - ) : ( - <>Estimated proceeds unavailable - )} -
- )} -
+ {bodyContent} {/* * Focus order is intentional: amount input → Cancel → Confirm. @@ -408,36 +506,7 @@ const TradeDialog: React.FC = ({ * `__tests__/TradeDialog.focusOrder.test.tsx` guards this. */} - - + {actionButtons}
diff --git a/src/components/common/__tests__/TradeDialog.mobileBottomSheet.test.tsx b/src/components/common/__tests__/TradeDialog.mobileBottomSheet.test.tsx new file mode 100644 index 00000000..1b535b25 --- /dev/null +++ b/src/components/common/__tests__/TradeDialog.mobileBottomSheet.test.tsx @@ -0,0 +1,265 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, act } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { useState } from 'react'; +import TradeDialog, { type TradeDialogProps } from '@/components/common/TradeDialog'; + +// --------------------------------------------------------------------------- +// Viewport / matchMedia mock helpers +// --------------------------------------------------------------------------- + +type MQCallback = (event: Pick) => void; + +interface MockMQL { + matches: boolean; + addEventListener: (event: string, cb: MQCallback) => void; + removeEventListener: (event: string, cb: MQCallback) => void; + _fire: (newMatches: boolean) => void; +} + +function mockViewportWidth(widthPx: number): MockMQL { + const matches = widthPx < 768; + const listeners: MQCallback[] = []; + const mql: MockMQL = { + matches, + addEventListener: (_event: string, cb: MQCallback) => listeners.push(cb), + removeEventListener: (_event: string, cb: MQCallback) => { + const idx = listeners.indexOf(cb); + if (idx !== -1) listeners.splice(idx, 1); + }, + _fire: (newMatches: boolean) => { + mql.matches = newMatches; + listeners.forEach(cb => cb({ matches: newMatches })); + }, + }; + + Object.defineProperty(window, 'matchMedia', { + writable: true, + value: vi.fn().mockReturnValue(mql), + }); + + return mql; +} + +function TestTradeDialog(props: Partial = {}) { + const [open, setOpen] = useState(props.open ?? true); + return ( + + ); +} + +describe('TradeDialog mobile slide-up sheet (#865)', () => { + let mql: MockMQL; + + beforeEach(() => { + mql = mockViewportWidth(375); // mobile iPhone width by default (< 768px) + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe('Viewport-responsive rendering', () => { + it('renders as a bottom sheet with drag handle on mobile viewports (< 768px)', () => { + mockViewportWidth(500); + render(); + + // Bottom sheet content slot is rendered + const sheet = screen.getByTestId('bottom-sheet-handle'); + expect(sheet).toBeInTheDocument(); + + const content = document.querySelector('[data-slot="bottom-sheet-content"]'); + expect(content).toBeInTheDocument(); + expect(document.querySelector('[data-slot="dialog-content"]')).not.toBeInTheDocument(); + + // Sheet title and description + expect(screen.getByText('Buy keys')).toBeInTheDocument(); + expect(screen.getByText('Purchase creator keys for Alice.')).toBeInTheDocument(); + }); + + it('renders as a centered modal without drag handle on desktop viewports (>= 768px)', () => { + mockViewportWidth(1024); + render(); + + // Centered dialog content slot is rendered + expect(document.querySelector('[data-slot="dialog-content"]')).toBeInTheDocument(); + expect(document.querySelector('[data-slot="bottom-sheet-content"]')).not.toBeInTheDocument(); + expect(screen.queryByTestId('bottom-sheet-handle')).not.toBeInTheDocument(); + + // Dialog title and description + expect(screen.getByText('Buy keys')).toBeInTheDocument(); + expect(screen.getByText('Purchase creator keys for Alice.')).toBeInTheDocument(); + }); + + it('switches between bottom sheet and centered modal dynamically when viewport changes', () => { + render(); + + // Initially mobile: bottom sheet + expect(document.querySelector('[data-slot="bottom-sheet-content"]')).toBeInTheDocument(); + expect(screen.getByTestId('bottom-sheet-handle')).toBeInTheDocument(); + + // Resize to desktop + act(() => { + mql._fire(false); + }); + + expect(document.querySelector('[data-slot="dialog-content"]')).toBeInTheDocument(); + expect(screen.queryByTestId('bottom-sheet-handle')).not.toBeInTheDocument(); + + // Resize back to mobile + act(() => { + mql._fire(true); + }); + + expect(document.querySelector('[data-slot="bottom-sheet-content"]')).toBeInTheDocument(); + expect(screen.getByTestId('bottom-sheet-handle')).toBeInTheDocument(); + }); + }); + + describe('Height constraint & top margin', () => { + it('enforces maximum height leaving at least 80px of viewport visible at top on mobile', () => { + render(); + + const content = document.querySelector('[data-slot="bottom-sheet-content"]'); + expect(content).toHaveClass('max-h-[calc(100vh-80px)]'); + expect(content).toHaveClass('overflow-y-auto'); + }); + }); + + describe('Slide-up animation', () => { + it('applies slide-up CSS animation classes on the bottom sheet content', () => { + render(); + + const content = document.querySelector('[data-slot="bottom-sheet-content"]'); + expect(content).toHaveClass('data-[state=open]:slide-in-from-bottom-8'); + expect(content).toHaveClass('data-[state=closed]:slide-out-to-bottom-8'); + }); + }); + + describe('Swipe-down to dismiss gesture', () => { + it('dismisses the sheet when dragging downward past the threshold', () => { + const onOpenChange = vi.fn(); + render(); + + const handle = screen.getByTestId('bottom-sheet-handle'); + + fireEvent.pointerDown(handle, { pointerId: 1, clientY: 100, button: 0 }); + fireEvent.pointerMove(handle, { pointerId: 1, clientY: 220 }); // 120px > 96px threshold + fireEvent.pointerUp(handle, { pointerId: 1, clientY: 220 }); + + expect(onOpenChange).toHaveBeenCalledWith(false); + }); + + it('does not dismiss when dragging below the threshold', () => { + const onOpenChange = vi.fn(); + render(); + + const handle = screen.getByTestId('bottom-sheet-handle'); + + fireEvent.pointerDown(handle, { pointerId: 1, clientY: 100, button: 0 }); + fireEvent.pointerMove(handle, { pointerId: 1, clientY: 130 }); // 30px < 96px threshold + fireEvent.pointerUp(handle, { pointerId: 1, clientY: 130 }); + + expect(onOpenChange).not.toHaveBeenCalledWith(false); + }); + + it('does not dismiss on upward drag', () => { + const onOpenChange = vi.fn(); + render(); + + const handle = screen.getByTestId('bottom-sheet-handle'); + + fireEvent.pointerDown(handle, { pointerId: 1, clientY: 200, button: 0 }); + fireEvent.pointerMove(handle, { pointerId: 1, clientY: 100 }); // -100px upward + fireEvent.pointerUp(handle, { pointerId: 1, clientY: 100 }); + + expect(onOpenChange).not.toHaveBeenCalledWith(false); + }); + }); + + describe('Sell modal variant on mobile', () => { + it('renders the sell variant as a bottom sheet with correct titles and sell details', () => { + render( + + ); + + expect(document.querySelector('[data-slot="bottom-sheet-content"]')).toBeInTheDocument(); + expect(screen.getByTestId('bottom-sheet-handle')).toBeInTheDocument(); + expect(screen.getByText('Sell keys')).toBeInTheDocument(); + expect(screen.getByText('Sell creator keys for Bob.')).toBeInTheDocument(); + expect(screen.getByTestId('trade-dialog-confirm')).toHaveTextContent('Confirm sell'); + }); + }); + + describe('Submitting state on mobile', () => { + it('disables drag-to-dismiss and hides close button when isSubmitting is true', () => { + const onOpenChange = vi.fn(); + render(); + + // Close button is hidden + expect(screen.queryByRole('button', { name: 'Close panel' })).not.toBeInTheDocument(); + + // Dragging handle does not dismiss + const handle = screen.getByTestId('bottom-sheet-handle'); + fireEvent.pointerDown(handle, { pointerId: 1, clientY: 100, button: 0 }); + fireEvent.pointerMove(handle, { pointerId: 1, clientY: 400 }); + fireEvent.pointerUp(handle, { pointerId: 1, clientY: 400 }); + + expect(onOpenChange).not.toHaveBeenCalledWith(false); + }); + }); + + describe('Form interactions & accessibility on mobile', () => { + it('allows changing amount and confirms trade on mobile', async () => { + const user = userEvent.setup(); + const onConfirm = vi.fn(); + render(); + + const input = screen.getByTestId('trade-dialog-amount'); + await user.clear(input); + await user.type(input, '3'); + + const confirmBtn = screen.getByTestId('trade-dialog-confirm'); + await user.click(confirmBtn); + + expect(onConfirm).toHaveBeenCalledWith(3, null); + }); + + it('allows cancelling trade via cancel button on mobile', async () => { + const user = userEvent.setup(); + const onOpenChange = vi.fn(); + render(); + + const cancelBtn = screen.getByTestId('trade-dialog-cancel'); + await user.click(cancelBtn); + + expect(onOpenChange).toHaveBeenCalledWith(false); + }); + + it('allows closing via the close button on mobile', () => { + const onOpenChange = vi.fn(); + render(); + + const closeBtn = screen.getByRole('button', { name: 'Close panel' }); + fireEvent.click(closeBtn); + + expect(onOpenChange).toHaveBeenCalledWith(false); + }); + }); +}); diff --git a/src/hooks/useIsMobile.ts b/src/hooks/useIsMobile.ts index d30ac864..77c71c42 100644 --- a/src/hooks/useIsMobile.ts +++ b/src/hooks/useIsMobile.ts @@ -10,11 +10,12 @@ const MOBILE_MEDIA_QUERY = `(max-width: ${MOBILE_BREAKPOINT_PX - 1}px)`; */ export function useIsMobile(): boolean { const [isMobile, setIsMobile] = useState(() => { - if (typeof window === 'undefined') return false; + if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false; return window.matchMedia(MOBILE_MEDIA_QUERY).matches; }); useEffect(() => { + if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return; const media = window.matchMedia(MOBILE_MEDIA_QUERY); const onChange = (event: MediaQueryListEvent) => { setIsMobile(event.matches);