client/src/HtmlSerializer.js
changeset 17 877d8796b86d
child 19 f1b125b95fe9
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/client/src/HtmlSerializer.js	Thu Jun 01 18:46:34 2017 +0200
@@ -0,0 +1,63 @@
+import React from 'react'
+import { Html } from 'slate'
+
+const BLOCK_TAGS = {
+  blockquote: 'quote',
+  p: 'paragraph',
+  pre: 'code'
+}
+
+// Add a dictionary of mark tags.
+const MARK_TAGS = {
+  em: 'italic',
+  strong: 'bold',
+  u: 'underline',
+}
+
+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 'code': return <pre><code>{children}</code></pre>
+        case 'paragraph':
+        case 'line': return <p>{children}</p>
+        case 'quote': return <blockquote>{children}</blockquote>
+      }
+    }
+  },
+  // 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>
+      }
+    }
+  }
+]
+
+const serializer = new Html({ rules })
+
+export default serializer