1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-22 06:53:25 +02:00

Image example: fix delete bug. Fixes #625 (#628)

As void-nodes now can be deleted, use a schema rule to normalize the document, and insert a paragraph when empty. Delete old "onDocumentChange" handler.
This commit is contained in:
Per-Kristian Nordnes
2017-02-25 21:50:52 +01:00
committed by Ian Storm Taylor
parent c3578d12ad
commit c456c9dbe1

View File

@@ -1,10 +1,24 @@
import { Editor, Raw } from '../..'
import { Editor, Block, Raw } from '../..'
import React from 'react'
import initialState from './state.json'
import isImage from 'is-image'
import isUrl from 'is-url'
/**
* Default block to be inserted when the document is empty,
* and after an image is the last node in the document.
*
* @type {Object}
*/
const defaultBlock = {
type: 'paragraph',
isVoid: false,
data: {}
}
/**
* Define a schema.
*
@@ -13,7 +27,7 @@ import isUrl from 'is-url'
const schema = {
nodes: {
image: (props) => {
image: props => {
const { node, state } = props
const isFocused = state.selection.hasEdgeIn(node)
const src = node.data.get('src')
@@ -21,8 +35,43 @@ const schema = {
return (
<img src={src} className={className} {...props.attributes} />
)
},
paragraph: props => {
return <p {...props.attributes}>{props.children}</p>
}
}
},
rules: [
// Rule to insert a paragraph block if the document is empty
{
match: node => {
return node.kind == 'document'
},
validate: document => {
return document.nodes.size ? null : true
},
normalize: (transform, document) => {
const block = Block.create(defaultBlock)
transform
.insertNodeByKey(document.key, 0, block)
}
},
// Rule to insert a paragraph below a void node (the image)
// if that node is the last one in the document
{
match: node => {
return node.kind == 'document'
},
validate: document => {
const lastNode = document.nodes.last()
return lastNode && lastNode.isVoid ? true : null
},
normalize: (transform, document) => {
const block = Block.create(defaultBlock)
transform
.insertNodeByKey(document.key, document.nodes.size, block)
}
}
]
}
/**
@@ -105,34 +154,6 @@ class Images extends React.Component {
this.setState({ state })
}
/**
* On document change, if the last block is an image, add another paragraph.
*
* @param {Document} document
* @param {State} state
*/
onDocumentChange = (document, state) => {
const blocks = document.getBlocks()
const last = blocks.last()
if (last.type != 'image') return
const normalized = state
.transform()
.collapseToEndOf(last)
.splitBlock()
.setBlock({
type: 'paragraph',
isVoid: false,
data: {}
})
.apply({
save: false
})
this.onChange(normalized)
}
/**
* On clicking the image button, prompt for an image and insert it.
*