Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make sure the first result in most recents is highlighted when user uses CMD+K #52298

Merged
merged 19 commits into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
22 changes: 20 additions & 2 deletions src/components/Search/SearchRouter/SearchRouter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import usePolicy from '@hooks/usePolicy';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useThemeStyles from '@hooks/useThemeStyles';
import * as CardUtils from '@libs/CardUtils';
import getPlatform from '@libs/getPlatform';
import * as OptionsListUtils from '@libs/OptionsListUtils';
import {getAllTaxRates} from '@libs/PolicyUtils';
import type {OptionData} from '@libs/ReportUtils';
Expand Down Expand Up @@ -57,6 +58,9 @@ function SearchRouter({onRouterClose}: SearchRouterProps) {
const [autocompleteSuggestions, setAutocompleteSuggestions] = useState<AutocompleteItemData[] | undefined>([]);
const [autocompleteSubstitutions, setAutocompleteSubstitutions] = useState<SubstitutionMap>({});

const isWeb = getPlatform() === CONST.PLATFORM.WEB;
const isDesktop = getPlatform() === CONST.PLATFORM.DESKTOP;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Pujan92 should we create platform-specific files for this case?


const {shouldUseNarrowLayout} = useResponsiveLayout();
const listRef = useRef<SelectionListHandle>(null);

Expand Down Expand Up @@ -325,6 +329,18 @@ function SearchRouter({onRouterClose}: SearchRouterProps) {
Report.searchInServer(debouncedInputValue.trim());
}, [debouncedInputValue]);

const setInitialFocus = useCallback(() => {
const initialFocusIndex = (sortedRecentSearches?.slice(0, 5).length ?? 0) + (contextualReportData ? 1 : 0);
listRef.current?.setFocusedIndex(initialFocusIndex, false);
}, [sortedRecentSearches, contextualReportData]);

