Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a selection based on start and end in Draft.js?

I am trying to replace the last insert in Draft.js

For example,

Orignal string -> aaazzz

After inserting 'bbb' in the middle -> aaabbbzzz

Replace last insert by 'ccc' -> aaaccczzz

Replace last insert by 'ddd' -> aaadddzzz

...

One way I thought is saving the insert start point. After inserting, save the end point. Then I can replace the range later

This is my inserting code

const selection1 = editorState.getSelection();
const contentState1 = editorState.getCurrentContent();

const contentState2 = Modifier.insertText(contentState, selection, text);
const editorState2 = EditorState.push(editorState, newContentState);
const selection2 = newEditorState.getSelection();
// here I don't know how to get the range based on selection1 and selection2

I can use

const start = selection1.getStartOffset();
const end = selection2.getEndOffset();

to get two numbers which are start and end points.

Based on the definition of

replaceText(
  contentState: ContentState,
  rangeToReplace: SelectionState,
  text: string,
  inlineStyle?: DraftInlineStyle,
  entityKey?: ?string
): ContentState

I need get a new selection. How to create the selection using those two numbers OR selection1 and selection2? Is there any function like

createSelection(start, end)  // not exist
like image 722
Hongbo Miao Avatar asked Oct 26 '17 23:10

Hongbo Miao


People also ask

What is EditorState?

EditorState is the top-level state object for the editor. It is an Immutable Record that represents the entire state of a Draft editor, including: The current text content state. The current selection state. The fully decorated representation of the contents.

How does draft work Javascript?

To be efficient, Draft. js organizes set of consecutive characters w/ same styles(or same set of styles) in a single object called inlineStyleRanges. To be clear, this is ONLY organized like this in the “convertToRaw” output (for brevity). In actual contentState it is stored the long way for each character.

How do I save Draftjs content?

Draft. js comes with convertToRaw method that takes in a ContentState object and returns the given ContentState as a raw javascript object. This object can then be stored to a database or wherever you need to store your application's data.


1 Answers

the doc says:

var selectionState = SelectionState.createEmpty('blockkey');
var updatedSelection = selectionState.merge({
  focusOffset: 0,
  anchorOffset:20,
});

so you need to get the block key then set offset. the start/end correspond to anchor/focus because in your situation.

like image 186
Jiang YD Avatar answered Oct 08 '22 23:10

Jiang YD