Skip to content

Commit

Permalink
fix(List): fix ListTitle getting focus on initialization
Browse files Browse the repository at this point in the history
  • Loading branch information
rivka-ungar committed Dec 9, 2024
1 parent b8f895b commit d407cf8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
13 changes: 12 additions & 1 deletion 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,14 @@ const List: VibeComponent<ListProps> & {
ref: componentRef
});

useEffect(() => {
const firstFocusableIndex = childrenRefs.current.findIndex(child => isListItem(child));
if (firstFocusableIndex !== -1) {
setFocusIndex(firstFocusableIndex);
updateFocusedItem(getListItemIdByIndex(childrenRefs, firstFocusableIndex));
}
}, [updateFocusedItem]);

const overrideChildren = useMemo(() => {
let override: ReactElement | ReactElement[] = Array.isArray(children) ? children : [children];
if (renderOnlyVisibleItems) {
Expand All @@ -125,10 +135,11 @@ const List: VibeComponent<ListProps> & {
}

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
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 d407cf8

Please sign in to comment.