useEffect(() => {
if ((!isWeb && !isDesktop) || textInputValue) {
return;
}
setInitialFocus();
}, [setInitialFocus, textInputValue, isWeb, isDesktop]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
useEffect(() => {
if ((!isWeb && !isDesktop) || textInputValue) {
return;
}
setInitialFocus();
}, [setInitialFocus, textInputValue, isWeb, isDesktop]);
useEffect(() => {
if ((!isWeb && !isDesktop)) {
return;
}
setInitialFocus();
}, [setInitialFocus, isWeb, isDesktop]);

Let search change focus be handled by onSearchChange function instead of making call to setInitialFocus twice.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah you are right, it calls the setInitialFocus twice

But this is intentional actually, if we dont early return when the textInputValue is not empty, it will trigger the setInitialFocus(); since setInitialFocus updated due to contextualReportData updated when we input search term

See this video
New-Expensify.35.mp4

I think we should remove setInitialFocus(); on onSearchChange instead

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As of now we need to focus only for the first time we can remove this entire function and use initiallyFocusedOptionKey as mentioned here. We won't consider of refocusing when the input is cleared by user.

Copy link
Contributor Author

@nyomanjyotisa nyomanjyotisa Nov 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we use initiallyFocusedOptionKey, it will still focus on all platforms. Don’t we not need to focus on the mobile platform?

New-Expensify.mp4

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For that, we can use isLargeScreenWidth and set undefined initiallyFocusedOptionKey based on it.


const onSearchChange = useCallback(
(userQuery: string) => {
let newUserQuery = userQuery;
Expand All @@ -340,11 +356,13 @@ function SearchRouter({onRouterClose}: SearchRouterProps) {

if (newUserQuery) {
listRef.current?.updateAndScrollToFocusedIndex(0);
} else {
} else if (!isWeb && !isDesktop) {
listRef.current?.updateAndScrollToFocusedIndex(-1);
} else {
setInitialFocus();
}
},
[autocompleteSubstitutions, autocompleteSuggestions, setTextInputValue, updateAutocomplete],
[autocompleteSubstitutions, autocompleteSuggestions, setTextInputValue, updateAutocomplete, setInitialFocus, isWeb, isDesktop],
);

const onSearchSubmit = useCallback(
Expand Down
1 change: 1 addition & 0 deletions src/components/Search/SearchRouter/SearchRouterList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ function SearchRouterList(
sectionTitleStyles={styles.mhn2}
shouldSingleExecuteRowSelect
onArrowFocus={onArrowFocus}
shouldScrollToFocusedIndexOnFirstRender={false}
/>
);
}
Expand Down
16 changes: 11 additions & 5 deletions src/components/SelectionList/BaseSelectionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ function BaseSelectionList<TItem extends ListItem>(
shouldKeepFocusedItemAtTopOfViewableArea = false,
shouldDebounceScrolling = false,
shouldPreventActiveCellVirtualization = false,
shouldScrollToFocusedIndexOnFirstRender = true,
}: BaseSelectionListProps<TItem>,
ref: ForwardedRef<SelectionListHandle>,
) {
Expand Down Expand Up @@ -316,12 +317,14 @@ function BaseSelectionList<TItem extends ListItem>(
maxIndex: Math.min(flattenedSections.allOptions.length - 1, CONST.MAX_SELECTION_LIST_PAGE_LENGTH * currentPage - 1),
disabledIndexes: disabledArrowKeyIndexes,
isActive: isFocused,
onFocusedIndexChange: (index: number) => {
onFocusedIndexChange: (index: number, shouldScrollToIndex = true) => {
const focusedItem = flattenedSections.allOptions.at(index);
if (focusedItem) {
onArrowFocus(focusedItem);
}
(shouldDebounceScrolling ? debouncedScrollToIndex : scrollToIndex)(index, true);
if (shouldScrollToIndex) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (shouldScrollToIndex) {
if (shouldScrollToFocusedIndex) {
(shouldDebounceScrolling ? debouncedScrollToIndex : scrollToIndex)(index, true);
}

I think we don't need any changes in useArrowKeyFocusManager file.
How about adding state isInitialRender in SearchRouterList with default value false and toggle its value in onLayout of the SelectionList and pass it to SelectionList like below.

shouldScrollToFocusedIndex={!isInitialRender}

(shouldDebounceScrolling ? debouncedScrollToIndex : scrollToIndex)(index, true);
}
},
isFocused,
});
Expand Down Expand Up @@ -586,10 +589,12 @@ function BaseSelectionList<TItem extends ListItem>(
if (!isInitialSectionListRender) {
return;
}
scrollToIndex(focusedIndex, false);
if (shouldScrollToFocusedIndexOnFirstRender) {
scrollToIndex(focusedIndex, false);
}
setIsInitialSectionListRender(false);
},
[focusedIndex, isInitialSectionListRender, scrollToIndex, shouldUseDynamicMaxToRenderPerBatch],
[focusedIndex, isInitialSectionListRender, scrollToIndex, shouldUseDynamicMaxToRenderPerBatch, shouldScrollToFocusedIndexOnFirstRender],
);

const onSectionListLayout = useCallback(
Expand Down Expand Up @@ -713,12 +718,13 @@ function BaseSelectionList<TItem extends ListItem>(
isTextInputFocusedRef.current = isTextInputFocused;
}, []);

useImperativeHandle(ref, () => ({scrollAndHighlightItem, clearInputAfterSelect, updateAndScrollToFocusedIndex, updateExternalTextInputFocus, scrollToIndex}), [
useImperativeHandle(ref, () => ({scrollAndHighlightItem, clearInputAfterSelect, updateAndScrollToFocusedIndex, updateExternalTextInputFocus, scrollToIndex, setFocusedIndex}), [
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
useImperativeHandle(ref, () => ({scrollAndHighlightItem, clearInputAfterSelect, updateAndScrollToFocusedIndex, updateExternalTextInputFocus, scrollToIndex, setFocusedIndex}), [
useImperativeHandle(ref, () => ({scrollAndHighlightItem, clearInputAfterSelect, updateAndScrollToFocusedIndex, updateExternalTextInputFocus, scrollToIndex}), [

scrollAndHighlightItem,
clearInputAfterSelect,
updateAndScrollToFocusedIndex,
updateExternalTextInputFocus,
scrollToIndex,
setFocusedIndex,
]);

/** Selects row when pressing Enter */
Expand Down
4 changes: 4 additions & 0 deletions src/components/SelectionList/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -612,12 +612,16 @@ type BaseSelectionListProps<TItem extends ListItem> = Partial<ChildrenProps> & {

/** Whether to prevent the active cell from being virtualized and losing focus in browsers */
shouldPreventActiveCellVirtualization?: boolean;

/** Whether to scroll to the focused index on the first render. */
shouldScrollToFocusedIndexOnFirstRender?: boolean;
} & TRightHandSideComponent<TItem>;

type SelectionListHandle = {
scrollAndHighlightItem?: (items: string[], timeout: number) => void;
clearInputAfterSelect?: () => void;
scrollToIndex: (index: number, animated?: boolean) => void;
setFocusedIndex: (index: number, shouldScrollToIndex?: boolean) => void;
updateAndScrollToFocusedIndex: (newFocusedIndex: number) => void;
updateExternalTextInputFocus: (isTextInputFocused: boolean) => void;
};
Expand Down
27 changes: 19 additions & 8 deletions src/hooks/useArrowKeyFocusManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import usePrevious from './usePrevious';

type Config = {
maxIndex: number;
onFocusedIndexChange?: (index: number) => void;
onFocusedIndexChange?: (index: number, shouldScrollToIndex?: boolean) => void;
initialFocusedIndex?: number;
disabledIndexes?: readonly number[];
shouldExcludeTextAreaNodes?: boolean;
Expand All @@ -17,7 +17,7 @@ type Config = {
isFocused?: boolean;
};

type UseArrowKeyFocusManager = [number, (index: number) => void];
type UseArrowKeyFocusManager = [number, (index: number, shouldScrollToIndex?: boolean) => void];

/**
* A hook that makes it easy to use the arrow keys to manage focus of items in a list
Expand Down Expand Up @@ -51,8 +51,15 @@ export default function useArrowKeyFocusManager({
allowNegativeIndexes = false,
isFocused = true,
}: Config): UseArrowKeyFocusManager {
const [focusedIndex, setFocusedIndex] = useState(initialFocusedIndex);
const [focusedIndex, setFocusedIndexState] = useState(initialFocusedIndex);
const [shouldScrollToIndex, setShouldScrollToIndex] = useState(true);
const prevIsFocusedIndex = usePrevious(focusedIndex);

const setFocusedIndex = useCallback((index: number, shouldScroll = true) => {
setFocusedIndexState(index);
setShouldScrollToIndex(shouldScroll);
}, []);

const arrowConfig = useMemo(
() => ({
excludedNodes: shouldExcludeTextAreaNodes ? ['TEXTAREA'] : [],
Expand All @@ -73,7 +80,7 @@ export default function useArrowKeyFocusManager({
if (prevIsFocusedIndex === focusedIndex) {
return;
}
onFocusedIndexChange(focusedIndex);
onFocusedIndexChange(focusedIndex, shouldScrollToIndex);
// eslint-disable-next-line react-compiler/react-compiler, react-hooks/exhaustive-deps
}, [focusedIndex, prevIsFocusedIndex]);

Expand All @@ -83,7 +90,8 @@ export default function useArrowKeyFocusManager({
}
const nextIndex = disableCyclicTraversal ? -1 : maxIndex;

setFocusedIndex((actualIndex) => {
setShouldScrollToIndex(true);
setFocusedIndexState((actualIndex) => {
const currentFocusedIndex = actualIndex > 0 ? actualIndex - (itemsPerRow ?? 1) : nextIndex;
let newFocusedIndex = currentFocusedIndex;

Expand Down Expand Up @@ -116,7 +124,8 @@ export default function useArrowKeyFocusManager({

const nextIndex = disableCyclicTraversal ? maxIndex : 0;

setFocusedIndex((actualIndex) => {
setShouldScrollToIndex(true);
setFocusedIndexState((actualIndex) => {
let currentFocusedIndex = -1;

if (actualIndex === -1) {
Expand Down Expand Up @@ -161,7 +170,8 @@ export default function useArrowKeyFocusManager({

const nextIndex = disableCyclicTraversal ? -1 : maxIndex;

setFocusedIndex((actualIndex) => {
setShouldScrollToIndex(true);
setFocusedIndexState((actualIndex) => {
const currentFocusedIndex = actualIndex > 0 ? actualIndex - 1 : nextIndex;

let newFocusedIndex = currentFocusedIndex;
Expand All @@ -187,7 +197,8 @@ export default function useArrowKeyFocusManager({

const nextIndex = disableCyclicTraversal ? maxIndex : 0;

setFocusedIndex((actualIndex) => {
setShouldScrollToIndex(true);
setFocusedIndexState((actualIndex) => {
const currentFocusedIndex = actualIndex < maxIndex ? actualIndex + 1 : nextIndex;

let newFocusedIndex = currentFocusedIndex;
Expand Down
Loading