client/src/HtmlSerializer.js
author Alexandre Segura <mex.zktk@gmail.com>
Tue, 06 Jun 2017 15:56:41 +0200
changeset 19 f1b125b95fe9
parent 17 877d8796b86d
child 21 284e866f55c7
permissions -rw-r--r--
Introduce "annotation" plugin. - Wrap mark around text. - Store selected text in mark data. - Colorize selected text.

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 annotationStyle = {
  textDecoration: 'underline',
  textDecorationStyle: 'dotted',
  backgroundColor: 'yellow'
}

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={annotationStyle}>{children}</span>
        default: return;
      }
    }
  }
]

const serializer = new Html({ rules })

export default serializer