2

how to deserializing nested html elements into a Slate-compatible JSON structure. any help please. i have already tried slate-hyperscript with the deserialize() function from the doc but it's not working. here is example html i have

<p><u><em><strong>Our S</strong></em></u><strong>ervi</strong><u><em><strong>ce</strong></em></u><em><strong>s </strong></em><em>A</em><u><em>nd</em></u><u><em><strong> </strong></em></u>Mo<u><em><strong>re</strong></em></u></p>

1 Answer 1

3

here is my solution:

import { jsx } from 'slate-hyperscript';

const deserialize = el => {
  if (el.nodeType === 3) {
    return el.textContent;
  }
  if (el.nodeType !== 1) {
    return null;
  }

  let children = Array.from(el.childNodes).map(deserialize);

  if (children.length === 0) {
    children = [{ text: '' }];
  }

  switch (el.nodeName) {
    // Elements:
    case 'BODY':
      return jsx('fragment', {}, children);
    case 'P':
      return jsx('element', { type: paragraph }, children);
    case 'H1':
      return jsx('element', { type: heading-one }, children);
    case 'H2':
      return jsx('element', { type: heading-two }, children);

    // Leafs:
    case 'STRONG':
      return { text: el.textContent, bold: true };
    case 'EM':
      return { text: el.textContent, italic: true };
    case 'U':
      return { text: el.textContent, underline: true };

    default:
      return el.textContent;
  }
};

const deserializeFromHtml = html => {
  const document = new window.DOMParser().parseFromString(html, 'text/html');
  return deserialize(document.body);
};
Sign up to request clarification or add additional context in comments.

1 Comment

Hi. Thank you for the answer but your code have a problem. You can't deserialize nested leaf in your editor. Like a bold text with an underline; your code is : ` case 'U': return { text: el.textContent, underline: true };` but my solution for supporting nested leaf is : case 'U': return jsx("text", { underline: true }, children); using JSX function with tagName : "text" and pass children to last argument. Make your code better and support nested leaf;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.