From 2af92e5588a39294bdd39d6dabe8ec1368ea0075 Mon Sep 17 00:00:00 2001 From: Roy Johnson Date: Wed, 28 Aug 2024 10:41:11 -0500 Subject: [PATCH] Focus on first item in revealed dropdown --- src/app/components/Dropdown.tsx | 15 ++++++++++++--- src/app/reactUtils.ts | 2 +- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/app/components/Dropdown.tsx b/src/app/components/Dropdown.tsx index 3a146cade1..294e8dec02 100644 --- a/src/app/components/Dropdown.tsx +++ b/src/app/components/Dropdown.tsx @@ -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'; @@ -167,10 +167,19 @@ const TabTransparentDropdown = styled(( `; function TrappingDropdownList(props: object) { - const ref = React.useRef(null); + const ref = React.useRef(null); useTrapTabNavigation(ref); + React.useEffect( + () => { + if (ref.current?.querySelector) { + ref.current?.querySelector(focusableItemQuery)?.focus(); + } + }, + [] + ); + return ( ); diff --git a/src/app/reactUtils.ts b/src/app/reactUtils.ts index c66c004960..55ecd50054 100644 --- a/src/app/reactUtils.ts +++ b/src/app/reactUtils.ts @@ -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(',');