10

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!

Yuqin Xu
  • 187
  • 1
  • 7

2 Answers2

2

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)

Hieu Nguyen
  • 474
  • 1
  • 5
  • 21
1

I had to look at parent to increment position and then focus. My original code was almost exactly the same as the OP's. The important difference here is switching to use Path.parent. My implementation is for handling Enter for paragraph and Enter+Shift for <br> (that branch is under construction).

if (event.key === 'Enter' && editor.selection?.anchor?.path) {
  event.preventDefault();
  if (!event.shiftKey) {
    const anchorAndFocus = {
      offset: 0,
      path: [Path.parent(editor.selection.anchor.path)[0] + 1, 0],
    };
    const selection = { anchor: anchorAndFocus, focus: anchorAndFocus } as Location;
    Transforms.insertNodes(editor, { type: 'paragraph', children: [{ text: '' }] });
    Transforms.select(editor, selection);
  } // else want a break tag...
}

A week later of SlateJS work I found there's a flag select for insertNodes options, so you could consolidate the last two lines above to something like:

Transforms.insertNodes(
  editor, 
  { type: 'paragraph', children: [{ text: '' }] },
  { at: selection, select: true }
);
Neil Gaetano Lindberg
  • 2,488
  • 26
  • 23