[IMP] web: auto-select content on focus for autocomplete (e.g. m2o) fields

On first focus in an autocomplete field, the text content of the input element
is automatically highlighted.

closes odoo/odoo#109025

Task-id: 3117420
Signed-off-by: Aaron Bohy (aab) <aab@odoo.com>
This commit is contained in:
Joseph Caburnay
2023-01-09 12:22:46 +01:00
parent 5c8cc3551f
commit 84d9cb9271
5 changed files with 21 additions and 9 deletions
@@ -4,11 +4,3 @@ import { AutoComplete } from "@web/core/autocomplete/autocomplete";
export class AnalyticAutoComplete extends AutoComplete {}
AnalyticAutoComplete.template = "analytic.AutoComplete";
AnalyticAutoComplete.props = {
...AutoComplete.props,
onFocus: { type: Function, optional: true },
}
AnalyticAutoComplete.defaultProps = {
...AutoComplete.defaultProps,
onFocus: () => {},
}
@@ -4,7 +4,6 @@
<xpath expr="//input" position="attributes">
<attribute name="t-on-click"></attribute>
<attribute name="t-on-click.stop">onInputClick</attribute>
<attribute name="t-on-focus">props.onFocus</attribute>
</xpath>
</t>
</templates>
@@ -228,6 +228,11 @@ export class AutoComplete extends Component {
this.open(true);
}
onInputFocus(ev) {
this.inputRef.el.setSelectionRange(0, this.inputRef.el.value.length);
this.props.onFocus(ev);
}
onInputKeydown(ev) {
const hotkey = getActiveHotkey(ev);
switch (hotkey) {
@@ -315,6 +320,7 @@ Object.assign(AutoComplete, {
onInput: { type: Function, optional: true },
onChange: { type: Function, optional: true },
onBlur: { type: Function, optional: true },
onFocus: { type: Function, optional: true },
input: { type: Function, optional: true },
},
defaultProps: {
@@ -323,6 +329,7 @@ Object.assign(AutoComplete, {
onInput: () => {},
onChange: () => {},
onBlur: () => {},
onFocus: () => {},
},
timeout: 250,
});
@@ -15,6 +15,7 @@
t-on-change="onInputChange"
t-on-input="debouncedOnInput"
t-on-keydown="onInputKeydown"
t-on-focus="onInputFocus"
t-ref="input"
/>
<t t-if="isOpened and hasOptions">
@@ -142,6 +142,19 @@ QUnit.module("Components", (hooks) => {
assert.containsNone(target, ".o-autocomplete--dropdown-menu");
});
QUnit.test("select input text on first focus", async (assert) => {
class Parent extends Component {}
Parent.components = { AutoComplete };
Parent.template = xml`
<AutoComplete value="'Bar'" sources="[{ options: [{ label: 'Bar' }] }]" onSelect="() => {}"/>
`;
await mount(Parent, target, { env });
await triggerEvents(target, ".o-autocomplete--input", ["focus", "click"]);
const el = target.querySelector(".o-autocomplete--input");
assert.strictEqual(el.value.substring(el.selectionStart, el.selectionEnd), "Bar");
});
QUnit.test("scroll outside should close dropdown", async (assert) => {
class Parent extends Component {}
Parent.components = { AutoComplete };