client/src/HtmlSerializer.js
author Alexandre Segura <mex.zktk@gmail.com>
Thu, 08 Jun 2017 18:54:36 +0200
changeset 25 e04714a1d4eb
parent 21 284e866f55c7
child 157 5c3af4f10e92
permissions -rw-r--r--
Improve categories tooltip. - Manage categories with comment enabled. - Rename mark type to "category". - Simplify code, use only one mark type.

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',
  category: '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 'category': return <span style={{ backgroundColor: object.data.get('color') }}>{children}</span>
        default: return;
      }
    }
  }
]

const serializer = new Html({ rules })

export default serializer