UNPKG

1.53 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @format
8 *
9 * @emails oncall+draft_js
10 */
11'use strict';
12
13var Immutable = require("immutable");
14
15var insertIntoList = require("./insertIntoList");
16
17var invariant = require("fbjs/lib/invariant");
18
19var Repeat = Immutable.Repeat;
20
21function insertTextIntoContentState(contentState, selectionState, text, characterMetadata) {
22 !selectionState.isCollapsed() ? process.env.NODE_ENV !== "production" ? invariant(false, '`insertText` should only be called with a collapsed range.') : invariant(false) : void 0;
23 var len = null;
24
25 if (text != null) {
26 len = text.length;
27 }
28
29 if (len == null || len === 0) {
30 return contentState;
31 }
32
33 var blockMap = contentState.getBlockMap();
34 var key = selectionState.getStartKey();
35 var offset = selectionState.getStartOffset();
36 var block = blockMap.get(key);
37 var blockText = block.getText();
38 var newBlock = block.merge({
39 text: blockText.slice(0, offset) + text + blockText.slice(offset, block.getLength()),
40 characterList: insertIntoList(block.getCharacterList(), Repeat(characterMetadata, len).toList(), offset)
41 });
42 var newOffset = offset + len;
43 return contentState.merge({
44 blockMap: blockMap.set(key, newBlock),
45 selectionAfter: selectionState.merge({
46 anchorOffset: newOffset,
47 focusOffset: newOffset
48 })
49 });
50}
51
52module.exports = insertTextIntoContentState;
\No newline at end of file