Skip to content

Commit

Permalink
Try suggested changes to TokenInput
Browse files Browse the repository at this point in the history
  • Loading branch information
ciampo committed Sep 28, 2022
1 parent 99cfdbc commit 29e46d4
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions packages/components/src/form-token-field/token-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
* External dependencies
*/
import classnames from 'classnames';
import type { ChangeEvent, ForwardedRef } from 'react';
import type { ChangeEvent, ForwardedRef, FocusEventHandler } from 'react';

/**
* WordPress dependencies
*/
import { forwardRef } from '@wordpress/element';
import { forwardRef, useState } from '@wordpress/element';

/**
* Internal dependencies
Expand All @@ -26,9 +26,13 @@ export function UnForwardedTokenInput(
selectedSuggestionIndex,
className,
onChange,
onFocus,
onBlur,
...restProps
} = props;

const [ hasFocus, setHasFocus ] = useState( false );

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

const onChangeHandler = ( event: ChangeEvent< HTMLInputElement > ) => {
Expand All @@ -39,6 +43,18 @@ export function UnForwardedTokenInput(
}
};

const onFocusHandler: FocusEventHandler< HTMLInputElement > = ( e ) => {
setHasFocus( true );
onFocus?.( e );
};

const onBlurHandler: React.FocusEventHandler< HTMLInputElement > = (
e
) => {
setHasFocus( false );
onBlur?.( e );
};

return (
<input
ref={ ref }
Expand All @@ -47,6 +63,8 @@ export function UnForwardedTokenInput(
{ ...restProps }
value={ value || '' }
onChange={ onChangeHandler }
onFocus={ onFocusHandler }
onBlur={ onBlurHandler }
size={ size }
className={ classnames(
className,
Expand All @@ -62,7 +80,11 @@ export function UnForwardedTokenInput(
: undefined
}
aria-activedescendant={
selectedSuggestionIndex !== -1
// Only add the `aria-activedescendant` attribute when:
// - the user is actively interacting with the input (`hasFocus`)
// - there is a selected suggestion (`selectedSuggestionIndex !== -1`)
// - the list of suggestions are rendered in the DOM (`isExpanded`)
hasFocus && selectedSuggestionIndex !== -1 && isExpanded
? `components-form-token-suggestions-${ instanceId }-${ selectedSuggestionIndex }`
: undefined
}
Expand Down

0 comments on commit 29e46d4

Please sign in to comment.