From 045cf17deea53267d5a15d94d8da2fdc096f38b0 Mon Sep 17 00:00:00 2001 From: Peter Stuifzand Date: Sat, 14 Nov 2020 15:42:03 +0100 Subject: [PATCH] Add new function 'deleteCharacterBackward' --- list-editor/index.js | 61 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/list-editor/index.js b/list-editor/index.js index 86db1d0..b0fb3de 100644 --- a/list-editor/index.js +++ b/list-editor/index.js @@ -43,6 +43,7 @@ function editor(root, inputData, options) { editorKeymap.mapKey('C-S-ArrowUp', 'blockMoveBackward') editorKeymap.mapKey('C-S-ArrowDown', 'blockMoveForward') editorKeymap.mapKey('C-.', 'toggleBlock') + editorKeymap.mapKey('Backspace', 'deleteCharacterBackward') // keymap.mapKey('C-]', 'zoomIn') // keymap.mapKey('C-[', 'zoomOut') @@ -179,6 +180,8 @@ function editor(root, inputData, options) { blockMoveBackward, blockMoveForward, + deleteCharacterBackward, + expandBlock, collapseBlock, toggleBlock @@ -658,6 +661,64 @@ function editor(root, inputData, options) { 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) { if (editing) { return editorKeymap.handleKey(EDITOR, event)