Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion packages/field-base/src/clear-button-mixin.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
* Copyright (c) 2021 - 2025 Vaadin Ltd.
* This program is available under Apache License Version 2.0, available at https://vaadin.com/license/
*/
import { isElementFocused } from '@vaadin/a11y-base/src/focus-utils.js';
import { KeyboardMixin } from '@vaadin/a11y-base/src/keyboard-mixin.js';
import { isTouch } from '@vaadin/component-base/src/browser-utils.js';
import { InputMixin } from './input-mixin.js';
Expand Down Expand Up @@ -71,7 +72,10 @@ export const ClearButtonMixin = (superclass) =>
* @protected
*/
_onClearButtonMouseDown(event) {
event.preventDefault();
if (this._shouldKeepFocusOnClearMousedown(event)) {
event.preventDefault();
}

if (!isTouch) {
this.inputElement.focus();
}
Expand Down Expand Up @@ -109,4 +113,17 @@ export const ClearButtonMixin = (superclass) =>
this.inputElement.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
this.inputElement.dispatchEvent(new Event('change', { bubbles: true }));
}

/**
* Whether to keep focus inside the field on clear button
* mousedown. By default, if the field has focus, it gets
* preserved using `preventDefault()` on mousedown event
* in order to avoid blur and change events.
*
* @protected
* @return {boolean}
*/
_shouldKeepFocusOnClearMousedown() {
return isElementFocused(this.inputElement);
}
};
9 changes: 8 additions & 1 deletion packages/field-base/test/clear-button-mixin.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,14 @@ describe('ClearButtonMixin', () => {
expect(spy.calledOnce).to.be.true;
});

it('should prevent default on clear button mousedown', () => {
it('should not prevent default on clear button mousedown if input is not focused', () => {
const event = new CustomEvent('mousedown', { cancelable: true });
clearButton.dispatchEvent(event);
expect(event.defaultPrevented).to.be.false;
});

it('should prevent default on clear button mousedown if input is focused', () => {
input.focus();
const event = new CustomEvent('mousedown', { cancelable: true });
clearButton.dispatchEvent(event);
expect(event.defaultPrevented).to.be.true;
Expand Down