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

2

10

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
Thad answered 26/10, 2017 at 23:41 Comment(0)
A
5

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.

Amata answered 28/10, 2017 at 3:2 Comment(6)
What is a block key and where do you get it?Mismatch
draftjs.org/docs/api-reference-content-blockAmata
Thanks! I think the order is wrong though, it should be anchorOffset for the start and focusOffset for the end.Snowfall
@BertrandBordage that's the same range.Amata
@Jiang YD Yes, but in the opposite direction, which leads to unwanted behaviour when you use the selection.Snowfall
interesting... how replace a range acting different?Amata
T
1

I changed my mind. My solution is

  1. Save the old editorState first.

  2. Then insert to the current editorState.

  3. When I want to insert another one, instead of insert to the current editorState, I insert to the copy of the old editorState again.

Hopefully, this can give someone who have the same question some ideas.

Thad answered 27/10, 2017 at 2:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.