From 6e0799010cb34664d8a160f633742f41b2b41731 Mon Sep 17 00:00:00 2001 From: Soreine Date: Thu, 27 Oct 2016 14:35:52 +0200 Subject: [PATCH] Add transform `wrapBlockByKey`, to wrap any node This can be used to simply wrap a Text node. This is not possible with the current implementation of `wrapBlockAtRange`, which wraps the closest parent block of the text node. --- src/transforms/by-key.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/src/transforms/by-key.js b/src/transforms/by-key.js index 852652ba4..a272446ed 100644 --- a/src/transforms/by-key.js +++ b/src/transforms/by-key.js @@ -363,3 +363,28 @@ export function unwrapBlockByKey(transform, key, properties, options) { const range = selection.moveToRangeOf(texts.first(), texts.last()) return transform.unwrapBlockAtRange(range, properties, options) } + +/** + * Wrap a node in a block with `properties`. + * + * @param {Transform} transform + * @param {String} key The node to wrap + * @param {Block || Object || String} block The wrapping block (its children are discarded) + * @param {Object} options + * @param {Boolean} normalize + * @return {Transform} + */ + +export function wrapBlockByKey(transform, key, block, options) { + block = Normalize.block(block) + block = block.merge({ nodes: block.nodes.clear() }) + + const { document } = transform.state + const node = document.assertDescendant(key) + const parent = document.getParent(node) + const index = parent.nodes.indexOf(node) + + return transform + .insertNodeByKey(parent.key, index, block, { normalize: false }) + .moveNodeByKey(node.key, block.key, 0, options) +}