Skip to content

Commit

Permalink
Only focus the form token field if it is not on initial render.
Browse files Browse the repository at this point in the history
  • Loading branch information
alexstine committed Sep 22, 2022
1 parent 7706fa2 commit 819fe4d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
1 change: 1 addition & 0 deletions packages/components/src/combobox-control/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,7 @@ function ComboboxControl( {
? `${ currentLabel }, ${ label }`
: null
}
inputHasFocus={ inputHasFocus }
onFocus={ onFocus }
onBlur={ onBlur }
isExpanded={ isExpanded }
Expand Down
16 changes: 14 additions & 2 deletions packages/components/src/form-token-field/token-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { ChangeEvent, ForwardedRef } from 'react';
/**
* WordPress dependencies
*/
import { forwardRef } from '@wordpress/element';
import { forwardRef, useEffect, useState } from '@wordpress/element';

/**
* Internal dependencies
Expand All @@ -22,6 +22,7 @@ export function UnForwardedTokenInput(
const {
value,
isExpanded,
inputHasFocus = false,
instanceId,
selectedSuggestionIndex,
className,
Expand All @@ -31,6 +32,17 @@ export function UnForwardedTokenInput(

const size = value ? value.length + 1 : 0;

// Is this our first render? Take the value and find out if it should be. If no value, A11Y concerns will not exist so false is okay.
const [ isInitialRender, setIsInitialRender ] = useState(
value ? true : false
);
useEffect( () => {
// If initial render is set to true but the user just placed focus on the input, now focus can be allowed.
if ( isInitialRender && inputHasFocus ) {
setIsInitialRender( false );
}
}, [ inputHasFocus ] );

const onChangeHandler = ( event: ChangeEvent< HTMLInputElement > ) => {
if ( onChange ) {
onChange( {
Expand Down Expand Up @@ -62,7 +74,7 @@ export function UnForwardedTokenInput(
: undefined
}
aria-activedescendant={
selectedSuggestionIndex !== -1
! isInitialRender && selectedSuggestionIndex !== -1
? `components-form-token-suggestions-${ instanceId }-${ selectedSuggestionIndex }`
: undefined
}
Expand Down
1 change: 1 addition & 0 deletions packages/components/src/form-token-field/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ export interface TokenProps extends TokenItem {

export interface TokenInputProps {
isExpanded: boolean;
inputHasFocus?: boolean;
instanceId: string | number;
selectedSuggestionIndex: number;
onChange?: ( { value }: { value: string } ) => void;
Expand Down

0 comments on commit 819fe4d

Please sign in to comment.