diff --git a/src/models/node.js b/src/models/node.js index cba45b4e7..9fc71ab71 100644 --- a/src/models/node.js +++ b/src/models/node.js @@ -975,38 +975,38 @@ const Node = { }, /** - * Join a node by `key` with another `withKey`. - * It brings Node after Node + * Join a children node `first` with another children node `second`. + * `first` and `second` will be concatenated in that order. + * `first` and `second` must be two Nodes or two Text. * - * @param {String} key - * @param {String} withKey + * @param {Node} first + * @param {Node} second * @return {Node} */ - joinNode(key, withKey) { + joinNode(first, second) { let node = this - let target = node.assertPath(key) - let withTarget = node.assertPath(withKey) - let parent = node.getParent(target) + let parent = node.getParent(second) const isParent = node == parent - const index = parent.nodes.indexOf(target) + const index = parent.nodes.indexOf(second) - if (target.kind == 'text') { - let { characters } = withTarget - characters = characters.concat(target.characters) - withTarget = withTarget.merge({ characters }) + if (second.kind == 'text') { + let { characters } = first + characters = characters.concat(second.characters) + first = first.merge({ characters }) } else { - const size = withTarget.nodes.size - target.nodes.forEach((child, i) => { - withTarget = withTarget.insertNode(size + i, child) + const size = first.nodes.size + second.nodes.forEach((child, i) => { + first = first.insertNode(size + i, child) }) } parent = parent.removeNode(index) node = isParent ? parent : node.updateDescendant(parent) - node = node.updateDescendant(withTarget) + console.log(node) + node = node.updateDescendant(first) return node }, diff --git a/src/transforms/apply-operation.js b/src/transforms/apply-operation.js index 6d99f6e0c..32720c0c4 100644 --- a/src/transforms/apply-operation.js +++ b/src/transforms/apply-operation.js @@ -136,9 +136,32 @@ function insertText(state, operation) { function joinNode(state, operation) { const { path, withPath } = operation - let { document } = state - document = document.joinNode(path, withPath) - state = state.merge({ document }) + let { document, selection } = state + const first = document.assertPath(withPath) + const second = document.assertPath(path) + + // Update doc + document = document.joinNode(first, second) + + // Update selection + // When merging two texts together + if (second.kind == 'text') { + // The final key is the `first` key + if (selection.anchorKey == second.key) { + selection = selection.merge({ + anchorKey: first.key, + anchorOffset: selection.anchorOffset + first.characters.size + }) + } + if (selection.focusKey == second.key) { + selection = selection.merge({ + focusKey: first.key, + focusOffset: selection.focusOffset + first.characters.size + }) + } + } + + state = state.merge({ document, selection }) return state }