@wordpress/blocks
Version:
Block API for WordPress.
63 lines (60 loc) • 2.26 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.htmlToBlocks = htmlToBlocks;
var _element = require("@wordpress/element");
var _factory = require("../factory");
var _parser = _interopRequireDefault(require("../parser"));
var _getBlockAttributes = require("../parser/get-block-attributes");
var _getRawTransforms = require("./get-raw-transforms");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Converts HTML directly to blocks. Looks for a matching transform for each
* top-level tag. The HTML should be filtered to not have any text between
* top-level tags and formatted in a way that blocks can handle the HTML.
*
* @param {string} html HTML to convert.
* @param {Function} handler The handler calling htmlToBlocks: either rawHandler
* or pasteHandler.
*
* @return {Array} An array of blocks.
*/
function htmlToBlocks(html, handler) {
const doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = html;
return Array.from(doc.body.children).flatMap(node => {
const rawTransform = (0, _factory.findTransform)((0, _getRawTransforms.getRawTransforms)(), ({
isMatch
}) => isMatch(node));
if (!rawTransform) {
// Until the HTML block is supported in the native version, we'll parse it
// instead of creating the block to generate it as an unsupported block.
if (_element.Platform.isNative) {
return (0, _parser.default)(`<!-- wp:html -->${node.outerHTML}<!-- /wp:html -->`);
}
return (0, _factory.createBlock)(
// Should not be hardcoded.
'core/html', (0, _getBlockAttributes.getBlockAttributes)('core/html', node.outerHTML));
}
const {
transform,
blockName
} = rawTransform;
if (transform) {
const block = transform(node, handler);
if (node.hasAttribute('class')) {
block.attributes.className = node.getAttribute('class');
}
return block;
}
return (0, _factory.createBlock)(blockName, (0, _getBlockAttributes.getBlockAttributes)(blockName, node.outerHTML));
});
}
//# sourceMappingURL=html-to-blocks.js.map