w3c / uievents

UI Events
https://w3c.github.io/uievents/
Other
145 stars 51 forks source link

A way to determine what the value of an input will be if `beforeinput` is not prevented #289

Open devongovett opened 3 years ago

devongovett commented 3 years ago

It would be very useful to have a way to determine what the value of an <input> element will be if beforeinput is not prevented. For example, when implementing validation of text entry (e.g. a number field, telephone field, credit card number, etc.), the beforeinput event can be used to cancel invalid characters from being typed.

However, especially with deletion inputTypes, it can be challenging to get the full input value that would be committed after the beforeinput event. This is necessary in some cases to prevent deletion of certain parts of the input value. We can look at the selection and attempt to modify the existing value accordingly but this has many pitfalls, especially to do with unicode. For example, deletion by word or sentence is tricky to handle correctly. Plus, we shouldn't need to reinvent the code that the browser already has to do this.

Perhaps the InputEvent could have a property that indicates what the value will be after it is applied in addition to the data that is inserted? Or maybe that belongs on the HTMLInputElement specifically, since I could see this being challenging to support for contenteditable?

This issue is mainly a starting point for a conversation about this usecase, and I'm entirely open to any and all suggestions. 😄

cmawhorter commented 2 years ago

beforeinput doesn't seem all that useful in its current form:

perhaps keyboardevent/beforeinput could include the offset/position of where the event is firing within the target value?

then my users could type "1023", but not "0123". and it'd mitigate OPs problem a bit, and determine if a deletion occurred in a restricted area. it'd be nice to get data or something to contain the data that's being removed, however.

masayuki-nakano commented 5 months ago

Talking as a maintainer of editor of Firefox/Gecko, it's not impossible to implement, but it needs some big changes.

beforeinput event is dispatched at start of handling insertion/deletion. Therefore, the builtin editor still does not have the result. So, doing it, the builtin editor needs to handle the command/operation and dispatch beforeinput immediately before touching the editor value. So, the dispatcher cannot be centralized without big changes. (FYI: getTargetRanges for contenteditable causes duplicating the deletion code to compute the deleting range, therefore, the performance is not good and increased the maintenance cost.)

Cc: @johanneswilm @dandclark