Created
February 26, 2017 18:59
-
-
Save ianstormtaylor/86a65213e443673a264faf0c9a9731bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createMatcher } from '../slate-plugin-utils' | |
/** | |
* A Slate plugin to reset empty blocks to a default type when the user presses | |
* backspace at the start of a block. | |
* | |
* @param {Object} opts | |
* @property {String} defaultType | |
* @property {Function || Array || String} ignoreIn | |
* @property {Function || Array || String} onlyIn | |
* @return {Function} | |
*/ | |
function ResetOnBackspace(opts) { | |
if (!opts.defaultType) throw new Error('You must provide a `defaultType` string.') | |
const ignoreIn = createMatcher(opts.ignoreIn) | |
const onlyIn = createMatcher(opts.onlyIn) | |
/** | |
* On key down. | |
* | |
* @param {Event} e | |
* @param {Object} data | |
* @param {State} state | |
* @return {State} | |
*/ | |
function onKeyDown(e, data, state) { | |
if (data.key != 'backspace') return | |
if (state.isExpanded) return | |
if (state.startOffset != 0) return | |
if (ignoreIn && ignoreIn(state.startBlock)) return | |
if (onlyIn && !onlyIn(state.startBlock)) return | |
return state | |
.transform() | |
.setBlock(opts.defaultType) | |
.apply() | |
} | |
/** | |
* Return the plugin. | |
*/ | |
return { | |
onKeyDown | |
} | |
} | |
/** | |
* Export. | |
*/ | |
export default ResetOnBackspace |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment