Matt Parlane
Matt Parlane

Reputation: 473

Serializing line breaks in SlateJS

I have a basic question about SlateJS.

My serializer is very basic, similar to the example given on slatejs.org. When I enter a linebreak in my editor, a new text node is created, and the JSON representation of this node is just {text: ''}.

How am I supposed to infer that this is a linebreak?

I have tried just checking whether node.text === '', but this doesn't work because empty text nodes appear in other places, like around <a> tags.

Thanks!

This is my serialize function:

const serialize = (node) => {
  const children = node.children?.map((n) => serialize(n)).join('') || '';

  switch (node.type) {
    [... a bunch of other tags omitted ...]
    case 'br':
      return '<br>';
    default: {
      if (node?.text === '') {
        return '<br>';
      } else {
        let string = node?.text ? escapeHtml(node.text) : children;
        if (node.bold) {
          string = `<strong>${string}</strong>`;
        }
        if (node.italic) {
          string = `<em>${string}</em>`;
        }

        return string;
      }
    }
  }
};

and this is my <Slate> element:

<Slate
  editor={editor}
  initialValue={initialValue}
  onChange={() => {
    const [node] = Editor.nodes(editor);
    if (!node) {
      return;
    }
    const html = serialize(node[0]);
    [... do something with html ...]
  }}
>

Upvotes: 1

Views: 227

Answers (0)

Related Questions