MCPcopy Create free account
hub / github.com/SamyPesse/draft-js-code / insertNewLine

Function insertNewLine

lib/utils/insertNewLine.js:14–62  ·  view source on GitHub ↗

* Insert a new line with right inden * * @param {SyntheticKeyboardEvent} event * @param {Draft.EditorState} editorState * @return {Draft.EditorState}

(editorState)

Source from the content-addressed store, hash-verified

12 * @return {Draft.EditorState}
13 */
14function insertNewLine(editorState) {
15 var contentState = editorState.getCurrentContent();
16 var selection = editorState.getSelection();
17 var startKey = selection.getStartKey();
18 var startOffset = selection.getStartOffset();
19 var currentBlock = contentState.getBlockForKey(startKey);
20 var blockText = currentBlock.getText();
21
22 var newContentState;
23
24 // Detect newline separation
25 var newLine = getNewLine(blockText);
26
27 // Add or replace
28 if (selection.isCollapsed()) {
29 // Create line to insert with right indentation
30 var lines = getLines(blockText, newLine);
31 var currentLineIndex = getLineAnchorForOffset(
32 blockText,
33 startOffset,
34 newLine
35 ).getLine();
36 var currentLine = lines.get(currentLineIndex);
37 var lineToInsert = newLine + getIndentForLine(currentLine);
38
39 newContentState = Draft.Modifier.insertText(
40 contentState,
41 selection,
42 lineToInsert
43 );
44 } else {
45 newContentState = Draft.Modifier.replaceText(
46 contentState,
47 selection,
48 newLine
49 );
50 }
51
52 var newEditorState = Draft.EditorState.push(
53 editorState,
54 newContentState,
55 'insert-characters'
56 );
57
58 return Draft.EditorState.forceSelection(
59 newEditorState,
60 newContentState.getSelectionAfter()
61 );
62}
63
64module.exports = insertNewLine;

Callers 1

handleReturnFunction · 0.85

Calls 4

getNewLineFunction · 0.85
getLinesFunction · 0.85
getLineAnchorForOffsetFunction · 0.85
getIndentForLineFunction · 0.85

Tested by

no test coverage detected