client/src/HtmlSerializer.js
changeset 17 877d8796b86d
child 19 f1b125b95fe9
equal deleted inserted replaced
16:e67cd18cc594 17:877d8796b86d
       
     1 import React from 'react'
       
     2 import { Html } from 'slate'
       
     3 
       
     4 const BLOCK_TAGS = {
       
     5   blockquote: 'quote',
       
     6   p: 'paragraph',
       
     7   pre: 'code'
       
     8 }
       
     9 
       
    10 // Add a dictionary of mark tags.
       
    11 const MARK_TAGS = {
       
    12   em: 'italic',
       
    13   strong: 'bold',
       
    14   u: 'underline',
       
    15 }
       
    16 
       
    17 const rules = [
       
    18   // Block rules
       
    19   {
       
    20     deserialize(el, next) {
       
    21       const type = BLOCK_TAGS[el.tagName]
       
    22       if (!type) return
       
    23       return {
       
    24         kind: 'block',
       
    25         type: type,
       
    26         nodes: next(el.children)
       
    27       }
       
    28     },
       
    29     serialize(object, children) {
       
    30       if (object.kind != 'block') return
       
    31       switch (object.type) {
       
    32         case 'code': return <pre><code>{children}</code></pre>
       
    33         case 'paragraph':
       
    34         case 'line': return <p>{children}</p>
       
    35         case 'quote': return <blockquote>{children}</blockquote>
       
    36       }
       
    37     }
       
    38   },
       
    39   // Mark rules
       
    40   {
       
    41     deserialize(el, next) {
       
    42       const type = MARK_TAGS[el.tagName]
       
    43       if (!type) return
       
    44       return {
       
    45         kind: 'mark',
       
    46         type: type,
       
    47         nodes: next(el.children)
       
    48       }
       
    49     },
       
    50     serialize(object, children) {
       
    51       if (object.kind != 'mark') return
       
    52       switch (object.type) {
       
    53         case 'bold': return <strong>{children}</strong>
       
    54         case 'italic': return <em>{children}</em>
       
    55         case 'underline': return <u>{children}</u>
       
    56       }
       
    57     }
       
    58   }
       
    59 ]
       
    60 
       
    61 const serializer = new Html({ rules })
       
    62 
       
    63 export default serializer