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

feat: add an AutocompleteWithSuggestions component for reusability #952

Merged
merged 8 commits into from
May 17, 2021
Merged
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
15 changes: 10 additions & 5 deletions assets/components/src/autocomplete-tokenfield/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,16 @@ class AutocompleteTokenField extends Component {
*/
getLabelsForValues( values ) {
const { validValues } = this.state;
return values.reduce(
( accumulator, value ) =>
validValues[ value ] ? [ ...accumulator, validValues[ value ] ] : accumulator,
[]
);
return values.reduce( ( accumulator, value ) => {
if ( ! value ) {
return accumulator;
}
if ( value.label ) {
return [ ...accumulator, value.label ];
}

return validValues[ value ] ? [ ...accumulator, validValues[ value ] ] : accumulator;
}, [] );
}

/**
Expand Down
83 changes: 83 additions & 0 deletions assets/components/src/autocomplete-with-suggestions/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* WordPress dependencies
*/
import { __, sprintf } from '@wordpress/i18n';
import { Button } from '@wordpress/components';
import { useEffect, useState } from '@wordpress/element';

/**
* External dependencies.
*/
import { AutocompleteTokenField } from '../';
import './style.scss';

const AutocompleteWithSuggestions = ( {
fetchSavedPosts = false,
fetchSuggestions = false,
onChange = false,
help = __( 'Begin typing search term, click autocomplete result to select.', 'newspack' ),
label = __( 'Search', 'newspack' ),
postTypeLabel = __( 'post', 'newspack' ),
selectedPost = 0,
} ) => {
const [ suggestions, setSuggestions ] = useState( [] );

/**
* Fetch recent posts to show as suggestions.
*/
useEffect( () => {
if ( fetchSuggestions ) {
fetchSuggestions().then( _suggestions => {
if ( 0 < _suggestions.length ) {
setSuggestions( _suggestions );
}
} );
}
}, [] );

/**
* Render a single suggestion object that can be clicked to select it immediately.
*
* @param {Object} suggestion Suggestion object with value and label keys.
* @param {number} index Index of this suggestion in the array.
*/
const renderSuggestion = ( suggestion, index ) => {
return (
<Button isLink key={ index } onClick={ () => onChange( [ suggestion ] ) }>
{ suggestion.label }
</Button>
);
};

/**
* Render a list of suggestions that can be clicked to select instead of searching by title.
*/
const renderSuggestions = () => {
return (
<>
<p className="newspack-autocomplete-with-suggestions__label">
{ __( 'Or, select a recent ', 'newspack' ) + sprintf( ' %s:', postTypeLabel ) }
</p>
<div className="newspack-autocomplete-with-suggestions__search-suggestions">
{ suggestions.map( renderSuggestion ) }
</div>
</>
);
};

return (
<div className="newspack-autocomplete-with-suggestions">
<AutocompleteTokenField
tokens={ [ selectedPost ] }
onChange={ onChange }
fetchSuggestions={ fetchSuggestions }
fetchSavedInfo={ postIDs => fetchSavedPosts( postIDs ) }
label={ label }
help={ help }
/>
{ 0 < suggestions.length && renderSuggestions() }
</div>
);
};

export default AutocompleteWithSuggestions;
56 changes: 56 additions & 0 deletions assets/components/src/autocomplete-with-suggestions/style.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Styles for AutocompleteWithSuggestions component.
*/

@import '../../../shared/scss/colors';
@import '~@wordpress/base-styles/colors';

.newspack-autocomplete-with-suggestions {
width: 100%;

.components-spinner {
position: absolute;
top: 2em;
right: 0;
}

.newspack-autocomplete-tokenfield__help {
font-size: 12px;
}

.components-form-token-field__suggestions-list {
margin: 4px -4px -4px;
}

.components-form-token-field__suggestion {
padding: 8px;
}

p.newspack-autocomplete-with-suggestions__label {
margin-bottom: 8px;
}

&__search-suggestions {
border-radius: 2px;
border: 1px solid $dark-gray-600;
max-height: 182px;
padding: 4px;
overflow: scroll;

.components-button {
color: $dark-gray-600;
display: block;
margin: 0;
padding: 10px 12px;
text-decoration: none;
width: 100%;

&:active:not( :disabled ),
&:hover:not( :disabled ) {
background: white;
background: var( --wp-admin-theme-color );
color: white;
}
}
}
}
1 change: 1 addition & 0 deletions assets/components/src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export { default as ActionCard } from './action-card';
export { default as AutocompleteTokenField } from './autocomplete-tokenfield';
export { default as Button } from './button';
export { default as AutocompleteWithSuggestions } from './autocomplete-with-suggestions';
export { default as ButtonGroup } from './button-group';
export { default as Card } from './card';
export { default as PreviewBox } from './preview-box';
Expand Down
53 changes: 53 additions & 0 deletions assets/wizards/componentsDemo/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import '../../shared/js/public-path';
* WordPress dependencies.
*/
import { Component, Fragment, render } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import { decodeEntities } from '@wordpress/html-entities';
import { addQueryArgs } from '@wordpress/url';
import { __ } from '@wordpress/i18n';

/**
Expand All @@ -33,6 +36,7 @@ import {
Modal,
ToggleGroup,
WebPreview,
AutocompleteWithSuggestions,
} from '../../components/src';

class ComponentsDemo extends Component {
Expand All @@ -42,6 +46,7 @@ class ComponentsDemo extends Component {
constructor() {
super( ...arguments );
this.state = {
selectedPostForAutocompleteWithSuggestions: [],
inputTextValue1: 'Input value',
inputTextValue2: '',
inputNumValue: 0,
Expand All @@ -59,6 +64,7 @@ class ComponentsDemo extends Component {
*/
render() {
const {
selectedPostForAutocompleteWithSuggestions,
inputTextValue1,
inputTextValue2,
inputNumValue,
Expand All @@ -78,6 +84,53 @@ class ComponentsDemo extends Component {
</div>
</div>
<div className="newspack-wizard newspack-wizard__content">
<Card>
<h2>{ __( 'Autocomplete with Suggestions', 'newspack' ) }</h2>
<AutocompleteWithSuggestions
label={ __( 'Search for a post', 'newspack' ) }
help={ __(
'Begin typing post title, click autocomplete result to select.',
'newspack'
) }
fetchSavedPosts={ async postIDs => {
const posts = await apiFetch( {
path: addQueryArgs( '/wp/v2/posts', {
per_page: 100,
include: postIDs.join( ',' ),
_fields: 'id,title',
} ),
} );

return posts.map( post => ( {
value: post.id,
label: decodeEntities( post.title ) || __( '(no title)', 'newspack' ),
} ) );
} }
fetchSuggestions={ async search => {
const posts = await apiFetch( {
path: addQueryArgs( '/wp/v2/posts', {
search,
per_page: 10,
_fields: 'id,title',
} ),
} );

// Format suggestions for FormTokenField display.
return posts.reduce( ( acc, post ) => {
acc.push( {
value: post.id,
label: decodeEntities( post.title.rendered ) || __( '(no title)', 'newspack' ),
} );

return acc;
}, [] );
} }
onChange={ items =>
this.setState( { selectedPostForAutocompleteWithSuggestions: items.pop() } )
}
selectedPost={ selectedPostForAutocompleteWithSuggestions }
/>
</Card>
<Card>
<h2>{ __( 'Plugin toggles' ) }</h2>
<PluginToggle
Expand Down
2 changes: 1 addition & 1 deletion includes/wizards/class-components-demo.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public function enqueue_scripts_and_styles() {
wp_enqueue_script(
'newspack-components-demo',
Newspack::plugin_url() . '/dist/componentsDemo.js',
$this->get_script_dependencies(),
$this->get_script_dependencies( [ 'wp-html-entities' ] ),
filemtime( dirname( NEWSPACK_PLUGIN_FILE ) . '/dist/componentsDemo.js' ),
true
);
Expand Down