-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathautocomplete-input.js
55 lines (51 loc) · 1.89 KB
/
autocomplete-input.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
import Component from '@glimmer/component';
import { action } from '@ember/object';
/**
* @module AutocompleteInput
* AutocompleteInput components are used as standard string inputs or optionally select options to append to input value
*
* @example
* <AutocompleteInput @label="Label here" @subText="subtext here" @value="foo" @onChange={{log "on change called"}} />
*
* @param {string} value - input value
* @param {function} onChange - fires when input value changes to mutate value param by caller
* @param {string} [optionsTrigger] - display options dropdown when trigger character is input
* @param {array} [options] - array of `{ label, value }` objects where label is displayed in options dropdown and value is appended to input value
* @param {string} [label] - label to display above input
* @param {string} [subText] - text to display below label
* @param {string} [placeholder] - input placeholder
*/
export default class AutocompleteInputComponent extends Component {
dropdownAPI;
inputElement;
@action
setElement(element) {
this.inputElement = element.querySelector('.input');
}
@action
setDropdownAPI(dropdownAPI) {
this.dropdownAPI = dropdownAPI;
}
@action
onInput(event) {
const { options = [], optionsTrigger } = this.args;
if (optionsTrigger && options.length) {
const method = event.data === optionsTrigger ? 'open' : 'close';
this.dropdownAPI.actions[method]();
}
this.args.onChange(event.target.value);
}
@action
selectOption(value) {
// if trigger character is at start of value it needs to be trimmed
const appendValue = value.startsWith(this.args.optionsTrigger) ? value.slice(1) : value;
const newValue = this.args.value + appendValue;
this.args.onChange(newValue);
this.dropdownAPI.actions.close();
this.inputElement.focus();
}
}