mirror of
https://github.com/ianstormtaylor/slate.git
synced 2025-08-20 06:01:24 +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
|
```javascript
|
||||||
import { jsx } from 'slate-hyperscript'
|
import { jsx } from 'slate-hyperscript'
|
||||||
|
|
||||||
const deserialize = el => {
|
const deserialize = (el, markAttributes = {}) => {
|
||||||
if (el.nodeType === 3) {
|
if (el.nodeType === Node.TEXT_NODE) {
|
||||||
return el.textContent
|
return jsx('text', markAttributes, el.textContent)
|
||||||
} else if (el.nodeType !== 1) {
|
} else if (el.nodeType !== Node.ELEMENT_NODE) {
|
||||||
return null
|
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) {
|
if (children.length === 0) {
|
||||||
children = [{ text: '' }]
|
children.push(jsx('text', nodeAttributes, ''))
|
||||||
}
|
}
|
||||||
|
|
||||||
switch (el.nodeName) {
|
switch (el.nodeName) {
|
||||||
@@ -191,7 +201,7 @@ const deserialize = el => {
|
|||||||
children
|
children
|
||||||
)
|
)
|
||||||
default:
|
default:
|
||||||
return el.textContent
|
return children
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user