Skip to content

Commit

Permalink
fix(List): fix ListTitle getting focus on initialization (#2638)
Browse files Browse the repository at this point in the history
  • Loading branch information
rivka-ungar authored Dec 10, 2024
1 parent 845390a commit 0986200
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
21 changes: 19 additions & 2 deletions packages/core/src/components/List/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import React, {
forwardRef,
ReactElement,
useCallback,
useEffect,
useMemo,
useRef,
useState
Expand All @@ -26,6 +27,7 @@ import {
getListItemIndexById,
getNextListItemIndex,
getPrevListItemIndex,
isListItem,
useListId
} from "./utils/ListUtils";
import styles from "./List.module.scss";
Expand Down Expand Up @@ -113,6 +115,20 @@ const List: VibeComponent<ListProps> & {
ref: componentRef
});

useEffect(() => {
const selectedItemIndex = childrenRefs.current.findIndex(
child => isListItem(child) && child?.getAttribute("aria-selected") === "true"
);
if (selectedItemIndex !== -1) {
updateFocusedItem(getListItemIdByIndex(childrenRefs, selectedItemIndex));
} else {
const firstFocusableIndex = childrenRefs.current.findIndex(child => isListItem(child));
if (firstFocusableIndex !== -1) {
updateFocusedItem(getListItemIdByIndex(childrenRefs, firstFocusableIndex));
}
}
}, [updateFocusedItem]);

const overrideChildren = useMemo(() => {
let override: ReactElement | ReactElement[] = Array.isArray(children) ? children : [children];
if (renderOnlyVisibleItems) {
Expand All @@ -123,12 +139,13 @@ const List: VibeComponent<ListProps> & {
if (!React.isValidElement(child)) {
return child;
}

const id = (child.props as { id: string }).id || `${overrideId}-item-${index}`;
const isFocusableItem = isListItem(childrenRefs.current[index]);

return React.cloneElement(child, {
// @ts-ignore not sure how to deal with ref here
ref: ref => (childrenRefs.current[index] = ref),
tabIndex: focusIndex === index ? 0 : -1,
tabIndex: focusIndex === index && isFocusableItem ? 0 : -1,
id,
component: getListItemComponentType(component)
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ exports[`List renders correctly with list items 1`] = `
onFocus={[Function]}
onMouseEnter={[Function]}
role="option"
tabIndex={0}
tabIndex={-1}
>
1
</li>
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/components/List/utils/ListUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const getListItemComponentType = (listComponent: ListElement): ListItemEl
}
};

const isListItem = (element: HTMLElement) => {
export const isListItem = (element: HTMLElement) => {
return element && element.getAttribute("role") === "option";
};

Expand Down

0 comments on commit 0986200

Please sign in to comment.