Insert tab character into SlateJS text editor

1k views Asked by At

How to insert tab characters into SlateJS?

So inserting   is a tab character, however, when inserting this as text, it appears as the literal characters   not the text with a tab spacing.

// Don't work, inserts literal characters
const insertText = (editor, format) => {
    Editor.insertText(editor, ` ')
}

Is there any simple way to insert a   and have Slatejs recognise it as the html, not as pure text?

Based on my rough understanding, it might be I'll need to serialise and deserialise html before inserting it. Maybe even inserting <pre> </pre> blocks with the spacing included.

2

There are 2 answers

0
wanna_coder101 On BEST ANSWER

Just dawned on me I could insert 4 spaces instead of a tab character... Although, this isn't perfect, you have to backspace 4 times instead of a single time like tabs.

const insertText = (editor, format) => {
    Editor.insertText(editor, '    ')
}

Could also insert tab space characters in the insert text, like the tabs in this article, can't copy paste their tabs as SO turns it into spaces. Seems to work perfectly fine, functionally a tab space.

0
Mengo On

You can use unicode convert to string. You can use horizontal tab &#9; as well. https://www.w3.org/MarkUp/html3/specialchars.html

Editor.insertText(editor, '\u2003'.toString()) // &emsp;
Editor.insertText(editor, '\u0009'.toString()) // &#9;

If you want to wrap it in a span, ie render as <span style={{whiteSpace: "pre"}}>&#9;</span> you can do so with marks.

renderLeaf={props => {
  const leafStyle = props.leaf.pre && {whiteSpace: "pre"}
  return <span style={leafStyle}>{children}</span>
}}

Editor.insertNodes(editor, {
  text: '\u0009'.toString(),
  pre: true
})