client/src/HtmlSerializer.js
author Alexandre Segura <mex.zktk@gmail.com>
Thu, 08 Jun 2017 11:13:41 +0200
changeset 21 284e866f55c7
parent 19 f1b125b95fe9
child 25 e04714a1d4eb
permissions -rw-r--r--
First version of categories tooltip. - Use react-portal to display hovering menu. - Add custom Mark to store category data.

import React from 'react'
import { Html } from 'slate'

const BLOCK_TAGS = {
  p: 'paragraph',
}

// Add a dictionary of mark tags.
const MARK_TAGS = {
  em: 'italic',
  strong: 'bold',
  u: 'underline',
  annotation: 'span'
}

const rules = [
  // Block rules
  {
    deserialize(el, next) {
      const type = BLOCK_TAGS[el.tagName]
      if (!type) return
      return {
        kind: 'block',
        type: type,
        nodes: next(el.children)
      }
    },
    serialize(object, children) {
      if (object.kind !== 'block') return
      switch (object.type) {
        case 'paragraph':
        case 'line': return <p>{children}</p>
        default: return;
      }
    }
  },
  // Mark rules
  {
    deserialize(el, next) {
      const type = MARK_TAGS[el.tagName]
      if (!type) return
      return {
        kind: 'mark',
        type: type,
        nodes: next(el.children)
      }
    },
    serialize(object, children) {
      if (object.kind !== 'mark') return
      switch (object.type) {
        case 'bold': return <strong>{children}</strong>
        case 'italic': return <em>{children}</em>
        case 'underline': return <u>{children}</u>
        case 'annotation': return <span style={{ backgroundColor: object.data.get('color') }}>{children}</span>
        default: return;
      }
    }
  }
]

const serializer = new Html({ rules })

export default serializer