-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.ts
1529 lines (1335 loc) · 41.3 KB
/
index.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
css,
CSSResultGroup,
ElementSize,
html,
PropertyValues,
TemplateResult
} from '@refinitiv-ui/core';
import { customElement } from '@refinitiv-ui/core/decorators/custom-element.js';
import { query } from '@refinitiv-ui/core/decorators/query.js';
import { property } from '@refinitiv-ui/core/decorators/property.js';
import { ref, createRef, Ref } from '@refinitiv-ui/core/directives/ref.js';
import { unsafeHTML } from '@refinitiv-ui/core/directives/unsafe-html.js';
import { VERSION } from '../version.js';
import { AnimationTaskRunner, TimeoutTaskRunner } from '@refinitiv-ui/utils/async.js';
import { isIE, isMobile } from '@refinitiv-ui/utils/browser.js';
import {
translate,
TranslateDirective,
TranslatePropertyKey
} from '@refinitiv-ui/translate';
import { TapEvent } from '../events.js';
import type {
AutosuggestTargetElement,
AutosuggestHighlightable,
AutosuggestMethodType,
AutosuggestQuery,
AutosuggestRenderer,
AutosuggestReason,
AutosuggestItem,
AutosuggestSelectItemEvent,
AutosuggestHighlightItemEvent,
AutosuggestQueryAction
} from './helpers/types';
import { escapeRegExp, itemHighlightable, queryWordSelect } from './helpers/utils.js';
import { renderer } from './helpers/renderer.js';
import { Overlay } from '../overlay/index.js';
import '../loader/index.js';
import '../item/index.js';
import '@refinitiv-ui/phrasebook/locale/en/autosuggest.js';
export type {
AutosuggestTargetElement,
AutosuggestHighlightable,
AutosuggestMethodType,
AutosuggestQuery,
AutosuggestRenderer,
AutosuggestReason,
AutosuggestItem,
ItemHighlightEvent,
AddAttachTargetEventsEvent,
RemoveAttachTargetEventsEvent,
ItemSelectEvent,
SuggestionsFetchRequestedEvent,
SuggestionsClearRequestedEvent,
SuggestionsQueryEvent,
SuggestionsChangedEvent
} from './helpers/types.js';
export { updateElementContent } from './helpers/utils.js';
export {
itemHighlightable,
escapeRegExp,
queryWordSelect,
renderer,
renderer as itemRenderer // compatibility
};
/**
* Shows suggestions based on users' query.
* It can be used by attaching to text form control
* such as TextField, Multi Input, etc.
* Autosuggest supports various use cases such as
* custom rendering, pagination, asynchronous data request, etc.
*
* @fires item-highlight Fired when an item gets highlighted or highlight is removed
* @fires add-attach-target-events Fired when attach has been set
* @fires remove-attach-target-events Fired when attach has been removed
* @fires item-select Fired when an item gets selected
* @fires suggestions-fetch-requested Fired when auto suggest requests the data
* @fires suggestions-clear-requested Fired when auto suggest requests to clear the data. If used in reactive application, prevent default and set suggestions to []
* @fires suggestions-query Fired when input value has changed and the query must be set
* @fires suggestions-changed Fired when suggestions changed
*
* @attr {boolean} opened - Set to open auto suggest popup
* @prop {boolean} [opened=false] - Auto suggest popup's open state
*
* @slot header - Slot to add custom contents at the top of autosuggest popup
* @slot footer - Slot to add custom contents at the bottom of autosuggest popup
*/
@customElement('ef-autosuggest', {
alias: 'emerald-autosuggest'
})
export class Autosuggest extends Overlay {
/**
* Element version number
* @returns version number
*/
static get version (): string {
return VERSION;
}
protected readonly defaultRole: string | null = 'listbox';
/**
* A `CSSResultGroup` that will be used
* to style the host, slotted children
* and the internal template of the element.
* @return CSS template
*/
static get styles (): CSSResultGroup {
return [
super.styles,
css`
:host {
overflow: hidden;
display: flex;
flex-direction: column;
}
[part=content] {
flex: 1 1 auto;
overflow-x: hidden;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
[part=header], [part=footer] {
flex: none;
}
`
];
}
/**
* A basic regexp matching pattern to replace text based on string input.
* @param text Value to test against
* @param query The query
* @param [pattern=<mark>$1</mark>] Provide a pattern to replace string
* @returns innerHTML The text that can be used as innerHTML
*/
public static QueryWordSelect (text: string, query = '', pattern = '<mark>$1</mark>'): string {
return queryWordSelect(text, query, pattern);
}
/**
* Build item element from data object
* @param suggestion Suggestion data
* @param query A query data (usually string, but could be any entity )
* @returns item
*/
public static ItemRenderer (suggestion: AutosuggestItem, query: AutosuggestQuery | null): HTMLElement {
return renderer(suggestion, query);
}
/**
* Replace forbidden characters in regular expressions
* @param string A string to process
* @returns clean string
*/
public static EscapeRegExp (string = ''): string {
return escapeRegExp(string);
}
/**
* Check whether item can be highlighted
* @param suggestion Suggestion object
* @param target item element
* @returns highlightable
*/
public static ItemHighlightable (suggestion: AutosuggestItem, target: HTMLElement): boolean {
return itemHighlightable(suggestion, target);
}
public static readonly defaultDebounceRate = 100;
/**
* An HTML Element or CSS selector
*/
@property({ type: String })
public attach: AutosuggestTargetElement | string | null = null;
/**
* Request suggestions when attach target is focused
*/
@property({ type: Boolean, attribute: 'request-on-focus' })
public requestOnFocus = false;
/**
* If set to true display 'Has more results' item
*/
@property({ type: Boolean, reflect: true, attribute: 'more-results' })
public moreResults = false;
/**
* Custom text for More Search
* @default More results for {0}
*/
@property({ type: String, attribute: 'more-search-text' })
public moreSearchText = '';
/**
* If set to true show loading mask
*/
@property({ type: Boolean, reflect: true })
public loading = false;
/**
* An object that represents a query from attach target
*/
@property({ type: Object, attribute: false })
public query: AutosuggestQuery | null = null;
/**
* Debounce rate in ms of the filter as a number.
* Used to throttle the filter rate so as not to trigger unneeded filtering
* @default 100
*/
@property({ type: Number, attribute: 'debounce-rate' })
public debounceRate = Autosuggest.defaultDebounceRate;
/**
* A renderer applied to suggestion.
* By default a render maps data to item attributes
*/
@property({ attribute: false })
public renderer: AutosuggestRenderer = renderer;
/**
* A function that is applied to every suggestion during the render process
* to say whether the item can be highlighted and selected. Only items that return true are considered.
* By default the function checks for `item` `highlightable` property.
*/
@property({ attribute: false })
public highlightable: AutosuggestHighlightable = itemHighlightable;
/**
* A list of suggestion items
*/
@property({ type: Array, attribute: false })
public suggestions: AutosuggestItem[] = [];
/**
* If set to true, the render function is not called. Instead the wrapper element
* should populate and destroy suggestion elements. Rendering items manually
* may have performance benefits in frameworks that use virtual DOM (such as `Vue`, `React`, `hyperHTML` and others)
*/
@property({ type: Boolean, attribute: 'html-renderer' })
public htmlRenderer = false;
/**
* Autosuggest internal translation strings
*/
@translate({ scope: 'ef-autosuggest' })
protected t!: TranslateDirective;
@query('#moreResults')
protected moreResultsItem?: HTMLElement | null;
private contentSlotRef: Ref<HTMLSlotElement> = createRef();
private contentElementRef: Ref<HTMLElement> = createRef();
private headerElementRef: Ref<HTMLElement> = createRef();
private footerElementRef: Ref<HTMLElement> = createRef();
// used to map render elements with data
private suggestionMap = new Map<HTMLElement, AutosuggestItem>();
protected highlightedItem: HTMLElement | null = null;
protected attachTarget: AutosuggestTargetElement | null = null;
private lastActiveElement: HTMLElement | null = null;
private suspendedKey = false;
private preservedQueryValue: AutosuggestQuery | null = null;
private focusSuspended = false;
private jobRunner = new TimeoutTaskRunner(this.debounceRate);
private attachChangeRunner = new AnimationTaskRunner();
private moreResultsRunner = new AnimationTaskRunner();
private loadingRunner = new AnimationTaskRunner();
/**
* creates auto-suggest
*/
constructor () {
super();
/**
* @ignore
*/
this.position = ['bottom-start', 'top-start', 'right-middle'];
/**
* @ignore
*/
this.noCancelOnEscKey = true;
/**
* @ignore
*/
this.noCancelOnOutsideClick = true;
/**
* @ignore
*/
this.noAutofocus = true;
/**
* @ignore
*/
this.noOverlap = true;
/**
* @ignore
*/
this.withShadow = false;
/**
* @ignore
*/
this.noFocusManagement = true;
/**
* @ignore
*/
this.onInputValueChange = this.onInputValueChange.bind(this);
/**
* @ignore
*/
this.onInputKeyDown = this.onInputKeyDown.bind(this);
/**
* @ignore
*/
this.onInputBlur = this.onInputBlur.bind(this);
/**
* @ignore
*/
this.onInputFocus = this.onInputFocus.bind(this);
/**
* @ignore
*/
this.suggestionsQueryAction = this.suggestionsQueryAction.bind(this);
/**
* @ignore
*/
this.itemSelectAction = this.itemSelectAction.bind(this);
/**
* @ignore
*/
this.itemHighlightAction = this.itemHighlightAction.bind(this);
/**
* @ignore
*/
this.suggestionsFetchRequestedAction = this.suggestionsFetchRequestedAction.bind(this);
/**
* @ignore
*/
this.suggestionsClearRequestedAction = this.suggestionsClearRequestedAction.bind(this);
/**
* @ignore
*/
this.attachEventsAddAction = this.attachEventsAddAction.bind(this);
/**
* @ignore
*/
this.attachEventsRemoveAction = this.attachEventsRemoveAction.bind(this);
/**
* @ignore
*/
this.onItemMousedown = this.onItemMousedown.bind(this);
/**
* @ignore
*/
this.onOutsideClick = this.onOutsideClick.bind(this);
}
public disconnectedCallback (): void {
this.dispatchAttachEventsRemoveAction();
super.disconnectedCallback();
}
/**
* Run when attach target value changes.
* @param event by default `value-changed` event is listened
* @returns {void}
*/
public onInputValueChange (event: Event): void {
if (!this.suspended) { // avoid circular
/* istanbul ignore next */
if (isMobile) {
this.lastActiveElement = event.target as HTMLElement;
}
this.requestSuggestions('value-changed', true);
}
}
/**
* Run when input has lost focus
* @param event by default `blur` event is listened
* @returns {void}
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public onInputBlur (event: FocusEvent): void {
requestAnimationFrame(() => {
if (!this.attachTargetFocused) {
this.setOpened(false);
}
});
}
/**
* Run when input received focus
* @param event by default `focus` event is listened
* @returns {void}
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
public onInputFocus (event: FocusEvent): void {
/* istanbul ignore next */
if (this.focusSuspended) {
// see _onItemMousedown, it is an IE fix for scrollbar
return;
}
this.requestOnFocus && this.requestSuggestions('input-focus');
}
/**
* Run when input key down event has happened
* @param event by default `keydown` event is listened
* @returns {void}
*/
public onInputKeyDown (event: KeyboardEvent): void {
if (event.defaultPrevented) {
return;
}
switch (event.key) {
case 'ArrowUp':
case 'Up':
this.onUpKey();
break;
case 'ArrowDown':
case 'Down':
this.onDownKey();
break;
case 'Escape':
case 'Esc':
this.onEscKey();
break;
case 'Return':
case 'Enter':
this.onEnterKey(event);
break;
default:
return;
}
event.preventDefault();
}
/**
* @ignore
* Called when the element's dimensions have changed
* @param size dimension details
* @returns {void}
*/
public resizedCallback (size: ElementSize): void {
super.resizedCallback(size);
this.calculateContentMaxHeight(size);
}
/**
* Called once after the component is first rendered
* @param changedProperties map of changed properties with old values
* @returns {void}
*/
protected firstUpdated (changedProperties: PropertyValues): void {
super.firstUpdated(changedProperties);
this.addEventListener('tapstart', this.onItemMousedown);
}
/**
* Called when the element’s DOM has been updated and rendered
* @param changedProperties Properties that has changed
* @returns shouldUpdate
*/
protected shouldUpdate (changedProperties: PropertyValues): boolean {
let result = super.shouldUpdate(changedProperties);
result = result || this.shouldAutosuggestUpdate(changedProperties);
return result;
}
/**
* Called after the element’s DOM has been updated
* @param changedProperties Properties that has changed
* @returns {void}
*/
protected updated (changedProperties: PropertyValues): void {
super.updated(changedProperties);
if (changedProperties.has('suggestions')) {
this.notifySuggestions();
}
this.changedCallbacks(changedProperties);
}
/**
* inheritance callbacks
*/
/**
* Run when the slot has changed.
* @param event Slot change query
* @returns {void}
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected onSlotChange (event: Event): void {
const contentSlot = this.contentSlotRef.value;
const nodes = (contentSlot && contentSlot.assignedNodes()) || [];
this.setOpened(this.attachTargetFocused && this.hasContent);
// make a brave assumption that suggestions are populated as well
const suggestions = this.suggestions;
this.highlightItem(); // hide highlight
this.suggestionMap.clear();
nodes.forEach((node, idx) => {
/* istanbul ignore next */
if (node.nodeType !== Node.ELEMENT_NODE) {
return;
}
const suggestion = suggestions[idx];
if (this.highlightable(suggestion, node as HTMLElement)) {
this.suggestionMap.set(node as HTMLElement, suggestion);
}
});
}
/**
* 'suggestions-query' default action
* @param event Suggestion query
* @returns {void}
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected suggestionsQueryAction (event: CustomEvent): void {
this.query = this.attachTarget && this.attachTarget.value;
}
/**
* 'item-select' default action
* @param event Select action
* @returns {void}
*/
protected itemSelectAction (event: AutosuggestSelectItemEvent): void {
const { detail: { query, suggestion } } = event;
/* istanbul ignore next */
if (this.attachTarget) {
this.attachTarget.value = suggestion && suggestion?.label || query;
}
}
/**
* 'item-highlight' default action
* @param event Highlight action
* @returns {void}
*/
protected itemHighlightAction (event: AutosuggestHighlightItemEvent): void {
const target = event.detail.target;
const oldTarget = event.detail.oldTarget;
if (target) {
target.highlighted = true;
// Required for aria-activedescendant to work correctly
target.setAttribute('aria-selected', 'true');
}
if (oldTarget) {
oldTarget.highlighted = false;
oldTarget.setAttribute('aria-selected', 'false');
}
}
/**
* 'suggestions-fetch-requested' default action
* @param event Fetch request
* @returns {void}
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected suggestionsFetchRequestedAction (event: CustomEvent): void {
// do nothing
}
/**
* 'suggestions-clear-requested' default action
* @param event Clear request
* @returns {void}
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected suggestionsClearRequestedAction (event: CustomEvent): void {
this.suggestions = [];
}
/**
* Add listeners to the attached target
* By default `input`, 'keydown', 'focus' and 'blur' events are listened
* @param event Attach add action
* @returns {void}
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected attachEventsAddAction (event: CustomEvent): void {
const attachTarget = this.attachTarget;
/* istanbul ignore next */
if (!attachTarget) {
return;
}
attachTarget.addEventListener('input', this.onInputValueChange);
attachTarget.addEventListener('keydown', this.onInputKeyDown);
attachTarget.addEventListener('blur', this.onInputBlur);
attachTarget.addEventListener('focus', this.onInputFocus);
}
/**
* Remove event listeners from the attached target
* By default `input`, 'keydown', 'focus' and 'blur' events are listened
* @param event Attach remove action
* @returns {void}
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected attachEventsRemoveAction (event: CustomEvent): void {
const attachTarget = this.attachTarget;
if (!attachTarget) {
return;
}
attachTarget.removeEventListener('input', this.onInputValueChange);
attachTarget.removeEventListener('keydown', this.onInputKeyDown);
attachTarget.removeEventListener('blur', this.onInputBlur);
attachTarget.removeEventListener('focus', this.onInputFocus);
}
/**
* Call this method to fetch more results
* @returns {void}
*/
protected fetchMoreSuggestions (): void {
this.dispatchSuggestionsFetchRequested('more-results');
}
/**
* Highlight the item and remove old highlighted item
* @param target Element to highlight. Pass null to just remove previous highlight
* @param silent Do not fire a select event on highlight. Select should be fired on keyboard navigation
* @returns {void}
*/
protected highlightItem (target: HTMLElement | null = null, silent = true): void {
if (this.highlightedItem !== target) {
const oldTarget = this.highlightedItem;
this.highlightedItem = target && this.canSelect(target) ? target : null;
/**
* @event item-highlight
* Fired when an item gets highlighted or highlight is removed
* @param {HTMLElement} [target] New highlight target or null
* @param {*} [suggestion] New suggestion or null
* @param {HTMLElement} [oldTarget] Old highlight target or null
* @param {*} [oldSuggestion] Old suggestion or null
*/
this.dispatchEventDefault(new CustomEvent('item-highlight', {
cancelable: true,
detail: {
target: this.highlightedItem,
suggestion: this.getSuggestionFor(this.highlightedItem),
oldTarget,
oldSuggestion: this.getSuggestionFor(oldTarget)
}
}), this.itemHighlightAction);
if (!silent && target) {
this.selectItem(target, 'navigation');
}
}
}
// Used to escape unsafe string character
// TODO: think of a nicer way to do this
private xmlSerializer: XMLSerializer | null = null;
/**
* Calculate more search text inner html
* @returns innerHTML
*/
protected get moreResultsTextTemplate (): TemplateResult | null {
if (!this.moreResults) {
return null;
}
if (!this.xmlSerializer) {
this.xmlSerializer = new XMLSerializer();
}
const query = this.xmlSerializer.serializeToString(document.createTextNode(this.query ? this.query.toString() : ''));
return html`
<span part="more-results-text">${this.moreSearchText
? unsafeHTML(this.moreSearchText.replace(/{0\}/g, `<mark>${query}</mark>`))
: this.t('MORE_RESULTS', {
query,
mark: (chunks: string) => `<mark>${chunks}</mark>`
})
}</span>
<span part="more-results-keys" slot="right"><kbd>SHIFT</kbd> + <kbd>ENTER</kbd></span>
`;
}
/**
* Call this method to request suggestions
* @private
* @param reason The reason to request query
* @param debounce True to debounce
* @returns {void}
*/
protected requestSuggestions (reason: AutosuggestReason, debounce = false): void {
this.dispatchSuggestionsQuery(reason);
if (this.preservedQueryValue === this.query) { // if the query is the same do not re-issue the request, instead try to open auto suggest
if (!this.opened && ((this.suggestions && this.suggestions.length) || this.moreResults)) {
this.setOpened(true);
}
return;
}
this.preservedQueryValue = this.query;
const dispatch = (): void => {
if (this.attachTargetFocused) {
this.dispatchSuggestionsFetchRequested(reason);
}
};
if (debounce) {
// debounce
this.jobRunner.schedule(dispatch);
return;
}
this.jobRunner.cancel();
dispatch();
}
/**
* All internal opened set events can be stoppable externally
* Use this instead of setting opened directly
* Protected method that can be used by managers or subclasses
* @returns {void}
*/
protected onOpened (): void {
super.onOpened();
document.addEventListener('tapstart', this.onOutsideClick);
}
/**
* Run when the popup has closed, managers are de-registered
* and closing transition has finished
* @returns {void}
*/
protected onClosed (): void {
super.onClosed();
this.restrictContentMaxHeight();
document.removeEventListener('tapstart', this.onOutsideClick);
}
/**
* enter key processing
* @param event Enter
* @returns {void}
*/
protected onEnterKey (event: KeyboardEvent): void {
if (!this.opened) {
this.requestSuggestions('enter-pressed');
return;
}
/* istanbul ignore next */
if (this.loading) {
return;
}
// more results
if (this.moreResults && event.shiftKey) {
this.fetchMoreSuggestions();
return;
}
if (!this.highlightedItem) {
this.setOpened(false);
return;
}
this.highlightedItem && this.selectItem(this.highlightedItem, 'enter');
}
/**
* Up key processing
* @returns {void}
*/
protected onUpKey (): void {
if (!this.opened) {
this.requestSuggestions('suggestions-revealed');
return;
}
/* istanbul ignore next */
if (this.loading) {
return;
}
this.focusElement(-1);
}
/**
* Down key processing
* @returns {void}
*/
protected onDownKey (): void {
if (!this.opened) {
this.requestSuggestions('suggestions-revealed');
return;
}
/* istanbul ignore next */
if (this.loading) {
return;
}
this.focusElement(1);
}
/**
* Esc key processing
* @returns {void}
*/
protected onEscKey (): void {
if (this.opened) {
// if preserved value exists, set it back
this.dispatchItemSelect('reset');
this.setOpened(false);
return;
}
if (this.query) {
this.suspend();
this.dispatchItemSelect('clear');
this.resume();
this.requestSuggestions('escape-pressed');
}
}
/**
* Highlight it on mouse move
* @param event for item
* @returns {void}
*/
protected onItemMouseMove (event: MouseEvent): void {
this.highlightItem(this.getTarget(event));
}
/**
* @param target Item to check
* @returns true if an item can be highlighted and selectable
*/
protected canSelect (target: HTMLElement): boolean {
return this.suggestionMap.has(target) || (this.moreResults && target === this.moreResultsItem);
}
/**
* Get suggestion for target
* @param target Target to check
* @returns suggestion
*/
protected getSuggestionFor (target: HTMLElement | null): AutosuggestItem {
return target && this.suggestionMap.get(target);
}
/**
* Select the item from the list
* @param target Element to select
* @param method 'click', 'enter' or 'navigation'
* @returns {void}
*/
protected selectItem (target: HTMLElement, method: AutosuggestMethodType): void {
if (this.canSelect(target)) {
// more results
if (target === this.moreResultsItem) {
this.dispatchItemSelect('reset');
switch (method) {
case 'click':
case 'enter':
this.fetchMoreSuggestions();
break;
default:
// node default
}
return;
}
this.dispatchItemSelect(method, target);
switch (method) {
case 'click':
case 'enter':
this.dispatchSuggestionsClearRequested();
break;
default:
// node default
}
}
}
/**
* Get the list of rendered suggestions
* @returns renderedSuggestions
*/
protected get renderedSuggestions (): Array<HTMLElement> {
const keys = [];
this.suggestionMap.forEach((value, key) => { // support IE11
keys.push(key);
});
if (this.moreResults && this.moreResultsItem) {
keys.push(this.moreResultsItem);
}
return keys;
}
/**
* Fired when mouse leave event happens. Remove highlight from the item
* @returns {void}
*/
/* istanbul ignore next */
protected onItemMouseLeave (): void {
this.highlightItem(); // remove highlight
}
/**
* Fired when mouse click event happens. Select an item
* @param event Mouse click event
* @returns {void}
*/
protected onItemMouseClick (event: MouseEvent): void {
const target = this.getTarget(event);
if (target) {
this.selectItem(target, 'click');
}
}
/**
* check some of native properties was modified
* @param changedProperties properties that was changed
* @returns true if some of changedProperties modified
*/
private shouldAutosuggestUpdate (changedProperties: PropertyValues): boolean {
return changedProperties.has('attach')
|| changedProperties.has('suggestions')
|| changedProperties.has('moreResults')
|| changedProperties.has('moreSearchText')
|| changedProperties.has('loading')
|| changedProperties.has('debounceRate')
|| changedProperties.has(TranslatePropertyKey);
}
/**
* Run when document click event happens.
* @param event object
* @returns {void}
*/
private onOutsideClick (event: TapEvent): void {
const path = event.composedPath();
// outside click
if (!path.includes(this) && this.attachTarget && !path.includes(this.attachTarget)) {
this.setOpened(false);
}
}
private changedCallbacks (changedProperties: PropertyValues): void {