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
4 changes: 4 additions & 0 deletions src/CONST/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9887,6 +9887,7 @@ const CONST = {
HOURS_FIELD: 'RequestConfirmationList-HoursField',
TIME_RATE_FIELD: 'RequestConfirmationList-TimeRateField',
CATEGORY_FIELD: 'RequestConfirmationList-CategoryField',
ADD_CATEGORY_BUTTON: 'RequestConfirmationList-AddCategoryButton',
DATE_FIELD: 'RequestConfirmationList-DateField',
TAG_FIELD: 'RequestConfirmationList-TagField',
TAX_RATE_FIELD: 'RequestConfirmationList-TaxRateField',
Expand Down Expand Up @@ -9965,6 +9966,9 @@ const CONST = {
GETTING_STARTED_ROW: 'HomePage-GettingStartedRow',
GETTING_STARTED_FOOTER_HELP: 'HomePage-GettingStartedFooterHelp',
},
CATEGORY_PICKER_MODAL: {
BACK_BUTTON: 'CategoryPickerModal-BackButton',
},
CALENDAR_PICKER: {
YEAR_PICKER: 'CalendarPicker-YearPicker',
MONTH_PICKER: 'CalendarPicker-MonthPicker',
Expand Down
4 changes: 3 additions & 1 deletion src/ROUTES.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2107,7 +2107,9 @@ const DYNAMIC_ROUTES = {
},
MONEY_REQUEST_STEP_CATEGORY_CREATE: {
path: 'add-category',
entryScreens: [SCREENS.MONEY_REQUEST.DYNAMIC_STEP_CATEGORY],
entryScreens: [SCREENS.MONEY_REQUEST.DYNAMIC_STEP_CATEGORY, SCREENS.MONEY_REQUEST.STEP_CONFIRMATION, SCREENS.MONEY_REQUEST.CREATE, SCREENS.SHARE.SUBMIT_DETAILS],
getRoute: (params: {action: IOUAction; iouType: IOUType; transactionID: string; reportID: string | undefined}) => getUrlWithParams('add-category', params),
queryParams: ['action', 'iouType', 'transactionID', 'reportID'],
},
MONEY_REQUEST_ATTENDEE: {
path: 'attendees',
Expand Down
66 changes: 65 additions & 1 deletion src/components/CategoryPicker/CategoryPickerModal.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import Icon from '@components/Icon';
import PopoverWithMeasuredContent from '@components/PopoverWithMeasuredContent';
import type PopoverWithMeasuredContentProps from '@components/PopoverWithMeasuredContent/types';
import PressableWithFeedback from '@components/Pressable/PressableWithFeedback';
import type {ListItem} from '@components/SelectionList/types';
import Text from '@components/Text';
import Tooltip from '@components/Tooltip';

import useKeyboardState from '@hooks/useKeyboardState';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import useOnyx from '@hooks/useOnyx';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useSafeAreaPaddings from '@hooks/useSafeAreaPaddings';
import useStyleUtils from '@hooks/useStyleUtils';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import useViewportOffsetTop from '@hooks/useViewportOffsetTop';
import useWindowDimensions from '@hooks/useWindowDimensions';
Expand All @@ -16,6 +23,8 @@ import getBottomSheetHeight from '@libs/getBottomSheetHeight';
import getNonEmptyStringOnyxID from '@libs/getNonEmptyStringOnyxID';
import getSelectionListPopoverContentHeight from '@libs/getSelectionListPopoverContentHeight';

import variables from '@styles/variables';

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

Expand All @@ -26,6 +35,9 @@ import {View} from 'react-native';

import CategoryPicker from '.';

/** Height of the add-category header the list shows above its options. Shared with the row sizing the container, so the two never disagree. */
const CATEGORY_PICKER_HEADER_HEIGHT = variables.componentSizeNormal;

const DEFAULT_ANCHOR_ALIGNMENT = {
horizontal: CONST.MODAL.ANCHOR_ORIGIN_HORIZONTAL.LEFT,
vertical: CONST.MODAL.ANCHOR_ORIGIN_VERTICAL.TOP,
Expand All @@ -51,6 +63,12 @@ type CategoryPickerModalProps = {
/** Whether the pop-over shrinks to the height its list needs, treating `popoverHeight` as a ceiling. */
shouldFitContentHeight?: boolean;

/** Shows a header with a back button and an add button, for users who can add a category to the workspace */
onAddCategory?: () => void;

/** Sentry label for the add button, so each caller's presses are attributed to it */
addCategorySentryLabel?: string;

/** Whether the pop-over may flip to the other side of the anchor when it overflows. It shifts by a whole pop-over height, so a caller that already picked the side turns this off. */
shouldSwitchPositionIfOverflow?: boolean;
} & Omit<PopoverWithMeasuredContentProps, 'anchorRef' | 'children' | 'onClose'>;
Expand All @@ -68,8 +86,13 @@ function CategoryPickerModal({
popoverHeight = CONST.POPOVER_DROPDOWN_MAX_HEIGHT,
shouldFitContentHeight = false,
shouldSwitchPositionIfOverflow = true,
onAddCategory,
addCategorySentryLabel,
}: CategoryPickerModalProps) {
const styles = useThemeStyles();
const theme = useTheme();
const {translate} = useLocalize();
const icons = useMemoizedLazyExpensifyIcons(['BackArrow', 'Plus']);
const StyleUtils = useStyleUtils();
// eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth -- must match PopoverWithMeasuredContent's dock decision (bottom-docked only when isSmallScreenWidth)
const {isSmallScreenWidth} = useResponsiveLayout();
Expand All @@ -84,7 +107,8 @@ function CategoryPickerModal({

const categoriesCount = policyCategories ?? 0;
const isSearchable = categoriesCount >= CONST.STANDARD_LIST_ITEM_LIMIT;
const estimatedContentHeight = getSelectionListPopoverContentHeight({optionCount: Math.max(renderedRowCount ?? categoriesCount, 1), isSearchable});
const headerHeight = onAddCategory ? CATEGORY_PICKER_HEADER_HEIGHT : 0;
const estimatedContentHeight = getSelectionListPopoverContentHeight({optionCount: Math.max(renderedRowCount ?? categoriesCount, 1), isSearchable}) + headerHeight;

// The sheet pads itself above the home indicator, except while the keyboard already covers it. The offline indicator
// is drawn on the page behind the sheet, so no room is kept for it.
Expand Down Expand Up @@ -135,6 +159,45 @@ function CategoryPickerModal({
outerStyle={outerStyle}
>
<View style={[StyleUtils.getHeight(popoverDimensions.height), styles.flexColumn, styles.pt4, StyleUtils.getPaddingBottom(bottomSafeAreaPadding)]}>
{!!onAddCategory && (
<View style={[styles.flexRow, styles.alignItemsCenter, styles.justifyContentBetween, styles.ph5, styles.pt1, styles.pb4, StyleUtils.getHeight(headerHeight)]}>
<View style={[styles.flexRow, styles.alignItemsCenter, styles.gap3]}>
<Tooltip text={translate('common.back')}>
<PressableWithFeedback
accessibilityLabel={translate('common.back')}
role={CONST.ROLE.BUTTON}
onPress={onClose}
shouldUseAutoHitSlop
sentryLabel={CONST.SENTRY_LABEL.CATEGORY_PICKER_MODAL.BACK_BUTTON}
>
<Icon
src={icons.BackArrow}
fill={theme.icon}
width={variables.iconSizeNormal}
height={variables.iconSizeNormal}
/>
</PressableWithFeedback>
</Tooltip>
<Text style={styles.textLabelSupporting}>{translate('common.category')}</Text>
</View>
<Tooltip text={translate('workspace.categories.addCategory')}>
<PressableWithFeedback
Comment thread
DylanDylann marked this conversation as resolved.
Resolved
accessibilityLabel={translate('workspace.categories.addCategory')}
role={CONST.ROLE.BUTTON}
onPress={onAddCategory}
shouldUseAutoHitSlop
sentryLabel={addCategorySentryLabel}
>
<Icon
src={icons.Plus}
fill={theme.icon}
width={variables.iconSizeNormal}
height={variables.iconSizeNormal}
/>
</PressableWithFeedback>
</Tooltip>
</View>
)}
<CategoryPicker
onRenderedRowCountChange={setRenderedRowCount}
selectedCategory={selectedCategory}
Expand All @@ -148,3 +211,4 @@ function CategoryPickerModal({
}

export default CategoryPickerModal;
export {CATEGORY_PICKER_HEADER_HEIGHT};
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {CATEGORY_PICKER_HEADER_HEIGHT} from '@components/CategoryPicker/CategoryPickerModal';
import MenuItemWithTopDescription from '@components/MenuItemWithTopDescription';
import {useConfirmationFields} from '@components/MoneyRequestConfirmationFields/context';
import usePolicyCategoriesForConfirmation from '@components/MoneyRequestConfirmationList/hooks/usePolicyCategoriesForConfirmation';

import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import {useMemoizedLazyExpensifyIcons} from '@hooks/useLazyAsset';
import useLocalize from '@hooks/useLocalize';
import usePermissions from '@hooks/usePermissions';
Expand All @@ -12,6 +14,7 @@ import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/crea
import Navigation from '@libs/Navigation/Navigation';
import TransitionTracker from '@libs/Navigation/TransitionTracker';
import {hasEnabledOptions} from '@libs/OptionsListUtils';
import {canCreateCategoryInSitu} from '@libs/PolicyUtils';

import CONST from '@src/CONST';
import type {IOUAction, IOUType} from '@src/CONST';
Expand Down Expand Up @@ -70,6 +73,7 @@ function CategoryField({
const styles = useThemeStyles();
const {translate} = useLocalize();
const icons = useMemoizedLazyExpensifyIcons(['Sparkles']);
const currentUserLogin = useCurrentUserPersonalDetails().login;
const dropdownRef = useRef<ExpenseFieldDropdownHandle>(null);
const isFocused = useIsFocused();
// Where the user is in the workspace step the row sent them to. Scoped to that one departure and return: it
Expand Down Expand Up @@ -115,6 +119,7 @@ function CategoryField({
// The one condition both the row and the effect below open on, so the effect never asks the row to open a
// list it would refuse and fall back to the full page for.
const canOpenListInPlace = shouldOpenInDropdown && !isReadOnly && !didConfirm;
const canAddCategory = canCreateCategoryInSitu(policy, currentUserLogin);
const canOpenInDropdownAfterWorkspaceStep = canUseAnchoredFieldDropdowns && shouldUseDropdownRows && isCreatingExpense;

// Blurs move the step along: the first is the departure to the workspace step, the next after returning means
Expand Down Expand Up @@ -225,13 +230,15 @@ function CategoryField({
errorText={shouldDisplayCategoryError ? translate(formError as TranslationPaths) : ''}
onPress={openCategoryPage}
shouldOpenInDropdown={canOpenListInPlace}
listHeaderHeight={canAddCategory ? CATEGORY_PICKER_HEADER_HEIGHT : 0}
renderDropdown={(dropdownProps) =>
!!transactionID && (
<CategoryFieldDropdown
{...dropdownProps}
transactionID={transactionID}
policy={policy}
selectedCategory={selectedCategory}
canAddCategory={canAddCategory}
/>
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ import type {ListItem} from '@components/SelectionList/types';
import useOnyx from '@hooks/useOnyx';
import useUpdateTransactionCategory from '@hooks/useUpdateTransactionCategory';

import createDynamicRoute from '@libs/Navigation/helpers/dynamicRoutesUtils/createDynamicRoute';
import Navigation from '@libs/Navigation/Navigation';
import TransitionTracker from '@libs/Navigation/TransitionTracker';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import {DYNAMIC_ROUTES} from '@src/ROUTES';
import type * as OnyxTypes from '@src/types/onyx';

import type {OnyxEntry} from 'react-native-onyx';
Expand All @@ -25,15 +30,18 @@ type CategoryFieldDropdownProps = ExpenseFieldDropdownRenderProps & {

/** Category the expense already holds, so the list can mark it */
selectedCategory: string;

/** Whether the user can add a category to the workspace from the list */
canAddCategory: boolean;
};

/**
* The category list, in the container anchored to the expense form's category row. Mounted only once the row is
* opened, keeping its Onyx subscriptions off the form's first render, and saves through the same hook the
* full-page selector uses so both leave the expense in the same state.
*/
function CategoryFieldDropdown({transactionID, policy, selectedCategory, onClose, ...popoverProps}: CategoryFieldDropdownProps) {
const {reportID, isEditingSplitBill, action} = useConfirmationFields();
function CategoryFieldDropdown({transactionID, policy, selectedCategory, canAddCategory, onClose, ...popoverProps}: CategoryFieldDropdownProps) {
const {reportID, isEditingSplitBill, action, iouType} = useConfirmationFields();

const [report] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`);
const [transaction] = useOnyx(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`);
Expand All @@ -50,6 +58,14 @@ function CategoryFieldDropdown({transactionID, policy, selectedCategory, onClose
isEditingSplit: isEditingSplitBill,
});

const openAddCategory = () => {
Comment thread
DylanDylann marked this conversation as resolved.
Resolved
onClose();
TransitionTracker.runAfterTransitions({
callback: () => Navigation.navigate(createDynamicRoute(DYNAMIC_ROUTES.MONEY_REQUEST_STEP_CATEGORY_CREATE.getRoute({action, iouType, transactionID, reportID}))),
waitForUpcomingTransition: true,
});
};

const handleSelected = (item: ListItem) => {
// `CategoryPickerModal` hands back an empty item when the selected category is tapped again, clearing it.
updateCategory(item.searchText ?? '');
Expand All @@ -63,6 +79,8 @@ function CategoryFieldDropdown({transactionID, policy, selectedCategory, onClose
policyID={policy?.id}
selectedCategory={selectedCategory}
onSelected={handleSelected}
onAddCategory={canAddCategory ? openAddCategory : undefined}
addCategorySentryLabel={CONST.SENTRY_LABEL.REQUEST_CONFIRMATION_LIST.ADD_CATEGORY_BUTTON}
/>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ type ExpenseFieldDropdownProps = Omit<ExpenseFieldRowProps, 'onPress' | 'anchorR
/** Opens the field's full-page selector, for every case `shouldOpenInDropdown` rules out */
onPress: () => void;

/** Height of a header the list shows above its options, e.g. an add button, added to the container's limits so it still fits as many options */
listHeaderHeight?: number;

/** Lets the field open its list without a press, e.g. once the user is back from a step the press sent them to */
ref?: Ref<ExpenseFieldDropdownHandle>;
};
Expand All @@ -103,7 +106,7 @@ type ExpenseFieldDropdownHandle = {
* pop-over matches the row's width and opens below it, or above when there isn't room, capped so it is never
* clipped. Knows nothing about any particular field: each passes its own list in through `renderDropdown`.
*/
function ExpenseFieldDropdown({renderDropdown, shouldOpenInDropdown, onPress, ref, ...rowProps}: ExpenseFieldDropdownProps) {
function ExpenseFieldDropdown({renderDropdown, shouldOpenInDropdown, onPress, listHeaderHeight = 0, ref, ...rowProps}: ExpenseFieldDropdownProps) {
const {windowHeight} = useWindowDimensions();
// eslint-disable-next-line rulesdir/prefer-shouldUseNarrowLayout-instead-of-isSmallScreenWidth -- must match PopoverWithMeasuredContent's dock decision, which is on isSmallScreenWidth
const {isSmallScreenWidth} = useResponsiveLayout();
Expand All @@ -120,6 +123,9 @@ function ExpenseFieldDropdown({renderDropdown, shouldOpenInDropdown, onPress, re
shouldOpenAbove: false,
});

const maxContainerHeight = MAX_CONTAINER_HEIGHT + listHeaderHeight;
const minUsableHeight = MIN_USABLE_HEIGHT + listHeaderHeight;

const closeDropdown = () => setIsVisible(false);

const openDropdown = () => {
Expand All @@ -132,10 +138,10 @@ function ExpenseFieldDropdown({renderDropdown, shouldOpenInDropdown, onPress, re
anchorRef.current?.measureInWindow((x, y, width, height) => {
const spaceBelow = windowHeight - (y + height + CONTAINER_GAP);
const spaceAbove = y - CONTAINER_GAP - (safeAreaTop + contentHeaderHeight);
const shouldOpenAbove = spaceBelow < MAX_CONTAINER_HEIGHT && spaceAbove > spaceBelow;
const shouldOpenAbove = spaceBelow < maxContainerHeight && spaceAbove > spaceBelow;
const availableHeight = (shouldOpenAbove ? spaceAbove : spaceBelow) - CONTAINER_BORDER;

if (availableHeight < MIN_USABLE_HEIGHT) {
if (availableHeight < minUsableHeight) {
onPress();
return;
}
Expand All @@ -144,7 +150,7 @@ function ExpenseFieldDropdown({renderDropdown, shouldOpenInDropdown, onPress, re
horizontal: x,
vertical: shouldOpenAbove ? y - CONTAINER_GAP : y + height + CONTAINER_GAP,
width,
height: Math.min(MAX_CONTAINER_HEIGHT, availableHeight),
height: Math.min(maxContainerHeight, availableHeight),
shouldOpenAbove,
});
setHasEverOpened(true);
Expand Down
10 changes: 8 additions & 2 deletions src/libs/PolicyUtils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ import type {ValueOf} from 'type-fest';

import {Str} from 'expensify-common';

import {getAccountingConnectionNames, hasAccountingFeatureConnection} from './connections';
import {getAccountingConnectionNames, hasAccountingConnections, hasAccountingFeatureConnection} from './connections';
import {getPerDiemCustomUnit, isPerDiemEligiblePolicy} from './customUnits';
import {canMemberWrite, getPolicyRole, isPolicyAdmin, isPolicyApprover, isPolicyOwner, isPolicyUser} from './permissions';
import {canEditWorkspaceSettings, canMemberWrite, getPolicyRole, isPolicyAdmin, isPolicyApprover, isPolicyOwner, isPolicyUser} from './permissions';
import {canPolicyAccessFeature, isArchivedPolicy, isCollectPolicy, isControlPolicy, isGroupPolicy, isPaidGroupPolicy, isSubmitPolicy} from './policyType';

type MemberEmailsToAccountIDs = Record<string, number>;
Expand Down Expand Up @@ -943,6 +943,11 @@ function shouldHideDynamicExternalWorkflowPeople(policy: OnyxEntry<Policy>): boo
return hasDynamicExternalWorkflow(policy) && !!policy?.dynamicExternalWorkflowHidePeople;
}

/** Whether the user can add a category to the workspace straight from an expense's category picker */
function canCreateCategoryInSitu(policy: OnyxEntry<Policy>, login?: string) {
return canEditWorkspaceSettings(policy, login) && !hasAccountingConnections(policy) && !!policy?.areCategoriesEnabled;
}

function goBackFromInvalidPolicy() {
Navigation.goBack(ROUTES.WORKSPACES_LIST.route);
}
Expand Down Expand Up @@ -1872,6 +1877,7 @@ export {
hasConfiguredRules,
isMaxExpenseAmountSet,
goBackFromInvalidPolicy,
canCreateCategoryInSitu,
shouldShowSyncError,
shouldShowCustomUnitsError,
shouldShowEmployeeListError,
Expand Down
Loading
Loading