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

Block Editor: Improve the way terms are matched in the block inserter #19122

Merged
merged 3 commits into from
Dec 17, 2019
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
63 changes: 8 additions & 55 deletions packages/block-editor/src/components/inserter/menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,14 @@
*/
import {
filter,
find,
findIndex,
flow,
groupBy,
isEmpty,
map,
some,
sortBy,
without,
includes,
deburr,
} from 'lodash';
import scrollIntoView from 'dom-scroll-into-view';
import classnames from 'classnames';
Expand All @@ -34,7 +31,6 @@ import {
Tip,
} from '@wordpress/components';
import {
getCategories,
isReusableBlock,
createBlock,
isUnmodifiedDefaultBlock,
Expand All @@ -54,57 +50,12 @@ import BlockTypesList from '../block-types-list';
import BlockCard from '../block-card';
import ChildBlocks from './child-blocks';
import __experimentalInserterMenuExtension from '../inserter-menu-extension';
import { searchItems } from './search-items';

const MAX_SUGGESTED_ITEMS = 9;

const stopKeyPropagation = ( event ) => event.stopPropagation();

/**
* Filters an item list given a search term.
*
* @param {Array} items Item list
* @param {string} searchTerm Search term.
*
* @return {Array} Filtered item list.
*/
export const searchItems = ( items, searchTerm ) => {
const normalizedSearchTerm = normalizeTerm( searchTerm );
const matchSearch = ( string ) => normalizeTerm( string ).indexOf( normalizedSearchTerm ) !== -1;
const categories = getCategories();

return items.filter( ( item ) => {
const itemCategory = find( categories, { slug: item.category } );
return matchSearch( item.title ) || some( item.keywords, matchSearch ) || ( itemCategory && matchSearch( itemCategory.title ) );
} );
};

/**
* Converts the search term into a normalized term.
*
* @param {string} term The search term to normalize.
*
* @return {string} The normalized search term.
*/
export const normalizeTerm = ( term ) => {
// Disregard diacritics.
// Input: "média"
term = deburr( term );

// Accommodate leading slash, matching autocomplete expectations.
// Input: "/media"
term = term.replace( /^\//, '' );

// Lowercase.
// Input: "MEDIA"
term = term.toLowerCase();

// Strip leading and trailing whitespace.
// Input: " media "
term = term.trim();

return term;
};

export class InserterMenu extends Component {
constructor() {
super( ...arguments );
Expand Down Expand Up @@ -204,9 +155,9 @@ export class InserterMenu extends Component {
}

filter( filterValue = '' ) {
const { debouncedSpeak, items, rootChildBlocks } = this.props;
const { categories, debouncedSpeak, items, rootChildBlocks } = this.props;

const filteredItems = searchItems( items, filterValue );
const filteredItems = searchItems( items, categories, filterValue );

const childItems = filter( filteredItems, ( { name } ) => includes( rootChildBlocks, name ) );

Expand All @@ -219,7 +170,7 @@ export class InserterMenu extends Component {
const reusableItems = filter( filteredItems, { category: 'reusable' } );

const getCategoryIndex = ( item ) => {
return findIndex( getCategories(), ( category ) => category.slug === item.category );
return findIndex( categories, ( category ) => category.slug === item.category );
};
const itemsPerCategory = flow(
( itemList ) => filter( itemList, ( item ) => item.category !== 'reusable' ),
Expand Down Expand Up @@ -261,7 +212,7 @@ export class InserterMenu extends Component {
}

render() {
const { instanceId, onSelect, rootClientId, showInserterHelpPanel } = this.props;
const { categories, instanceId, onSelect, rootClientId, showInserterHelpPanel } = this.props;
const {
childItems,
hoveredItem,
Expand Down Expand Up @@ -330,7 +281,7 @@ export class InserterMenu extends Component {
</PanelBody>
}

{ map( getCategories(), ( category ) => {
{ map( categories, ( category ) => {
const categoryItems = itemsPerCategory[ category.slug ];
if ( ! categoryItems || ! categoryItems.length ) {
return null;
Expand Down Expand Up @@ -465,6 +416,7 @@ export default compose(
getSettings,
} = select( 'core/block-editor' );
const {
getCategories,
getChildBlockNames,
} = select( 'core/blocks' );

Expand All @@ -483,6 +435,7 @@ export default compose(
} = getSettings();

return {
categories: getCategories(),
rootChildBlocks: getChildBlockNames( destinationRootBlockName ),
items: getInserterItems( destinationRootClientId ),
showInserterHelpPanel: showInserterHelpPanel && showInserterHelpPanelSetting,
Expand Down
86 changes: 86 additions & 0 deletions packages/block-editor/src/components/inserter/search-items.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/**
* External dependencies
*/
import {
deburr,
differenceWith,
find,
get,
words,
} from 'lodash';

/**
* Converts the search term into a list of normalized terms.
*
* @param {string} term The search term to normalize.
*
* @return {string[]} The normalized list of search terms.
*/
export const normalizeSearchTerm = ( term = '' ) => {
// Disregard diacritics.
// Input: "média"
term = deburr( term );

// Accommodate leading slash, matching autocomplete expectations.
// Input: "/media"
term = term.replace( /^\//, '' );

// Lowercase.
// Input: "MEDIA"
term = term.toLowerCase();

// Extract words.
return words( term );
};

const removeMatchingTerms = ( unmatchedTerms, unprocessedTerms ) => {
return differenceWith(
unmatchedTerms,
normalizeSearchTerm( unprocessedTerms ),
( unmatchedTerm, unprocessedTerm ) => unprocessedTerm.includes( unmatchedTerm )
);
};

/**
* Filters an item list given a search term.
*
* @param {Array} items Item list
* @param {Array} categories Available categories.
* @param {string} searchTerm Search term.
*
* @return {Array} Filtered item list.
*/
export const searchItems = ( items, categories, searchTerm ) => {
const normalizedTerms = normalizeSearchTerm( searchTerm );

if ( normalizedTerms.length === 0 ) {
return items;
}

return items.filter( ( { title, category, keywords = [] } ) => {
let unmatchedTerms = removeMatchingTerms(
normalizedTerms,
title
);

if ( unmatchedTerms.length === 0 ) {
return true;
}

unmatchedTerms = removeMatchingTerms(
unmatchedTerms,
keywords.join( ' ' ),
);

if ( unmatchedTerms.length === 0 ) {
return true;
}

unmatchedTerms = removeMatchingTerms(
unmatchedTerms,
get( find( categories, { slug: category } ), [ 'title' ] ),
);

return unmatchedTerms.length === 0;
} );
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
export const categories = [
{ slug: 'common', title: 'Common Blocks' },
{ slug: 'formatting', title: 'Formatting' },
{ slug: 'layout', title: 'Layout Elements' },
{ slug: 'widgets', title: 'Widgets' },
{ slug: 'embed', title: 'Embeds' },
{ slug: 'reusable', title: 'Reusable Blocks' },
];

export const textItem = {
id: 'core/text-block',
name: 'core/text-block',
initialAttributes: {},
title: 'Text',
category: 'common',
isDisabled: false,
utility: 1,
};

export const advancedTextItem = {
id: 'core/advanced-text-block',
name: 'core/advanced-text-block',
initialAttributes: {},
title: 'Advanced Text',
category: 'common',
isDisabled: false,
utility: 1,
};

export const someOtherItem = {
id: 'core/some-other-block',
name: 'core/some-other-block',
initialAttributes: {},
title: 'Some Other Block',
category: 'common',
isDisabled: false,
utility: 1,
};

export const moreItem = {
id: 'core/more-block',
name: 'core/more-block',
initialAttributes: {},
title: 'More',
category: 'layout',
isDisabled: true,
utility: 0,
};

export const youtubeItem = {
id: 'core-embed/youtube',
name: 'core-embed/youtube',
initialAttributes: {},
title: 'YouTube',
category: 'embed',
keywords: [ 'google', 'video' ],
isDisabled: false,
utility: 0,
};

export const textEmbedItem = {
id: 'core-embed/a-text-embed',
name: 'core-embed/a-text-embed',
initialAttributes: {},
title: 'A Text Embed',
category: 'embed',
isDisabled: false,
utility: 0,
};

export const reusableItem = {
id: 'core/block/123',
name: 'core/block',
initialAttributes: { ref: 123 },
title: 'My reusable block',
category: 'reusable',
isDisabled: false,
utility: 0,
};

export default [
textItem,
advancedTextItem,
someOtherItem,
moreItem,
youtubeItem,
textEmbedItem,
reusableItem,
];
Loading