Fix Chrome autocomplete incorrectly triggerring actions by MatheusRich · Pull Request #853 · hotwired/stimulus

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The underlying Action.shouldIgnoreKeyboardEvent function ultimately accesses properties on the KeyboardEvent instance, so instantiating a new KeyboardEvent instance without those properties might lead to unexpected behavior.

As an alternative, what do you think about using typecasting instead?

if (event.type === "keydown") {
// when accepting an autocomplete suggestion, Chrome dispatches a keydown event,
// but it isn't a KeyboardEvent instance
const keyboardEvent: KeyboardEvent = event instanceof KeyboardEvent ? event : new KeyboardEvent("keydown")
if (this.action.shouldIgnoreKeyboardEvent(keyboardEvent)) {
// When accepting an autocomplete suggestion, Chrome dispatches a keydown event that is not a KeyboardEvent instance
if (event.type === "keydown" && this.action.shouldIgnoreKeyboardEvent(event as KeyboardEvent)) {

That assumes that Chrome's synthetic event does have the properties required to behave like a KeyboardEvent. That might not be the case, but my hunch is that it'd behave better as the syntetic event than as an event that Stimulus constructs itself.