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:
@@ -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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user