Add new function 'deleteCharacterBackward'

This commit is contained in:
Peter Stuifzand 2020-11-14 15:42:03 +01:00
parent 4518621790
commit 045cf17dee

View File

@ -43,6 +43,7 @@ function editor(root, inputData, options) {
editorKeymap.mapKey('C-S-ArrowUp', 'blockMoveBackward') editorKeymap.mapKey('C-S-ArrowUp', 'blockMoveBackward')
editorKeymap.mapKey('C-S-ArrowDown', 'blockMoveForward') editorKeymap.mapKey('C-S-ArrowDown', 'blockMoveForward')
editorKeymap.mapKey('C-.', 'toggleBlock') editorKeymap.mapKey('C-.', 'toggleBlock')
editorKeymap.mapKey('Backspace', 'deleteCharacterBackward')
// keymap.mapKey('C-]', 'zoomIn') // keymap.mapKey('C-]', 'zoomIn')
// keymap.mapKey('C-[', 'zoomOut') // keymap.mapKey('C-[', 'zoomOut')
@ -179,6 +180,8 @@ function editor(root, inputData, options) {
blockMoveBackward, blockMoveBackward,
blockMoveForward, blockMoveForward,
deleteCharacterBackward,
expandBlock, expandBlock,
collapseBlock, collapseBlock,
toggleBlock toggleBlock
@ -658,6 +661,64 @@ function editor(root, inputData, options) {
return toggleBlock(event, false) return toggleBlock(event, false)
} }
function countBraces(sset, as) {
let set = _(sset).chain().split('').value()
let defaults = {}
defaults[set[0]] = 0
defaults[set[1]] = 0
return _(as)
.chain()
.takeWhile(c => _.includes(set, c))
.countBy()
.defaults(defaults)
.thru(x => x[set[0]] - x[set[1]])
.value()
}
function deleteCharacterBackward(event) {
let input = event.target
let value = input.value
// There is text selected, so we skip
if (input.selectionStart !== input.selectionEnd) return true
let prefix = value.slice(0, input.selectionStart)
let suffix = value.slice(input.selectionStart)
let braces = {
'[': '[]',
'(': '()',
'{': '{}',
}
let c = prefix[prefix.length-1]
let braceSet = braces[c]
let prefixCount = _(prefix)
.split('').reverse()
.thru(_.partial(countBraces, braceSet))
.value()
let suffixCount = _(suffix)
.split('')
.thru(_.partial(countBraces, braceSet))
.value()
if (prefixCount > 0 && suffixCount < 0 && prefixCount + suffixCount === 0) {
event.preventDefault()
input.value = prefix.slice(0, prefix.length - 1) + suffix.slice(1)
_.defer(() => {
input.selectionStart = prefix.length - 1
input.selectionEnd = input.selectionStart
})
return false
}
return true
}
$(root).on('keydown', function (event) { $(root).on('keydown', function (event) {
if (editing) { if (editing) {
return editorKeymap.handleKey(EDITOR, event) return editorKeymap.handleKey(EDITOR, event)