allow enter key to make space around void nodes

This commit is contained in:
Shawn Erquhart 2017-07-26 17:11:23 -04:00
parent fbecc887b8
commit 6443f5d808

View File

@ -439,9 +439,40 @@ export default class Editor extends Component {
hasBlock = type => this.state.editorState.blocks.some(node => node.type === type); hasBlock = type => this.state.editorState.blocks.some(node => node.type === type);
handleKeyDown = (e, data, state) => { handleKeyDown = (e, data, state) => {
if (!data.isMod) { const createDefaultBlock = () => {
return; return SlateBlock.create({
type: 'paragraph',
nodes: [SlateText.createFromString('')]
});
};
if (data.key === 'enter') {
/**
* If a single void block is selected, and it's a direct descendant of the
* document (top level), a new paragraph should be added above or below it
* when 'Enter' is pressed, and the current selection should move to the
* new paragraph.
*
* If the selected block is the first block in the document, create the
* new block above it. If not, create the new block below it.
*/
const { document: doc, selection, anchorBlock, focusBlock } = state;
const focusBlockIndex = doc.nodes.indexOf(focusBlock);
const focusBlockIsTopLevel = focusBlockIndex > -1;
const focusBlockIsFirstChild = focusBlockIndex === 0;
const singleBlockSelected = anchorBlock === focusBlock;
if (focusBlock.isVoid && focusBlockIsTopLevel && singleBlockSelected) {
e.preventDefault();
const newBlock = createDefaultBlock();
const newBlockIndex = focusBlockIsFirstChild ? 0 : focusBlockIndex + 1;
return state.transform()
.insertNodeByKey(doc.key, newBlockIndex, newBlock)
.collapseToStartOf(newBlock)
.apply();
} }
}
if (data.isMod) {
const marks = { const marks = {
b: 'bold', b: 'bold',
i: 'italic', i: 'italic',
@ -453,9 +484,10 @@ export default class Editor extends Component {
const mark = marks[data.key]; const mark = marks[data.key];
if (mark) { if (mark) {
state = state.transform().toggleMark(mark).apply(); e.preventDefault();
return state.transform().toggleMark(mark).apply();
}
} }
return;
}; };
handleMarkClick = (event, type) => { handleMarkClick = (event, type) => {
@ -584,7 +616,7 @@ export default class Editor extends Component {
plugins={slatePlugins} plugins={slatePlugins}
onChange={editorState => this.setState({ editorState })} onChange={editorState => this.setState({ editorState })}
onDocumentChange={this.handleDocumentChange} onDocumentChange={this.handleDocumentChange}
onKeyDown={this.onKeyDown} onKeyDown={this.handleKeyDown}
onPaste={this.handlePaste} onPaste={this.handlePaste}
ref={ref => this.ref = ref} ref={ref => this.ref = ref}
spellCheck spellCheck