@wordpress/blocks
Version:
Block API for WordPress.
1,026 lines (617 loc) • 26.6 kB
Markdown
# Blocks
"Block" is the abstract term used to describe units of markup that, composed together, form the content or layout of a webpage. The idea combines concepts of what in WordPress today we achieve with shortcodes, custom HTML, and embed discovery into a single consistent API and user experience.
For more context, refer to [_What Are Little Blocks Made Of?_](https://make.wordpress.org/design/2017/01/25/what-are-little-blocks-made-of/) from the [Make WordPress Design](https://make.wordpress.org/design/) blog.
<div class="callout callout-alert">
<a href="https://developer.wordpress.org/block-editor/getting-started/create-block/">Learn how to create your first block</a> for the WordPress block editor. From setting up your development environment, tools, and getting comfortable with the new development model, this tutorial covers all you need to know to get started with creating blocks.
</div>
## Installation
Install the module
```bash
npm install @wordpress/blocks --save
```
_This package assumes that your code will run in an **ES2015+** environment. If you're using an environment that has limited or no support for such language features and APIs, you should include [the polyfill shipped in `@wordpress/babel-preset-default`](https://github.com/WordPress/gutenberg/tree/HEAD/packages/babel-preset-default#polyfill) in your code._
## API
<!-- START TOKEN(Autogenerated API docs) -->
### cloneBlock
Given a block object, returns a copy of the block object, optionally merging new attributes and/or replacing its inner blocks.
_Parameters_
- _block_ `Object`: Block instance.
- _mergeAttributes_ `Object`: Block attributes.
- _newInnerBlocks_ `?Array`: Nested blocks.
_Returns_
- `Object`: A cloned block.
### createBlock
Returns a block object given its type and attributes.
_Parameters_
- _name_ `string`: Block name.
- _attributes_ `Object`: Block attributes.
- _innerBlocks_ `?Array`: Nested blocks.
_Returns_
- `Object`: Block object.
### createBlocksFromInnerBlocksTemplate
Given an array of InnerBlocks templates or Block Objects, returns an array of created Blocks from them. It handles the case of having InnerBlocks as Blocks by converting them to the proper format to continue recursively.
_Parameters_
- _innerBlocksOrTemplate_ `Array`: Nested blocks or InnerBlocks templates.
_Returns_
- `Object[]`: Array of Block objects.
### doBlocksMatchTemplate
Checks whether a list of blocks matches a template by comparing the block names.
_Parameters_
- _blocks_ `Array`: Block list.
- _template_ `Array`: Block template.
_Returns_
- `boolean`: Whether the list of blocks matches a templates.
### findTransform
Given an array of transforms, returns the highest-priority transform where the predicate function returns a truthy value. A higher-priority transform is one with a lower priority value (i.e. first in priority order). Returns null if the transforms set is empty or the predicate function returns a falsey value for all entries.
_Parameters_
- _transforms_ `Object[]`: Transforms to search.
- _predicate_ `Function`: Function returning true on matching transform.
_Returns_
- `?Object`: Highest-priority transform candidate.
### getBlockAttributes
Returns the block attributes of a registered block node given its type.
_Parameters_
- _blockTypeOrName_ `string|Object`: Block type or name.
- _innerHTML_ `string|Node`: Raw block content.
- _attributes_ `?Object`: Known block attributes (from delimiters).
_Returns_
- `Object`: All block attributes.
### getBlockAttributesNamesByRole
Filter block attributes by `role` and return their names.
_Parameters_
- _name_ `string`: Block attribute's name.
- _role_ `string`: The role of a block attribute.
_Returns_
- `string[]`: The attribute names that have the provided role.
### getBlockBindingsSource
Returns a registered block bindings source by its name.
_Parameters_
- _name_ `string`: Block bindings source name.
_Returns_
- `?Object`: Block bindings source.
_Changelog_
`6.7.0` Introduced in WordPress core.
### getBlockBindingsSources
Returns all registered block bindings sources.
_Returns_
- `Array`: Block bindings sources.
_Changelog_
`6.7.0` Introduced in WordPress core.
### getBlockContent
Given a block object, returns the Block's Inner HTML markup.
_Parameters_
- _block_ `Object`: Block instance.
_Returns_
- `string`: HTML.
### getBlockDefaultClassName
Returns the block's default classname from its name.
_Parameters_
- _blockName_ `string`: The block name.
_Returns_
- `string`: The block's default class.
### getBlockFromExample
Create a block object from the example API.
_Parameters_
- _name_ `string`:
- _example_ `Object`:
_Returns_
- `Object`: block.
### getBlockMenuDefaultClassName
Returns the block's default menu item classname from its name.
_Parameters_
- _blockName_ `string`: The block name.
_Returns_
- `string`: The block's default menu item class.
### getBlockSupport
Returns the block support value for a feature, if defined.
_Parameters_
- _nameOrType_ `(string|Object)`: Block name or type object
- _feature_ `string`: Feature to retrieve
- _defaultSupports_ `*`: Default value to return if not explicitly defined
_Returns_
- `?*`: Block support value
### getBlockTransforms
Returns normal block transforms for a given transform direction, optionally for a specific block by name, or an empty array if there are no transforms. If no block name is provided, returns transforms for all blocks. A normal transform object includes `blockName` as a property.
_Parameters_
- _direction_ `string`: Transform direction ("to", "from").
- _blockTypeOrName_ `string|Object`: Block type or name.
_Returns_
- `Array`: Block transforms for direction.
### getBlockType
Returns a registered block type.
_Parameters_
- _name_ `string`: Block name.
_Returns_
- `?Object`: Block type.
### getBlockTypes
Returns all registered blocks.
_Returns_
- `Array`: Block settings.
### getChildBlockNames
Returns an array with the child blocks of a given block.
_Parameters_
- _blockName_ `string`: Name of block (example: “latest-posts”).
_Returns_
- `Array`: Array of child block names.
### getDefaultBlockName
Retrieves the default block name.
_Returns_
- `?string`: Block name.
### getFreeformContentHandlerName
Retrieves name of block handling non-block content, or undefined if no handler has been defined.
_Returns_
- `?string`: Block name.
### getGroupingBlockName
Retrieves name of block used for handling grouping interactions.
_Returns_
- `?string`: Block name.
### getPhrasingContentSchema
Undocumented declaration.
### getPossibleBlockTransformations
Returns an array of block types that the set of blocks received as argument can be transformed into.
_Parameters_
- _blocks_ `Array`: Blocks array.
_Returns_
- `Array`: Block types that the blocks argument can be transformed to.
### getSaveContent
Given a block type containing a save render implementation and attributes, returns the static markup to be saved.
_Parameters_
- _blockTypeOrName_ `string|Object`: Block type or name.
- _attributes_ `Object`: Block attributes.
- _innerBlocks_ `?Array`: Nested blocks.
_Returns_
- `string`: Save content.
### getSaveElement
Given a block type containing a save render implementation and attributes, returns the enhanced element to be saved or string when raw HTML expected.
_Parameters_
- _blockTypeOrName_ `string|Object`: Block type or name.
- _attributes_ `Object`: Block attributes.
- _innerBlocks_ `?Array`: Nested blocks.
_Returns_
- `Object|string`: Save element or raw HTML string.
### getUnregisteredTypeHandlerName
Retrieves name of block handling unregistered block types, or undefined if no handler has been defined.
_Returns_
- `?string`: Block name.
### hasBlockSupport
Returns true if the block defines support for a feature, or false otherwise.
_Parameters_
- _nameOrType_ `(string|Object)`: Block name or type object.
- _feature_ `string`: Feature to test.
- _defaultSupports_ `boolean`: Whether feature is supported by default if not explicitly defined.
_Returns_
- `boolean`: Whether block supports feature.
### hasChildBlocks
Returns a boolean indicating if a block has child blocks or not.
_Parameters_
- _blockName_ `string`: Name of block (example: “latest-posts”).
_Returns_
- `boolean`: True if a block contains child blocks and false otherwise.
### hasChildBlocksWithInserterSupport
Returns a boolean indicating if a block has at least one child block with inserter support.
_Parameters_
- _blockName_ `string`: Block type name.
_Returns_
- `boolean`: True if a block contains at least one child blocks with inserter support and false otherwise.
### isReusableBlock
Determines whether or not the given block is a reusable block. This is a special block type that is used to point to a global block stored via the API.
_Parameters_
- _blockOrType_ `Object`: Block or Block Type to test.
_Returns_
- `boolean`: Whether the given block is a reusable block.
### isTemplatePart
Determines whether or not the given block is a template part. This is a special block type that allows composing a page template out of reusable design elements.
_Parameters_
- _blockOrType_ `Object`: Block or Block Type to test.
_Returns_
- `boolean`: Whether the given block is a template part.
### isUnmodifiedBlock
Determines whether the block's attributes are equal to the default attributes which means the block is unmodified.
_Parameters_
- _block_ `WPBlock`: Block Object.
- _role_ `?string`: Optional role to filter attributes for modification check.
_Returns_
- `boolean`: Whether the block is an unmodified block.
### isUnmodifiedDefaultBlock
Determines whether the block is a default block and its attributes are equal to the default attributes which means the block is unmodified.
_Parameters_
- _block_ `WPBlock`: Block Object
- _role_ `?string`: Optional role to filter attributes for modification check.
_Returns_
- `boolean`: Whether the block is an unmodified default block.
### isValidBlockContent
> **Deprecated** Use validateBlock instead to avoid data loss.
Returns true if the parsed block is valid given the input content. A block is considered valid if, when serialized with assumed attributes, the content matches the original value.
Logs to console in development environments when invalid.
_Parameters_
- _blockTypeOrName_ `string|Object`: Block type.
- _attributes_ `Object`: Parsed block attributes.
- _originalBlockContent_ `string`: Original block content.
_Returns_
- `boolean`: Whether block is valid.
### isValidIcon
Function that checks if the parameter is a valid icon.
_Parameters_
- _icon_ `*`: Parameter to be checked.
_Returns_
- `boolean`: True if the parameter is a valid icon and false otherwise.
### normalizeIconObject
Function that receives an icon as set by the blocks during the registration and returns a new icon object that is normalized so we can rely on just on possible icon structure in the codebase.
_Parameters_
- _icon_ `WPBlockTypeIconRender`: Render behavior of a block type icon; one of a Dashicon slug, an element, or a component.
_Returns_
- `WPBlockTypeIconDescriptor`: Object describing the icon.
### parse
Utilizes an optimized token-driven parser based on the Gutenberg grammar spec defined through a parsing expression grammar to take advantage of the regular cadence provided by block delimiters -- composed syntactically through HTML comments -- which, given a general HTML document as an input, returns a block list array representation.
This is a recursive-descent parser that scans linearly once through the input document. Instead of directly recursing it utilizes a trampoline mechanism to prevent stack overflow. This initial pass is mainly interested in separating and isolating the blocks serialized in the document and manifestly not in the content within the blocks.
_Related_
- <https://developer.wordpress.org/block-editor/packages/packages-block-serialization-default-parser/>
_Parameters_
- _content_ `string`: The post content.
- _options_ `ParseOptions`: Extra options for handling block parsing.
_Returns_
- `Array`: Block list.
### parseWithAttributeSchema
Given a block's raw content and an attribute's schema returns the attribute's value depending on its source.
_Parameters_
- _innerHTML_ `string|Node`: Block's raw content.
- _attributeSchema_ `Object`: Attribute's schema.
_Returns_
- `*`: Attribute value.
### pasteHandler
Converts an HTML string to known blocks. Strips everything else.
_Parameters_
- _options_ `Object`:
- _options.HTML_ `[string]`: The HTML to convert.
- _options.plainText_ `[string]`: Plain text version.
- _options.mode_ `[string]`: Handle content as blocks or inline content. _ 'AUTO': Decide based on the content passed. _ 'INLINE': Always handle as inline content, and return string. \* 'BLOCKS': Always handle as blocks, and return array of blocks.
- _options.tagName_ `[Array]`: The tag into which content will be inserted.
_Returns_
- `Array|string`: A list of blocks or a string, depending on `handlerMode`.
### privateApis
Undocumented declaration.
### rawHandler
Converts an HTML string to known blocks.
_Parameters_
- _$1_ `Object`:
- _$1.HTML_ `string`: The HTML to convert.
_Returns_
- `Array`: A list of blocks.
### registerBlockBindingsSource
Registers a new block bindings source with an object defining its behavior. Once registered, the source is available to be connected to the supported block attributes.
_Usage_
```js
import { _x } from '@wordpress/i18n';
import { registerBlockBindingsSource } from '@wordpress/blocks';
registerBlockBindingsSource( {
name: 'plugin/my-custom-source',
label: _x( 'My Custom Source', 'block bindings source' ),
usesContext: [ 'postType' ],
getValues: getSourceValues,
setValues: updateMyCustomValuesInBatch,
canUserEditValue: () => true,
} );
```
_Parameters_
- _source_ `WPBlockBindingsSource`: Object describing a block bindings source.
_Changelog_
`6.7.0` Introduced in WordPress core.
### registerBlockCollection
Registers a new block collection to group blocks in the same namespace in the inserter.
_Usage_
```js
import { __ } from '@wordpress/i18n';
import { registerBlockCollection, registerBlockType } from '@wordpress/blocks';
// Register the collection.
registerBlockCollection( 'my-collection', {
title: __( 'Custom Collection' ),
} );
// Register a block in the same namespace to add it to the collection.
registerBlockType( 'my-collection/block-name', {
title: __( 'My First Block' ),
edit: () => <div>{ __( 'Hello from the editor!' ) }</div>,
save: () => <div>'Hello from the saved content!</div>,
} );
```
_Parameters_
- _namespace_ `string`: The namespace to group blocks by in the inserter; corresponds to the block namespace.
- _settings_ `Object`: The block collection settings.
- _settings.title_ `string`: The title to display in the block inserter.
- _settings.icon_ `[Object]`: The icon to display in the block inserter.
### registerBlockStyle
Registers a new block style for the given block types.
For more information on connecting the styles with CSS [the official documentation](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-styles/#styles).
_Usage_
```js
import { __ } from '@wordpress/i18n';
import { registerBlockStyle } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
registerBlockStyle( 'core/quote', {
name: 'fancy-quote',
label: __( 'Fancy Quote' ),
} );
} }
>
{ __( 'Add a new block style for core/quote' ) }
</Button>
);
};
```
_Parameters_
- _blockNames_ `string|Array`: Name of blocks e.g. “core/latest-posts” or `["core/group", "core/columns"]`.
- _styleVariation_ `Object`: Object containing `name` which is the class name applied to the block and `label` which identifies the variation to the user.
### registerBlockType
Registers a new block provided a unique name and an object defining its behavior. Once registered, the block is made available as an option to any editor interface where blocks are implemented.
For more in-depth information on registering a custom block see the [Create a block tutorial](https://developer.wordpress.org/block-editor/getting-started/create-block/).
_Usage_
```js
import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
registerBlockType( 'namespace/block-name', {
title: __( 'My First Block' ),
edit: () => <div>{ __( 'Hello from the editor!' ) }</div>,
save: () => <div>Hello from the saved content!</div>,
} );
```
_Parameters_
- _blockNameOrMetadata_ `string|Object`: Block type name or its metadata.
- _settings_ `Object`: Block settings.
_Returns_
- `WPBlockType | undefined`: The block, if it has been successfully registered; otherwise `undefined`.
### registerBlockVariation
Registers a new block variation for the given block type.
For more information on block variations see [the official documentation ](https://developer.wordpress.org/block-editor/reference-guides/block-api/block-variations/).
_Usage_
```js
import { __ } from '@wordpress/i18n';
import { registerBlockVariation } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
registerBlockVariation( 'core/embed', {
name: 'custom',
title: __( 'My Custom Embed' ),
attributes: { providerNameSlug: 'custom' },
} );
} }
>
__( 'Add a custom variation for core/embed' ) }
</Button>
);
};
```
_Parameters_
- _blockName_ `string`: Name of the block (example: “core/columns”).
- _variation_ `WPBlockVariation`: Object describing a block variation.
### serialize
Takes a block or set of blocks and returns the serialized post content.
_Parameters_
- _blocks_ `Array`: Block(s) to serialize.
- _options_ `WPBlockSerializationOptions`: Serialization options.
_Returns_
- `string`: The post content.
### serializeRawBlock
Serializes a block node into the native HTML-comment-powered block format. CAVEAT: This function is intended for re-serializing blocks as parsed by valid parsers and skips any validation steps. This is NOT a generic serialization function for in-memory blocks. For most purposes, see the following functions available in the `@wordpress/blocks` package:
_Related_
- serializeBlock
- serialize For more on the format of block nodes as returned by valid parsers:
- `@wordpress/block-serialization-default-parser` package
- `@wordpress/block-serialization-spec-parser` package
_Parameters_
- _rawBlock_ `WPRawBlock`: A block node as returned by a valid parser.
- _options_ `[Options]`: Serialization options.
_Returns_
- `string`: An HTML string representing a block.
### setCategories
Sets the block categories.
_Usage_
```js
import { __ } from '@wordpress/i18n';
import { store as blocksStore, setCategories } from '@wordpress/blocks';
import { useSelect } from '@wordpress/data';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
// Retrieve the list of current categories.
const blockCategories = useSelect(
( select ) => select( blocksStore ).getCategories(),
[]
);
return (
<Button
onClick={ () => {
// Add a custom category to the existing list.
setCategories( [
...blockCategories,
{ title: 'Custom Category', slug: 'custom-category' },
] );
} }
>
{ __( 'Add a new custom block category' ) }
</Button>
);
};
```
_Parameters_
- _categories_ `WPBlockCategory[]`: Block categories.
### setDefaultBlockName
Assigns the default block name.
_Usage_
```js
import { setDefaultBlockName } from '@wordpress/blocks';
const ExampleComponent = () => {
return (
<Button onClick={ () => setDefaultBlockName( 'core/heading' ) }>
{ __( 'Set the default block to Heading' ) }
</Button>
);
};
```
_Parameters_
- _name_ `string`: Block name.
### setFreeformContentHandlerName
Assigns name of block for handling non-block content.
_Parameters_
- _blockName_ `string`: Block name.
### setGroupingBlockName
Assigns name of block for handling block grouping interactions.
This function lets you select a different block to group other blocks in instead of the default `core/group` block. This function must be used in a component or when the DOM is fully loaded. See <https://developer.wordpress.org/block-editor/reference-guides/packages/packages-dom-ready/>
_Usage_
```js
import { setGroupingBlockName } from '@wordpress/blocks';
const ExampleComponent = () => {
return (
<Button onClick={ () => setGroupingBlockName( 'core/columns' ) }>
{ __( 'Wrap in columns' ) }
</Button>
);
};
```
_Parameters_
- _name_ `string`: Block name.
### setUnregisteredTypeHandlerName
Assigns name of block handling unregistered block types.
_Parameters_
- _blockName_ `string`: Block name.
### store
Store definition for the blocks namespace.
_Related_
- <https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore>
_Type_
- `Object`
### switchToBlockType
Switch one or more blocks into one or more blocks of the new block type.
_Parameters_
- _blocks_ `Array|Object`: Blocks array or block object.
- _name_ `string`: Block name.
_Returns_
- `?Array`: Array of blocks or null.
### synchronizeBlocksWithTemplate
Synchronize a block list with a block template.
Synchronizing a block list with a block template means that we loop over the blocks keep the block as is if it matches the block at the same position in the template (If it has the same name) and if doesn't match, we create a new block based on the template. Extra blocks not present in the template are removed.
_Parameters_
- _blocks_ `Array`: Block list.
- _template_ `Array`: Block template.
_Returns_
- `Array`: Updated Block list.
### unregisterBlockBindingsSource
Unregisters a block bindings source by providing its name.
_Usage_
```js
import { unregisterBlockBindingsSource } from '@wordpress/blocks';
unregisterBlockBindingsSource( 'plugin/my-custom-source' );
```
_Parameters_
- _name_ `string`: The name of the block bindings source to unregister.
_Changelog_
`6.7.0` Introduced in WordPress core.
### unregisterBlockStyle
Unregisters a block style for the given block.
_Usage_
```js
import { __ } from '@wordpress/i18n';
import { unregisterBlockStyle } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
unregisterBlockStyle( 'core/quote', 'plain' );
} }
>
{ __( 'Remove the "Plain" block style for core/quote' ) }
</Button>
);
};
```
_Parameters_
- _blockName_ `string`: Name of block (example: “core/latest-posts”).
- _styleVariationName_ `string`: Name of class applied to the block.
### unregisterBlockType
Unregisters a block.
_Usage_
```js
import { __ } from '@wordpress/i18n';
import { unregisterBlockType } from '@wordpress/blocks';
const ExampleComponent = () => {
return (
<Button
onClick={ () => unregisterBlockType( 'my-collection/block-name' ) }
>
{ __( 'Unregister my custom block.' ) }
</Button>
);
};
```
_Parameters_
- _name_ `string`: Block name.
_Returns_
- `WPBlockType | undefined`: The previous block value, if it has been successfully unregistered; otherwise `undefined`.
### unregisterBlockVariation
Unregisters a block variation defined for the given block type.
_Usage_
```js
import { __ } from '@wordpress/i18n';
import { unregisterBlockVariation } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
unregisterBlockVariation( 'core/embed', 'youtube' );
} }
>
{ __( 'Remove the YouTube variation from core/embed' ) }
</Button>
);
};
```
_Parameters_
- _blockName_ `string`: Name of the block (example: “core/columns”).
- _variationName_ `string`: Name of the variation defined for the block.
### updateCategory
Updates a category.
_Usage_
```js
import { __ } from '@wordpress/i18n';
import { updateCategory } from '@wordpress/blocks';
import { Button } from '@wordpress/components';
const ExampleComponent = () => {
return (
<Button
onClick={ () => {
updateCategory( 'text', { title: __( 'Written Word' ) } );
} }
>
{ __( 'Update Text category title' ) }
</Button>
);
};
```
_Parameters_
- _slug_ `string`: Block category slug.
- _category_ `WPBlockCategory`: Object containing the category properties that should be updated.
### validateBlock
Returns an object with `isValid` property set to `true` if the parsed block is valid given the input content. A block is considered valid if, when serialized with assumed attributes, the content matches the original value. If block is invalid, this function returns all validations issues as well.
_Parameters_
- _block_ `WPBlock`: block object.
- _blockTypeOrName_ `[WPBlockType|string]`: Block type or name, inferred from block if not given.
_Returns_
- `[boolean,Array<LoggerItem>]`: validation results.
### withBlockContentContext
> **Deprecated**
A Higher Order Component used to inject BlockContent using context to the wrapped component.
_Parameters_
- _OriginalComponent_ `Component`: The component to enhance.
_Returns_
- `Component`: The same component.
<!-- END TOKEN(Autogenerated API docs) -->
## Contributing to this package
This is an individual package that's part of the Gutenberg project. The project is organized as a monorepo. It's made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to [npm](https://www.npmjs.com/) and used by [WordPress](https://make.wordpress.org/core/) as well as other software projects.
To find out more about contributing to this package or Gutenberg as a whole, please read the project's main [contributor guide](https://github.com/WordPress/gutenberg/tree/HEAD/CONTRIBUTING.md).
<br /><br /><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>