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,23 +439,55 @@ 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',
const marks = { nodes: [SlateText.createFromString('')]
b: 'bold', });
i: 'italic',
u: 'underlined',
s: 'strikethrough',
'`': 'code',
}; };
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;
const mark = marks[data.key]; if (focusBlock.isVoid && focusBlockIsTopLevel && singleBlockSelected) {
e.preventDefault();
if (mark) { const newBlock = createDefaultBlock();
state = state.transform().toggleMark(mark).apply(); const newBlockIndex = focusBlockIsFirstChild ? 0 : focusBlockIndex + 1;
return state.transform()
.insertNodeByKey(doc.key, newBlockIndex, newBlock)
.collapseToStartOf(newBlock)
.apply();
}
}
if (data.isMod) {
const marks = {
b: 'bold',
i: 'italic',
u: 'underlined',
s: 'strikethrough',
'`': 'code',
};
const mark = marks[data.key];
if (mark) {
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