From 11b2a9efbd0687f09bf2d846f8aeb5ee48f596b7 Mon Sep 17 00:00:00 2001 From: Brandon Payton Date: Sun, 8 Apr 2018 15:15:14 -0700 Subject: [PATCH] Add shared blocks to block completer --- edit-post/hooks/autocompleters/index.js | 44 +++++++++++++++++++++++++ edit-post/hooks/index.js | 1 + 2 files changed, 45 insertions(+) create mode 100644 edit-post/hooks/autocompleters/index.js diff --git a/edit-post/hooks/autocompleters/index.js b/edit-post/hooks/autocompleters/index.js new file mode 100644 index 0000000000000..ce655c5c39cfb --- /dev/null +++ b/edit-post/hooks/autocompleters/index.js @@ -0,0 +1,44 @@ +/** + * WordPress dependencies. + */ +import { addFilter } from '@wordpress/hooks'; +import { select } from '@wordpress/data'; +import { createBlock } from '@wordpress/blocks'; + +// Export for unit test +export function getBlockOptions( query ) { + const editor = select( 'core/editor' ); + const isInitialQuery = ! query; + + // TODO: Fetch reusable blocks if necessary (they aren't fetched initially) + return isInitialQuery ? + // Before we have a query, offer frecent blocks as a sensible default. + editor.getFrecentInserterItems() : + editor.getInserterItems(); +} + +// Export for unit test +export function getBlockCompletion( inserterItem ) { + const { name, initialAttributes } = inserterItem; + return { + action: 'replace', + value: createBlock( name, initialAttributes ), + }; +} + +// Export for unit test +export function addReusableBlocksCompletion( completers ) { + const blocksCompleter = completers.find( c => 'blocks' === c.name ); + if ( blocksCompleter ) { + blocksCompleter.options = getBlockOptions; + blocksCompleter.getOptionCompletion = getBlockCompletion; + } + + return completers; +} + +addFilter( + 'blocks.Autocomplete.completers', + 'core/edit-post/autocompleters/shared-blocks', + addReusableBlocksCompletion +); diff --git a/edit-post/hooks/index.js b/edit-post/hooks/index.js index 4025e1ac47617..f39faa54dd700 100644 --- a/edit-post/hooks/index.js +++ b/edit-post/hooks/index.js @@ -4,3 +4,4 @@ import './blocks'; import './more-menu'; import './validate-use-once'; +import './autocompleters';