Skip to content

Commit

Permalink
Focus on first item in revealed dropdown
Browse files Browse the repository at this point in the history
  • Loading branch information
RoyEJohnson committed Sep 17, 2024
1 parent a881a46 commit 2af92e5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
15 changes: 12 additions & 3 deletions src/app/components/Dropdown.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@

import { HTMLElement } from '@openstax/types/lib.dom';
import { HTMLElement, HTMLMenuElement } from '@openstax/types/lib.dom';
import flow from 'lodash/fp/flow';
import isUndefined from 'lodash/fp/isUndefined';
import omitBy from 'lodash/fp/omitBy';
import React, { ReactNode } from 'react';
import { FormattedMessage, useIntl } from 'react-intl';
import styled, { css, keyframes } from 'styled-components/macro';
import { useFocusLost, useTrapTabNavigation } from '../reactUtils';
import { useFocusLost, useTrapTabNavigation, focusableItemQuery } from '../reactUtils';
import { useOnEsc } from '../reactUtils';
import theme, { defaultFocusOutline } from '../theme';
import { preventDefault } from '../utils';
Expand Down Expand Up @@ -167,10 +167,19 @@ const TabTransparentDropdown = styled((
`;

function TrappingDropdownList(props: object) {
const ref = React.useRef(null);
const ref = React.useRef<HTMLMenuElement>(null);

useTrapTabNavigation(ref);

React.useEffect(
() => {
if (ref.current?.querySelector) {
ref.current?.querySelector<HTMLElement>(focusableItemQuery)?.focus();
}
},
[]
);

return (
<menu ref={ref} {...props} />
);
Expand Down
2 changes: 1 addition & 1 deletion src/app/reactUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function isHidden(el: HTMLElement) {
return el.offsetWidth === 0 && el.offsetHeight === 0;
}

const focusableItemQuery = [
export const focusableItemQuery = [
'button', 'input', 'select', 'textarea', '[href]', '[tabindex]:not([tabindex="-1"]',
].map((s) => s.includes('[') ? s : `${s}:not([disabled])`).join(',');

Expand Down

0 comments on commit 2af92e5

Please sign in to comment.