miztroh-zz / wysiwyg-e

A what-you-see-is-what-you-get editor created with Polymer
85 stars 18 forks source link

Simulating an Enter key press #205

Closed lastmjs closed 6 years ago

lastmjs commented 6 years ago

I'm struggling to figure this out...how would I go about simulating an Enter key press? I've tried constructing my own event and dispatching it on the editable and content divs inside of the editor, but nothing happens. Is this even the correct way to go about this?

miztroh-zz commented 6 years ago

Why do you need to simulate this keypress? What's the final result you're hoping to achieve?

lastmjs commented 6 years ago

When I programmatically insert text into the editor, I want to insert a new line as well. I'm struggling to figure out how to do that.

Also, when I start doing integration tests I want to simulate actual key presses, so even if a return key press isn't the right way to go about inserting a new line, I'd like to know how to do general key press emulation if possible.

miztroh-zz commented 6 years ago

Assuming you have a valid selection within wysiwyg-e's target, you can call the following:

document.execCommand('insertHTML', false, '<br>');

https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

Let me know if this fixes it for you.

lastmjs commented 6 years ago

That is beautiful, it worked! I would still like to do integration tests by simulating key events. I use property based testing, which generates many random strings within a DSL as inputs. I'm then going to have the test act like a user and "type" the random DSL strings into the editor and ensure that it behaves properly. Any help on generating those key presses?

miztroh-zz commented 6 years ago

Try this:

https://elgervanboxtel.nl/site/blog/simulate-keydown-event-with-javascript

miztroh-zz commented 6 years ago

You will probably want to use keypress instead of keydown ... and change the details of the key you need of course.