w3c / input-events

Input Events
https://w3c.github.io/input-events/
Other
24 stars 17 forks source link

Trigger beforeinput event from JS with measurements. #54

Open johanneswilm opened 7 years ago

johanneswilm commented 7 years ago

This came up in today's Editing taskforce call. We discussed whether Selection.modify [1] could be used to create beforeinput events in JS with correctly measured target ranges. The difficulty is to add the right target range -- for example to cover what the browser sees as a word backward or alike.

So if I wanted to create a beforeinput event with the inputtype "deleteWordForward", it seems I would do something like this:

let oldRange = selection.getRangeAt(0)
selection.modify('extend', 'forward', 'word')
let newRange = selection.getRangeAt(0)
selection.removeAllRanges()
selection.addRange(oldRange)

triggerBeforeInputEvent('deleteWordForward', newRange)

Where triggerBeforeInputEvent will then convert the newRange lvierange to a static range and trigger the corresponding event.

So it seems to me that it is possible to use, but it will require the temporary loss of the selection. Having to lose the selection seems like an inconvenience that will be OK a lot of times, but probably problematic during some other times, for example during IME input when the selection cannot be touched.

So the question is: Is this a good way of doing it? Should this be what we recommend JS developers do?

[1] https://github.com/w3c/selection-api/issues/37

johanneswilm commented 7 years ago

@choniong Is this was you proposed?

chong-z commented 7 years ago

Yes it seems to me that the issue could be solved using SelectionAPI.

Question: In which case JS needs to trigger beforeinput with selection other than current selection?

johanneswilm commented 7 years ago

@choniong Well, in the case of word or line forward or backward, the target range will almost always be different than the current selection. You can have a collapsed selection, then click a key combination to delete the word in front of the caret. By the time the beforeinput event is triggered, the selection will still be collapsed and the JS now decides whether it will let the browser's built-in idea of a word forward be selected, or if it has its own idea of what it should delete.

I guess this is fine in most cases. It is a little bit odd that one needs to lose the selection in order to be able to measure certain things, but with the exception of the period during an IME-input, this will probably be fine mostly.