Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set selection after Transforms.insertNodes() in Slate JS

Tags:

slatejs

I am trying to add a new line right below current selection, then put the selection to the new line.

let current_path = props.selection.anchor.path[0]
Transforms.insertNodes(editor, {type:'line', children:[{ text:'' }]},{at: [current_path+1]});
const point = { anchor: { path: [current_path+1, 0], offset: 0 }, focus: { path: [current_path+1, 0], offset: 0 }}
// set focus
ReactEditor.focus(editor);
// set selection
Transforms.select(editor, point);

But this came up with an error: Error: Cannot resolve a DOM node from Slate node: {"text":""}. Does anyone know how to solve it or have other way to realize it? Thanks!

like image 500
Yuqin Xu Avatar asked Jun 18 '20 11:06

Yuqin Xu


1 Answers

I stumble into the problem and found the answer. You'll need to save the selection, then use Transform.select to restore it.

For example

import { Transforms } from "slate";


// clone to store selection
const previousSelection = Object.assign({}, editor.selection);

// restore selection
Transform.select(editor, previousSelection)

like image 147
Hieu Nguyen Avatar answered Nov 12 '22 15:11

Hieu Nguyen