diff --git a/src/App.tsx b/src/App.tsx index dc0862639..b5fb00182 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -148,65 +148,64 @@ function InnerApp() { - - - - - - - - - - {/* LabelDefsProvider MUST come before ModerationOptsProvider */} - - - - - - - - - - - - - - - + + + + + + + + + + + {/* LabelDefsProvider MUST come before ModerationOptsProvider */} + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/App.web.tsx b/src/App.web.tsx index f6d42888b..b75e4b8c8 100644 --- a/src/App.web.tsx +++ b/src/App.web.tsx @@ -162,7 +162,6 @@ function InnerApp() { - @@ -188,6 +187,7 @@ function InnerApp() { + diff --git a/src/components/Dialog/context.ts b/src/components/Dialog/context.ts index 020925149..4ebe42557 100644 --- a/src/components/Dialog/context.ts +++ b/src/components/Dialog/context.ts @@ -24,6 +24,7 @@ export const Context = createContext({ isNativePopover: false, nativeSnapPoint: BottomSheetSnapPoint.Hidden, disableDrag: false, + preventDismiss: false, setDisableDrag: () => {}, isWithinDialog: false, isHeightConstrained: false, diff --git a/src/components/Dialog/dismissal.web.test.tsx b/src/components/Dialog/dismissal.web.test.tsx new file mode 100644 index 000000000..9d6c7d9b6 --- /dev/null +++ b/src/components/Dialog/dismissal.web.test.tsx @@ -0,0 +1,161 @@ +import {act, createRef} from 'react' +import {fireEvent, render, screen} from '@testing-library/react-native' + +import {Close, Inner, Outer} from '#/components/Dialog/index.web' +import {type DialogControlProps} from '#/components/Dialog/types' + +let mockOnDismiss: (() => void) | undefined + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({_: (value: {message: string}) => value.message}), +})) +jest.mock('#/state/dialogs', () => ({ + useDialogStateControlContext: () => ({setDialogIsOpen: jest.fn()}), +})) +jest.mock('#/state/a11y', () => ({ + useA11y: () => ({reduceMotionEnabled: true}), +})) +jest.mock('#/alf', () => ({ + atoms: new Proxy({}, {get: () => ({})}), + flatten: (style: unknown) => style, + web: () => ({}), + useBreakpoints: () => ({gtMobile: true}), + useTheme: () => ({ + atoms: {bg: {}}, + palette: {contrast_200: '#000', black: '#000'}, + name: 'light', + }), +})) +jest.mock('#/logger', () => ({logger: {error: jest.fn()}})) +jest.mock('#/components/Portal', () => ({ + Portal: ({children}: {children: React.ReactNode}) => <>{children}, +})) +jest.mock('react-remove-scroll-bar', () => ({RemoveScrollBar: () => null})) +jest.mock('@radix-ui/react-focus-guards', () => ({useFocusGuards: () => {}})) +jest.mock('@radix-ui/react-focus-scope', () => ({ + FocusScope: ({children}: {children: React.ReactNode}) => <>{children}, +})) +jest.mock('@radix-ui/react-dismissable-layer', () => ({ + DismissableLayer: ({ + children, + onDismiss, + }: { + children: React.ReactNode + onDismiss: () => void + }) => { + mockOnDismiss = onDismiss + return <>{children} + }, +})) +jest.mock('#/components/icons/Times', () => ({ + TimesLarge_Stroke2_Corner0_Rounded: () => null, +})) +jest.mock('#/components/Button', () => { + const {Pressable} = require('react-native') as typeof import('react-native') + return { + Button: ({ + onPress, + disabled, + children, + }: { + onPress?: () => void + disabled?: boolean + children?: React.ReactNode + }) => ( + + {children} + + ), + ButtonIcon: () => null, + } +}) + +function makeControl() { + const ref = createRef() + const control = { + id: 'test', + ref, + open: () => ref.current?.open(), + close: (cb?: () => void) => ref.current?.close(cb), + } as unknown as DialogControlProps + return control +} + +function renderDialog({ + preventDismiss, + onBackgroundPress, +}: { + preventDismiss?: boolean + onBackgroundPress?: () => void +}) { + const control = makeControl() + const ui = (prevent?: boolean) => ( + + + + + + ) + const utils = render(ui(preventDismiss)) + act(() => control.open()) + return {control, rerender: (prevent?: boolean) => utils.rerender(ui(prevent))} +} + +const isOpen = () => screen.queryByLabelText('Test dialog') !== null +const isCloseDisabled = () => { + const state = screen.getByTestId('dialogClose').props.accessibilityState as + {disabled?: boolean} | undefined + return !!state?.disabled +} + +describe('Dialog preventDismiss (web)', () => { + beforeEach(() => { + jest.useFakeTimers() + mockOnDismiss = undefined + }) + afterEach(() => { + jest.useRealTimers() + }) + + it('blocks backdrop, Escape/outside dismissal and the close button while locked', () => { + const onBackgroundPress = jest.fn() + renderDialog({preventDismiss: true, onBackgroundPress}) + expect(isOpen()).toBe(true) + + fireEvent.press(screen.getByLabelText('Close active dialog')) + act(() => mockOnDismiss?.()) + fireEvent.press(screen.getByTestId('dialogClose')) + + expect(onBackgroundPress).not.toHaveBeenCalled() + expect(isCloseDisabled()).toBe(true) + expect(isOpen()).toBe(true) + }) + + it('still closes programmatically, running the callback, while locked', () => { + const {control} = renderDialog({preventDismiss: true}) + const callback = jest.fn() + + act(() => control.close(callback)) + expect(isOpen()).toBe(false) + act(() => { + jest.runAllTimers() + }) + expect(callback).toHaveBeenCalledTimes(1) + }) + + it('unlocks when preventDismiss goes back to false', () => { + const {rerender} = renderDialog({preventDismiss: true}) + expect(isCloseDisabled()).toBe(true) + rerender(false) + expect(isCloseDisabled()).toBe(false) + act(() => mockOnDismiss?.()) + expect(isOpen()).toBe(false) + }) +}) diff --git a/src/components/Dialog/index.tsx b/src/components/Dialog/index.tsx index 34da5274c..908df60b0 100644 --- a/src/components/Dialog/index.tsx +++ b/src/components/Dialog/index.tsx @@ -83,6 +83,7 @@ export function Outer({ control, onOpen, onClose, + preventDismiss = false, nativeOptions, testID, }: React.PropsWithChildren) { @@ -112,6 +113,12 @@ export function Outer({ popover: nativeOptions?.popover, }) + /* + * Only user dismissal paths are blocked natively; the imperative `close` + * below still dismisses the sheet. + */ + const shouldPreventDismiss = preventDismiss || !!nativeOptions?.preventDismiss + const callQueuedCallbacks = useCallback(() => { for (const cb of closeCallbacks.current) { try { @@ -264,6 +271,7 @@ export function Outer({ isNativePopover: IS_IOS && presentation?.isPopover === true, nativeSnapPoint: snapPoint, disableDrag, + preventDismiss: shouldPreventDismiss, setDisableDrag, isWithinDialog: true, isHeightConstrained, @@ -275,6 +283,7 @@ export function Outer({ presentation, snapPoint, disableDrag, + shouldPreventDismiss, setDisableDrag, isHeightConstrained, shouldMeasureContentHeight, @@ -292,6 +301,7 @@ export function Outer({ backgroundColor={t.atoms.bg.backgroundColor} colorScheme={t.scheme} {...nativeOptions} + preventDismiss={shouldPreventDismiss} sourceViewTag={sourceViewTag ?? nativeOptions?.sourceViewTag} onSnapPointChange={onSnapPointChange} onStateChange={onStateChange} diff --git a/src/components/Dialog/index.web.tsx b/src/components/Dialog/index.web.tsx index fdae059c6..3ef437438 100644 --- a/src/components/Dialog/index.web.tsx +++ b/src/components/Dialog/index.web.tsx @@ -57,6 +57,7 @@ export function Outer({ control, onOpen, onClose, + preventDismiss = false, webOptions, }: React.PropsWithChildren) { const {_} = useLingui() @@ -113,9 +114,10 @@ export function Outer({ const startTarget = pressStartTarget.current pressStartTarget.current = null if (startTarget && startTarget !== e.target) return + if (preventDismiss) return webOptions?.onBackgroundPress ? webOptions.onBackgroundPress(e) : close() }, - [webOptions, close], + [webOptions, close, preventDismiss], ) useImperativeHandle( @@ -135,13 +137,14 @@ export function Outer({ isNativePopover: false, nativeSnapPoint: 0, disableDrag: false, + preventDismiss, setDisableDrag: () => {}, isWithinDialog: true, isHeightConstrained: false, shouldMeasureContentHeight: false, setDesiredContentHeight: () => {}, }), - [close], + [close, preventDismiss], ) return ( @@ -208,7 +211,7 @@ export function Inner({ contentContainerStyle, }: DialogInnerProps) { const t = useTheme() - const {close} = useContext(Context) + const {close, preventDismiss} = useContext(Context) const {gtMobile} = useBreakpoints() const {reduceMotionEnabled} = useA11y() FocusGuards.useFocusGuards() @@ -244,7 +247,9 @@ export function Inner({ { + if (!preventDismiss) close() + }} style={{height: '100%', display: 'flex', flexDirection: 'column'}}> {header} @@ -352,7 +357,7 @@ export function FlatListFooter({ export function Close() { const {_} = useLingui() - const {close} = useContext(Context) + const {close, preventDismiss} = useContext(Context) return ( close()} + disabled={preventDismiss} label={_(msg`Close active dialog`)}> diff --git a/src/components/Dialog/types.ts b/src/components/Dialog/types.ts index f843d6f0f..4ef1caf3d 100644 --- a/src/components/Dialog/types.ts +++ b/src/components/Dialog/types.ts @@ -47,6 +47,11 @@ export type DialogContextProps = { isNativePopover: boolean nativeSnapPoint: BottomSheetSnapPoint disableDrag: boolean + /** + * Whether user dismissal (backdrop, swipe, back, Escape, close button) is + * currently prevented. `close` itself is never blocked. + */ + preventDismiss: boolean setDisableDrag: React.Dispatch> // in the event that the hook is used outside of a dialog isWithinDialog: boolean @@ -77,6 +82,15 @@ export type DialogOuterProps = { control: DialogControlProps onOpen?: () => void onClose?: () => void + /** + * Prevents the user from dismissing the dialog (backdrop press, swipe, back + * button, Escape, and the close button), e.g. while a request is pending. + * Does not block `control.close()`, so the pending operation can still close + * the dialog itself when it finishes. + * + * @default false + */ + preventDismiss?: boolean nativeOptions?: Omit webOptions?: { alignCenter?: boolean diff --git a/src/screens/Settings/components/ChangePasswordDialog.tsx b/src/screens/Settings/components/ChangePasswordDialog.tsx index 0d2062586..2aa0abe6f 100644 --- a/src/screens/Settings/components/ChangePasswordDialog.tsx +++ b/src/screens/Settings/components/ChangePasswordDialog.tsx @@ -7,7 +7,7 @@ import {cleanError, isNetworkError} from '#/lib/strings/errors' import {checkAndFormatResetCode} from '#/lib/strings/password' import {matchXrpcError} from '#/lib/xrpc-error' import {logger} from '#/logger' -import {usePdsClient, useSession} from '#/state/session' +import {usePdsClient, useSession, useSessionApi} from '#/state/session' import {ErrorMessage} from '#/view/com/util/error/ErrorMessage' import {android, atoms as a, web} from '#/alf' import {Button, ButtonIcon, ButtonText} from '#/components/Button' @@ -16,6 +16,7 @@ import {TokenField} from '#/components/dialogs/EmailDialog/components/TokenField import {PasswordField} from '#/components/forms/PasswordField' import * as TextField from '#/components/forms/TextField' import {Loader} from '#/components/Loader' +import * as Toast from '#/components/Toast' import {Text} from '#/components/Typography' import {IS_NATIVE} from '#/env' import {com} from '#/lexicons' @@ -23,7 +24,6 @@ import {com} from '#/lexicons' enum Stages { RequestCode = 'RequestCode', ChangePassword = 'ChangePassword', - Done = 'Done', } export function ChangePasswordDialog({ @@ -32,25 +32,33 @@ export function ChangePasswordDialog({ control: Dialog.DialogControlProps }) { const {height} = useWindowDimensions() + const [isProcessing, setIsProcessing] = useState(false) return ( - + ) } -function Inner() { +function Inner({ + isProcessing, + setIsProcessing, +}: { + isProcessing: boolean + setIsProcessing: (isProcessing: boolean) => void +}) { const {t: l} = useLingui() const {currentAccount} = useSession() const client = usePdsClient() + const {logoutCurrentAccount} = useSessionApi() const control = Dialog.useDialogContext() const [stage, setStage] = useState(Stages.RequestCode) - const [isProcessing, setIsProcessing] = useState(false) const [resetCode, setResetCode] = useState('') const [newPassword, setNewPassword] = useState('') const [error, setError] = useState('') @@ -64,10 +72,6 @@ function Inner() { title: l`Enter code`, message: l`Please enter the code you received and the new password you would like to use.`, }, - Done: { - title: l`Password changed`, - message: l`Your password has been changed successfully! Please use your new password when you sign in to Bluesky from now on.`, - }, } const onRequestCode = async () => { @@ -125,7 +129,22 @@ function Inner() { token: formattedCode, password: newPassword, }) - setStage(Stages.Done) + setResetCode('') + setNewPassword('') + /* + * Resetting the password revokes every refresh token for this account, + * so the current session can no longer be refreshed. Sign out and ask + * the user to sign in again with the new password. Keep processing + * until the dialog has closed to prevent a second submission. + */ + control.close(() => { + logoutCurrentAccount('Settings') + Toast.show( + l`Password successfully reset. Please sign in with your new password.`, + {type: 'success'}, + ) + }) + return } catch (error) { const e = error as Error if (isNetworkError(e)) { @@ -162,6 +181,12 @@ function Inner() { {uiStrings[stage].message} + + + Changing your password will sign you out. You’ll need to sign in + again with your new password. + + {stage === Stages.ChangePassword && ( @@ -225,7 +250,7 @@ function Inner() { )} - ) : stage === Stages.ChangePassword ? ( + ) : ( <> - ) : stage === Stages.Done ? ( - - ) : null} + )} diff --git a/src/screens/Settings/components/__tests__/ChangePasswordDialog.test.tsx b/src/screens/Settings/components/__tests__/ChangePasswordDialog.test.tsx new file mode 100644 index 000000000..9b9b9e824 --- /dev/null +++ b/src/screens/Settings/components/__tests__/ChangePasswordDialog.test.tsx @@ -0,0 +1,233 @@ +import {act} from 'react' +import {fireEvent, render, screen} from '@testing-library/react-native' + +import {ChangePasswordDialog} from '../ChangePasswordDialog' + +const mockCall = jest.fn() +const mockClose = jest.fn void)?]>() + +jest.mock('@lingui/react', () => ({ + useLingui: () => ({_: (value: {message: string}) => value.message}), + Trans: ({message}: {message?: string}) => message ?? null, +})) +jest.mock('#/state/session', () => ({ + usePdsClient: () => ({call: mockCall}), + useSession: () => ({currentAccount: {email: 'alice@example.com'}}), + useSessionApi: () => ({logoutCurrentAccount: jest.fn()}), +})) +jest.mock('#/logger', () => ({logger: {error: jest.fn()}})) +jest.mock('#/alf', () => ({ + atoms: new Proxy({}, {get: () => ({})}), + android: () => ({}), + web: () => ({}), +})) +jest.mock('#/components/Dialog', () => ({ + Outer: ({ + children, + preventDismiss, + }: { + children: React.ReactNode + preventDismiss?: boolean + }) => { + const {View} = require('react-native') as typeof import('react-native') + return ( + + {children} + + ) + }, + Handle: () => null, + ScrollableInner: ({children}: {children: React.ReactNode}) => <>{children}, + Close: () => null, + useDialogContext: () => ({close: mockClose}), +})) +jest.mock('#/components/Button', () => { + const {Pressable, Text} = + require('react-native') as typeof import('react-native') + return { + Button: ({ + label, + onPress, + disabled, + children, + }: { + label: string + onPress?: () => void + disabled?: boolean + children: React.ReactNode + }) => ( + + {children} + + ), + ButtonText: ({children}: {children: React.ReactNode}) => ( + {children} + ), + ButtonIcon: () => null, + } +}) +jest.mock('#/components/Loader', () => ({Loader: () => null})) +jest.mock('#/components/Toast', () => ({show: jest.fn()})) +jest.mock('#/components/Typography', () => { + const {Text} = require('react-native') as typeof import('react-native') + return {Text} +}) +jest.mock('#/view/com/util/error/ErrorMessage', () => { + const {Text} = require('react-native') as typeof import('react-native') + return { + ErrorMessage: ({message}: {message: string}) => {message}, + } +}) +jest.mock('#/env', () => ({IS_NATIVE: false})) +jest.mock('#/components/forms/TextField', () => ({ + LabelText: ({children}: {children: React.ReactNode}) => <>{children}, +})) +jest.mock('#/components/dialogs/EmailDialog/components/TokenField', () => { + const {TextInput} = require('react-native') as typeof import('react-native') + return { + TokenField: (props: React.ComponentProps) => ( + + ), + } +}) +jest.mock('#/components/forms/PasswordField', () => { + const {TextInput} = require('react-native') as typeof import('react-native') + return { + PasswordField: ({ + label, + ...rest + }: React.ComponentProps & {label: string}) => ( + + ), + } +}) + +const control = {open: jest.fn(), close: jest.fn()} + +function renderDialog() { + render( + ['control'] + } + />, + ) +} + +function enterCodeStage() { + fireEvent.press(screen.getByLabelText('Already have a code?')) +} + +async function submit() { + await act(async () => { + fireEvent.press(screen.getByLabelText('Change password')) + await Promise.resolve() + }) +} + +function deferred() { + let resolve!: (value: unknown) => void + let reject!: (reason: unknown) => void + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return {promise, resolve, reject} +} + +function isDismissPrevented() { + const state = screen.getByTestId('dialogOuter').props.accessibilityState as { + busy: boolean + } + return state.busy +} + +function isDisabled(label: string) { + const state = screen.getByLabelText(label).props.accessibilityState as + {disabled?: boolean} | undefined + return !!state?.disabled +} + +function fillCodeStage() { + enterCodeStage() + fireEvent.changeText(screen.getByTestId('resetCode'), 'abcde23456') + fireEvent.changeText(screen.getByTestId('newPassword'), 'new-password') +} + +describe('ChangePasswordDialog', () => { + beforeEach(() => { + jest.clearAllMocks() + mockCall.mockResolvedValue({}) + }) + + it('locks dismissal while a reset is pending, until the programmatic close', async () => { + const request = deferred() + mockCall.mockReturnValueOnce(request.promise) + renderDialog() + expect(isDismissPrevented()).toBe(false) + fillCodeStage() + await submit() + + expect(isDismissPrevented()).toBe(true) + expect(isDisabled('Change password')).toBe(true) + expect(isDisabled('Back')).toBe(true) + expect(mockClose).not.toHaveBeenCalled() + + await act(async () => { + request.resolve({}) + await request.promise + }) + + // Still locked for the user, but the programmatic close is requested. + expect(isDismissPrevented()).toBe(true) + expect(mockClose).toHaveBeenCalledTimes(1) + expect(mockClose).toHaveBeenCalledWith(expect.any(Function)) + }) + + it('restores dismissal when a reset fails, and a retry can succeed', async () => { + const request = deferred() + mockCall.mockReturnValueOnce(request.promise) + renderDialog() + fillCodeStage() + await submit() + expect(isDismissPrevented()).toBe(true) + + await act(async () => { + request.reject(new Error('Network request failed')) + await request.promise.catch(() => {}) + }) + + expect(isDismissPrevented()).toBe(false) + expect(isDisabled('Change password')).toBe(false) + expect(mockClose).not.toHaveBeenCalled() + + await submit() + expect(mockCall).toHaveBeenCalledTimes(2) + expect(mockClose).toHaveBeenCalledTimes(1) + }) + + it('locks dismissal while requesting a code, then releases it', async () => { + const request = deferred() + mockCall.mockReturnValueOnce(request.promise) + renderDialog() + await act(async () => { + fireEvent.press(screen.getByLabelText('Request code')) + await Promise.resolve() + }) + expect(isDismissPrevented()).toBe(true) + + await act(async () => { + request.resolve({}) + await request.promise + }) + + expect(isDismissPrevented()).toBe(false) + expect(mockClose).not.toHaveBeenCalled() + }) +})