Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Components: Introduce support custom suggestions filter for the FormTokenField component #61683

Draft
wants to merge 3 commits into
base: trunk
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions packages/components/src/form-token-field/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ export function FormTokenField( props: FormTokenFieldProps ) {
__next40pxDefaultSize = false,
__experimentalAutoSelectFirstMatch = false,
__nextHasNoMarginBottom = false,
__filterSuggestions,
__onSuggestionClick,
__forceSuggestionFocus = false,
tokenizeOnBlur = false,
} = useDeprecated36pxDefaultSizeProp< FormTokenFieldProps >( props );

Expand Down Expand Up @@ -449,17 +452,35 @@ export function FormTokenField( props: FormTokenFieldProps ) {
speak( messages.__experimentalInvalid, 'assertive' );
return;
}

addNewTokens( [ token ] );
speak( messages.added, 'assertive' );

setIncompleteTokenValue( '' );
setSelectedSuggestionIndex( -1 );
setSelectedSuggestionScroll( false );
setIsExpanded( ! __experimentalExpandOnFocus );

if ( isActive && ! tokenizeOnBlur ) {
focus();
}

/*
* If a __filterSuggestions is provided,
* it's possible that the token has been already added.
*/
const isTokenTaken = value.some( ( item ) => {
return getTokenValue( item ) === token;
} );

__onSuggestionClick?.( token, isTokenTaken );

if ( __forceSuggestionFocus ) {
const index = getMatchingSuggestions().indexOf( token );
setSelectedSuggestionIndex( index );
setSelectedSuggestionScroll( true );
} else {
setSelectedSuggestionScroll( false );
setSelectedSuggestionIndex( -1 );
}
}

function deleteToken( token: string | TokenItem ) {
Expand Down Expand Up @@ -516,6 +537,11 @@ export function FormTokenField( props: FormTokenFieldProps ) {
_suggestions = startsWithMatch.concat( containsMatch );
}

// Apply custom filter if provided.
if ( __filterSuggestions ) {
_suggestions = __filterSuggestions( _suggestions, match );
}

return _suggestions.slice( 0, _maxSuggestions );
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
*/
import type { Meta, StoryFn } from '@storybook/react';
import type { ComponentProps } from 'react';
import styled from '@emotion/styled';

/**
* WordPress dependencies
*/
Expand All @@ -12,6 +14,8 @@ import { useState } from '@wordpress/element';
* Internal dependencies
*/
import FormTokenField from '../';
import CheckboxControl from '../../checkbox-control';
import Label from '../../input-control/label';

const meta: Meta< typeof FormTokenField > = {
component: FormTokenField,
Expand Down Expand Up @@ -135,3 +139,92 @@ WithValidatedInput.args = {
__experimentalValidateInput: ( input: string ) =>
continents.includes( input ),
};

const fruits = [
'Apple',
'Apricot',
'Avocado',
'Banana',
'Blackberry',
'Blueberry',
];

const CheckboxLabelWrapper = styled.div`
.suggestion-checkbox-label {
display: flex !important;
align-items: center;
color: inherit;
}
`;

export const WithSuggestionCheckbox: StoryFn< typeof FormTokenField > = ( {
suggestions,
...args
} ) => {
const [ selectedFruits, setSelectedFruits ] = useState<
ComponentProps< typeof FormTokenField >[ 'value' ]
>( [] );

/*
* Combine the suggested fruits with
*/
let allFruits = suggestions ? [ ...suggestions ] : [];

if ( selectedFruits ) {
allFruits = allFruits.concat(
selectedFruits.map( ( fruit ) => String( fruit ) )
);

// Remove duplicates
allFruits = [ ...new Set( allFruits ) ];

// Sort the values
allFruits.sort();
}

return (
<FormTokenField
{ ...args }
value={ selectedFruits }
suggestions={ allFruits }
onChange={ setSelectedFruits }
__filterSuggestions={ ( _filteredSuggestions, value ) => {
return allFruits.filter( ( suggestion ) =>
suggestion.toLowerCase().includes( value.toLowerCase() )
);
} }
__onSuggestionClick={ ( suggestion, isSuggestionTaken ) => {
// If the suggestion is taken, filter the selected continents
if ( isSuggestionTaken ) {
const filteredContinents = selectedFruits?.filter(
( continent ) => continent !== suggestion
);
setSelectedFruits( filteredContinents );
}
} }
__experimentalRenderItem={ ( { item } ) => {
const itemTaken = selectedFruits?.includes( item );
return (
<CheckboxLabelWrapper>
<Label className="suggestion-checkbox-label">
<CheckboxControl
checked={ itemTaken }
onChange={ () => {} }
/>
{ item }
</Label>
</CheckboxLabelWrapper>
);
} }
/>
);
};

WithSuggestionCheckbox.args = {
label: 'Pick or create a fruit',
suggestions: fruits,
__nextHasNoMarginBottom: true,
__experimentalExpandOnFocus: true,
__experimentalAutoSelectFirstMatch: true,
__forceSuggestionFocus: true,
};
21 changes: 21 additions & 0 deletions packages/components/src/form-token-field/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,27 @@ export interface FormTokenFieldProps
* @default false
*/
__nextHasNoMarginBottom?: boolean;

/**
* Use this prop to filter the suggestions list.
* It receives the list of suggestions and the current input value.
* It should return a filtered list of suggestions.
*/
__filterSuggestions?: ( suggestions: string[], value: string ) => string[];

/**
* Callback to be called when a suggestion is clicked.
*/
__onSuggestionClick?: (
suggestion: string,
isSuggestionTaken: boolean
) => void;

/**
* If true, the suggestion item will be focused when the suggestions list is opened.
*/
__forceSuggestionFocus?: boolean;

/**
* If true, add any incompleteTokenValue as a new token when the field loses focus.
*
Expand Down
Loading