grafana/public/app/features/explore/slate-plugins/braces.ts

71 lines
2.0 KiB
TypeScript
Raw Normal View History

import { Plugin } from '@grafana/slate-react';
import { Editor as CoreEditor } from 'slate';
const BRACES: any = {
2018-04-26 04:58:42 -05:00
'[': ']',
'{': '}',
'(': ')',
};
export default function BracesPlugin(): Plugin {
2018-04-26 04:58:42 -05:00
return {
onKeyDown(event: KeyboardEvent, editor: CoreEditor, next: Function) {
const { value } = editor;
2018-04-26 04:58:42 -05:00
switch (event.key) {
case '(':
2018-04-26 04:58:42 -05:00
case '{':
case '[': {
event.preventDefault();
const {
start: { offset: startOffset, key: startKey },
end: { offset: endOffset, key: endKey },
focus: { offset: focusOffset },
} = value.selection;
const text = value.focusText.text;
// If text is selected, wrap selected text in parens
if (value.selection.isExpanded) {
editor
.insertTextByKey(startKey, startOffset, event.key)
.insertTextByKey(endKey, endOffset + 1, BRACES[event.key])
.moveEndBackward(1);
} else if (
focusOffset === text.length ||
text[focusOffset] === ' ' ||
Object.values(BRACES).includes(text[focusOffset])
) {
editor.insertText(`${event.key}${BRACES[event.key]}`).moveBackward(1);
} else {
editor.insertText(event.key);
}
2018-04-26 04:58:42 -05:00
return true;
}
case 'Backspace': {
const text = value.anchorText.text;
const offset = value.selection.anchor.offset;
const previousChar = text[offset - 1];
const nextChar = text[offset];
if (BRACES[previousChar] && BRACES[previousChar] === nextChar) {
event.preventDefault();
// Remove closing brace if directly following
editor
.deleteBackward(1)
.deleteForward(1)
.focus();
return true;
}
}
2018-04-26 04:58:42 -05:00
default: {
break;
}
}
return next();
2018-04-26 04:58:42 -05:00
},
};
}