Skip to content

Commit

Permalink
DOCS: improved deserialization example (#4856)
Browse files Browse the repository at this point in the history
* Updated deserialize function

* forgot the .flat()

* made prettier happier
  • Loading branch information
janpaepke authored Mar 4, 2022
1 parent 47f2403 commit df1720d
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions docs/concepts/10-serializing.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,17 +162,27 @@ For example, here's a `deserialize` function for HTML:
```javascript
import { jsx } from 'slate-hyperscript'

const deserialize = el => {
if (el.nodeType === 3) {
return el.textContent
} else if (el.nodeType !== 1) {
const deserialize = (el, markAttributes = {}) => {
if (el.nodeType === Node.TEXT_NODE) {
return jsx('text', markAttributes, el.textContent)
} else if (el.nodeType !== Node.ELEMENT_NODE) {
return null
}

let children = Array.from(el.childNodes).map(deserialize)
const nodeAttributes = { ...markAttributes }

// define attibutes for text nodes
switch (el.nodeName) {
case 'strong':
nodeAttributes.bold = true
}

const children = Array.from(el.childNodes)
.map(node => deserialize(el, nodeAttributes))
.flat()

if (children.length === 0) {
children = [{ text: '' }]
children.push(jsx('text', nodeAttributes, ''))
}

switch (el.nodeName) {
Expand All @@ -191,7 +201,7 @@ const deserialize = el => {
children
)
default:
return el.textContent
return children
}
}
```
Expand Down

0 comments on commit df1720d

Please sign in to comment.