1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-19 05:31:56 +02:00

DOCS: improved deserialization example (#4856)

* Updated deserialize function

* forgot the .flat()

* made prettier happier
This commit is contained in:
Jan Paepke
2022-03-04 02:27:19 +01:00
committed by GitHub
parent 47f2403e3a
commit df1720d311

View File

@@ -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) {
@@ -191,7 +201,7 @@ const deserialize = el => {
children
)
default:
return el.textContent
return children
}
}
```