From c456c9dbe160e587f600cbc0b10038aaa6a01eda Mon Sep 17 00:00:00 2001 From: Per-Kristian Nordnes Date: Sat, 25 Feb 2017 21:50:52 +0100 Subject: [PATCH] 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. --- examples/images/index.js | 83 +++++++++++++++++++++++++--------------- 1 file changed, 52 insertions(+), 31 deletions(-) diff --git a/examples/images/index.js b/examples/images/index.js index 0e3ed2a6d..c3a83f3da 100644 --- a/examples/images/index.js +++ b/examples/images/index.js @@ -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 ( ) + }, + paragraph: props => { + return

{props.children}

} - } + }, + 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. *