Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/components/Share/ShareTabParticipantsSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import usePreferredPolicy from '@hooks/usePreferredPolicy';
import {clearMoneyRequest} from '@libs/actions/IOU/MoneyRequest';
import {saveUnknownUserDetails} from '@libs/actions/Share';
import Navigation from '@libs/Navigation/Navigation';
import {shouldValidateFile} from '@libs/ReceiptUtils';
import {getPolicyExpenseChat} from '@libs/ReportUtils';
import {cancelSpan, getSpan, startSpan} from '@libs/telemetry/activeSpans';

Expand All @@ -26,10 +27,16 @@ type ShareTabParticipantsSelectorProps = {
function ShareTabParticipantsSelectorComponent({detailsPageRouteObject}: ShareTabParticipantsSelectorProps) {
const {accountID: currentUserAccountID} = useCurrentUserPersonalDetails();
const [draftTransactionIDs] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, {selector: validTransactionDraftIDsSelector});
const [currentAttachment] = useOnyx(ONYXKEYS.SHARE_TEMP_FILE);
const [validatedFile] = useOnyx(ONYXKEYS.VALIDATED_FILE_OBJECT);
const [selectedReportID, setSelectedReportID] = useState<string | number | undefined>();

const isSubmitFlow = detailsPageRouteObject === ROUTES.SHARE_SUBMIT_DETAILS;

// Focusing the search input opens the keyboard, so wait until the shared file is known and, when it has to be checked
// or converted first (e.g. HEIC), until it has passed. Otherwise the keyboard opens just before a file error bottom sheet.
const shouldDeferTextInputAutoFocus = !currentAttachment || (shouldValidateFile(currentAttachment) && !validatedFile);

const {isRestrictedToPreferredPolicy, preferredPolicyID} = usePreferredPolicy();

// When the user's domain security group restricts submission to a single workspace, skip the participant picker and
Expand Down Expand Up @@ -100,6 +107,10 @@ function ShareTabParticipantsSelectorComponent({detailsPageRouteObject}: ShareTa
return (
<MoneyRequestParticipantsSelector
iouType={CONST.IOU.TYPE.SUBMIT}
// Share shows file errors in a bottom sheet from the global modal stack. On iOS the contacts prompt opening
// over that sheet replaced it mid-presentation and froze the screen, so this flow doesn't show the prompt.
shouldShowContactImportPrompt={false}
shouldDeferTextInputAutoFocus={shouldDeferTextInputAutoFocus}
initiallySelectedReportID={typeof selectedReportID === 'string' ? selectedReportID : undefined}
onParticipantsAdded={(value) => {
// clear the existing draft transaction from the previous flow to prevent the old data from being displayed
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useContactPermissionModal/index.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import {RESULTS} from 'react-native-permissions';

import type UseContactPermissionModalParams from './types';

function useContactPermissionModal({onDeny, onGrant, onFocusTextInput}: UseContactPermissionModalParams) {
function useContactPermissionModal({onDeny, onGrant, onFocusTextInput, isEnabled = true}: UseContactPermissionModalParams) {
const [hasDeniedContactImportPrompt, hasDeniedContactImportPromptMetadata] = useOnyx(ONYXKEYS.HAS_DENIED_CONTACT_IMPORT_PROMPT);

const styles = useThemeStyles();
Expand All @@ -28,7 +28,7 @@ function useContactPermissionModal({onDeny, onGrant, onFocusTextInput}: UseConta
const isMountedRef = useRef(false);

const runContactPermissionFlow = useEffectEvent(async () => {
if (hasDeniedContactImportPrompt) {
if (!isEnabled || hasDeniedContactImportPrompt) {
onFocusTextInput();
return;
}
Expand Down
3 changes: 3 additions & 0 deletions src/hooks/useContactPermissionModal/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ type UseContactPermissionModalParams = {

/** A callback to call when the text input should be focused */
onFocusTextInput: () => void;

/** Whether the import contacts prompt may be shown. When false, the hook only asks for the text input to be focused. */
isEnabled?: boolean;
};

export default UseContactPermissionModalParams;
12 changes: 11 additions & 1 deletion src/pages/iou/request/MoneyRequestParticipantsSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ type MoneyRequestParticipantsSelectorProps = {
*/
shouldBlockParticipantSelection?: (policyID?: string) => boolean;

/** Whether the import contacts prompt may be shown when the picker opens */
shouldShowContactImportPrompt?: boolean;

/** Whether to hold off focusing the search input, e.g. while the share flow is still checking the shared file */
shouldDeferTextInputAutoFocus?: boolean;

ref?: Ref<InputFocusRef>;
};

Expand All @@ -93,6 +99,8 @@ function MoneyRequestParticipantsSelector({
onRestrictedParticipantSelected,
onCloseParticipantPicker,
shouldBlockParticipantSelection,
shouldShowContactImportPrompt = true,
shouldDeferTextInputAutoFocus = false,
ref,
}: MoneyRequestParticipantsSelectorProps) {
const isFocused = useIsFocused();
Expand All @@ -106,7 +114,7 @@ function MoneyRequestParticipantsSelector({

useImperativeHandle(ref, () => ({
focus: () => {
if (!textInputAutoFocus) {
if (!textInputAutoFocus || shouldDeferTextInputAutoFocus) {
return;
}
selectionListRef.current?.focusTextInput?.();
Expand Down Expand Up @@ -137,6 +145,8 @@ function MoneyRequestParticipantsSelector({
onRestrictedParticipantSelected={onRestrictedParticipantSelected}
onCloseParticipantPicker={onCloseParticipantPicker}
shouldBlockParticipantSelection={shouldBlockParticipantSelection}
shouldShowContactImportPrompt={shouldShowContactImportPrompt}
shouldDeferTextInputAutoFocus={shouldDeferTextInputAutoFocus}
/>
</AlwaysPaintedView>
</Activity>
Expand Down
11 changes: 10 additions & 1 deletion src/pages/iou/request/ParticipantSearchResults.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ type ParticipantSearchResultsProps = {
* Return true to block the selection (e.g. manual/odometer distance into a commuter-exclusion workspace).
*/
shouldBlockParticipantSelection?: (policyID?: string) => boolean;

/** Whether the import contacts prompt may be shown when the picker opens */
shouldShowContactImportPrompt?: boolean;

/** Whether to hold off focusing the search input, e.g. while the share flow is still checking the shared file */
shouldDeferTextInputAutoFocus?: boolean;
};

function ParticipantSearchResults({
Expand All @@ -149,6 +155,8 @@ function ParticipantSearchResults({
onRestrictedParticipantSelected,
onCloseParticipantPicker,
shouldBlockParticipantSelection,
shouldShowContactImportPrompt = true,
shouldDeferTextInputAutoFocus = false,
}: ParticipantSearchResultsProps) {
const getParticipantOptionKey = (option: Partial<Participant>) => option.reportID ?? option.accountID?.toString() ?? option.login ?? option.phoneNumber ?? '';
const isIOUSplit = iouType === CONST.IOU.TYPE.SPLIT;
Expand Down Expand Up @@ -564,7 +572,7 @@ function ParticipantSearchResults({
label: translate('selectionList.nameEmailOrPhoneNumber'),
hint: offlineMessage,
onChangeText: setSearchTerm,
disableAutoFocus: !textInputAutoFocus,
disableAutoFocus: !textInputAutoFocus || shouldDeferTextInputAutoFocus,
headerMessage: header,
};

Expand All @@ -574,6 +582,7 @@ function ParticipantSearchResults({
onFocusTextInput: () => {
setTextInputAutoFocus(true);
},
isEnabled: shouldShowContactImportPrompt,
});

return (
Expand Down
102 changes: 102 additions & 0 deletions tests/unit/components/Share/ShareTabParticipantsSelectorTest.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import {render} from '@testing-library/react-native';

import ShareTabParticipantsSelector from '@components/Share/ShareTabParticipantsSelector';

import type MoneyRequestParticipantsSelector from '@pages/iou/request/MoneyRequestParticipantsSelector';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import ROUTES from '@src/ROUTES';

import type {ComponentProps} from 'react';

import React from 'react';

type CapturedSelectorProps = Pick<ComponentProps<typeof MoneyRequestParticipantsSelector>, 'shouldShowContactImportPrompt' | 'shouldDeferTextInputAutoFocus'>;

let lastSelectorProps: CapturedSelectorProps | undefined;
jest.mock('@pages/iou/request/MoneyRequestParticipantsSelector', () => {
function MockMoneyRequestParticipantsSelector({shouldShowContactImportPrompt, shouldDeferTextInputAutoFocus}: CapturedSelectorProps) {
lastSelectorProps = {shouldShowContactImportPrompt, shouldDeferTextInputAutoFocus};
return null;
}
MockMoneyRequestParticipantsSelector.displayName = 'MoneyRequestParticipantsSelector';
return MockMoneyRequestParticipantsSelector;
});

// Onyx values by key; each test sets the ones it needs before rendering.
const mockOnyxValues: Record<string, unknown> = {};
jest.mock('@hooks/useOnyx', () => (key: string) => [mockOnyxValues[key], {status: 'loaded'}]);

jest.mock('@hooks/useCurrentUserPersonalDetails', () => () => ({accountID: 1}));
jest.mock('@hooks/usePreferredPolicy', () => () => ({isRestrictedToPreferredPolicy: false, preferredPolicyID: undefined}));
jest.mock('@libs/telemetry/activeSpans', () => ({cancelSpan: jest.fn(), getSpan: jest.fn(), startSpan: jest.fn()}));
jest.mock('@libs/actions/IOU/MoneyRequest', () => ({clearMoneyRequest: jest.fn()}));
jest.mock('@libs/actions/Share', () => ({saveUnknownUserDetails: jest.fn()}));
jest.mock('@libs/Navigation/Navigation', () => ({navigate: jest.fn(), getActiveRoute: jest.fn(() => '')}));
jest.mock('@libs/ReportUtils', () => ({getPolicyExpenseChat: jest.fn()}));
jest.mock('@userActions/Report', () => ({getOptimisticChatReport: jest.fn(), saveReportDraft: jest.fn()}));

const sharedHeic = {id: 'shared.heic', content: 'file:///sharedFiles/shared.heic', mimeType: CONST.SHARE_FILE_MIMETYPE.HEIC};
const sharedJpeg = {id: 'shared.jpeg', content: 'file:///sharedFiles/shared.jpeg', mimeType: CONST.SHARE_FILE_MIMETYPE.JPEG};

function renderSelector() {
return render(<ShareTabParticipantsSelector detailsPageRouteObject={ROUTES.SHARE_SUBMIT_DETAILS} />);
}

describe('ShareTabParticipantsSelector', () => {
beforeEach(() => {
lastSelectorProps = undefined;
for (const key of Object.keys(mockOnyxValues)) {
delete mockOnyxValues[key];
}
});

it.each([
['Submit', ROUTES.SHARE_SUBMIT_DETAILS],
['Share', ROUTES.SHARE_DETAILS],
])('does not show the import contacts prompt in the %s tab', (_tabName, detailsPageRouteObject) => {
// Given the share flow is open on this tab
// When its participant picker renders
render(<ShareTabParticipantsSelector detailsPageRouteObject={detailsPageRouteObject} />);

// Then it turns the prompt off, so it can't open over the share flow's file error bottom sheet
expect(lastSelectorProps?.shouldShowContactImportPrompt).toBe(false);
});

it('waits to focus the search input until the shared file is known', () => {
// Given the shared file hasn't been read yet
// When the picker renders
renderSelector();

// Then the keyboard stays closed for now, because the file may still need checking
expect(lastSelectorProps?.shouldDeferTextInputAutoFocus).toBe(true);
});

it('focuses the search input right away for a shared file that needs no checking', () => {
// Given a shared JPEG, which skips the HEIC/image check
mockOnyxValues[ONYXKEYS.SHARE_TEMP_FILE] = sharedJpeg;

// When the picker renders
renderSelector();

// Then the search input can focus right away
expect(lastSelectorProps?.shouldDeferTextInputAutoFocus).toBe(false);
Comment thread
mountiny marked this conversation as resolved.
Resolved
});

it('keeps the keyboard closed while a shared HEIC is checked, and opens it only once the file has passed', () => {
// Given a shared HEIC that is still being converted, or failed and is showing the error bottom sheet
mockOnyxValues[ONYXKEYS.SHARE_TEMP_FILE] = sharedHeic;
const {rerender} = renderSelector();

// Then the search input waits, so the keyboard can't open under the error bottom sheet
expect(lastSelectorProps?.shouldDeferTextInputAutoFocus).toBe(true);

// When the converted file is saved
mockOnyxValues[ONYXKEYS.VALIDATED_FILE_OBJECT] = {uri: 'file:///converted.jpg', name: 'shared.jpg', type: 'image/jpeg'};
rerender(<ShareTabParticipantsSelector detailsPageRouteObject={ROUTES.SHARE_SUBMIT_DETAILS} />);

// Then the search input may focus
expect(lastSelectorProps?.shouldDeferTextInputAutoFocus).toBe(false);
});
});
86 changes: 86 additions & 0 deletions tests/unit/hooks/useContactPermissionModal.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import {renderHook, waitFor} from '@testing-library/react-native';

import useContactPermissionModal from '@hooks/useContactPermissionModal/index.native';

import {getContactPermission} from '@libs/ContactPermission';

import {RESULTS} from 'react-native-permissions';

import type * as MockUseConfirmModalUtil from '../../utils/mockUseConfirmModal';

import {mockShowConfirmModal, resetMockConfirmModal} from '../../utils/mockUseConfirmModal';

jest.mock('@hooks/useConfirmModal', () => {
const {default: mockUseConfirmModal} = jest.requireActual<typeof MockUseConfirmModalUtil>('../../utils/mockUseConfirmModal');
return mockUseConfirmModal;
});

jest.mock('@components/Modal/Global/ModalContext', () => {
const {createMockModalContextModule} = jest.requireActual<typeof MockUseConfirmModalUtil>('../../utils/mockUseConfirmModal');
return createMockModalContextModule();
});

jest.mock('@hooks/useLazyAsset', () => ({
useMemoizedLazyIllustrations: () => ({ToddWithPhones: 'ToddWithPhones'}),
}));

jest.mock('@hooks/useLocalize', () => () => ({
translate: (key: string) => key,
}));

jest.mock('@hooks/useThemeStyles', () => () => ({
mb0: {},
mb4: {},
mt2: {},
textHeadline: {},
textLabelSupportingEmptyValue: {},
}));

jest.mock('@hooks/useOnyx', () => () => [false, {status: 'loaded'}]);

jest.mock('@libs/actions/ContactPermissions', () => ({
setHasDeniedContactImportPrompt: jest.fn(),
}));

jest.mock('@libs/ContactPermission', () => ({
getContactPermission: jest.fn(),
requestContactPermission: jest.fn(),
}));

const mockGetContactPermission = jest.mocked(getContactPermission);

function renderContactPermissionModal(isEnabled?: boolean) {
const params = {onDeny: jest.fn(), onGrant: jest.fn(), onFocusTextInput: jest.fn(), isEnabled};
return {params, ...renderHook(() => useContactPermissionModal(params))};
}

describe('useContactPermissionModal', () => {
beforeEach(() => {
jest.clearAllMocks();
resetMockConfirmModal();
// Contacts permission hasn't been asked yet, which is when the prompt normally shows.
mockGetContactPermission.mockResolvedValue(RESULTS.DENIED);
});

it('shows the import contacts prompt when contacts permission has not been asked yet', async () => {
// Given the prompt is enabled (the default) and contacts permission hasn't been asked yet
// When the hook mounts
renderContactPermissionModal();

// Then the import contacts prompt opens
await waitFor(() => expect(mockShowConfirmModal).toHaveBeenCalledTimes(1));
Comment thread
mountiny marked this conversation as resolved.
Resolved
});

it('does not show the prompt when it is disabled, and focuses the text input instead', async () => {
// Given a picker that turned the prompt off, as the share flow does
// When the hook mounts
const {params} = renderContactPermissionModal(false);

// Then the text input is focused as if the prompt weren't needed
await waitFor(() => expect(params.onFocusTextInput).toHaveBeenCalledTimes(1));

// And neither the prompt nor the permission check runs
expect(mockShowConfirmModal).not.toHaveBeenCalled();
expect(mockGetContactPermission).not.toHaveBeenCalled();
});
});
Loading