1import React from 'react'; 2import Plain from 'slate-plain-serializer'; 3import { Editor } from '@grafana/slate-react'; 4import { shallow } from 'enzyme'; 5import { BracesPlugin } from './braces'; 6 7declare global { 8 interface Window { 9 KeyboardEvent: any; 10 } 11} 12 13describe('braces', () => { 14 const handler = BracesPlugin().onKeyDown!; 15 const nextMock = () => {}; 16 17 it('adds closing braces around empty value', () => { 18 const value = Plain.deserialize(''); 19 const editor = shallow<Editor>(<Editor value={value} />); 20 const event = new window.KeyboardEvent('keydown', { key: '(' }); 21 expect(handler(event as Event, editor.instance() as any, nextMock)).toBeTruthy(); 22 expect(Plain.serialize(editor.instance().value)).toEqual('()'); 23 }); 24 25 it('removes closing brace when opening brace is removed', () => { 26 const value = Plain.deserialize('time()'); 27 const editor = shallow<Editor>(<Editor value={value} />); 28 const event = new window.KeyboardEvent('keydown', { key: 'Backspace' }); 29 handler(event as Event, editor.instance().moveForward(5) as any, nextMock); 30 expect(Plain.serialize(editor.instance().value)).toEqual('time'); 31 }); 32 33 it('keeps closing brace when opening brace is removed and inner values exist', () => { 34 const value = Plain.deserialize('time(value)'); 35 const editor = shallow<Editor>(<Editor value={value} />); 36 const event = new window.KeyboardEvent('keydown', { key: 'Backspace' }); 37 const handled = handler(event as Event, editor.instance().moveForward(5) as any, nextMock); 38 expect(handled).toBeFalsy(); 39 }); 40 41 it('overrides an automatically inserted brace', () => { 42 const value = Plain.deserialize(''); 43 const editor = shallow<Editor>(<Editor value={value} />); 44 const opening = new window.KeyboardEvent('keydown', { key: '(' }); 45 expect(handler(opening as Event, editor.instance() as any, nextMock)).toBeTruthy(); 46 const closing = new window.KeyboardEvent('keydown', { key: ')' }); 47 expect(handler(closing as Event, editor.instance() as any, nextMock)).toBeTruthy(); 48 expect(Plain.serialize(editor.instance().value)).toEqual('()'); 49 }); 50 51 it.skip('does not override manually inserted braces', () => { 52 const value = Plain.deserialize(''); 53 const editor = shallow<Editor>(<Editor value={value} />); 54 const event1 = new window.KeyboardEvent('keydown', { key: ')' }); 55 expect(handler(event1 as Event, editor.instance() as any, nextMock)).toBeFalsy(); 56 const event2 = new window.KeyboardEvent('keydown', { key: ')' }); 57 expect(handler(event2 as Event, editor.instance().moveBackward(1) as any, nextMock)).toBeFalsy(); 58 expect(Plain.serialize(editor.instance().value)).toEqual('))'); 59 }); 60}); 61