cx 23.12.2 → 23.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1131 +1,1131 @@
1
- import { Widget, VDOM, getContent } from "../../ui/Widget";
2
- import { Cx } from "../../ui/Cx";
3
- import { Field, getFieldTooltip } from "./Field";
4
- import { ReadOnlyDataView } from "../../data/ReadOnlyDataView";
5
- import { HtmlElement } from "../HtmlElement";
6
- import { Binding } from "../../data/Binding";
7
- import { debug } from "../../util/Debug";
8
- import { Dropdown } from "../overlay/Dropdown";
9
- import { FocusManager } from "../../ui/FocusManager";
10
- import { isFocused } from "../../util/DOM";
11
- import { isTouchDevice } from "../../util/isTouchDevice";
12
- import { isTouchEvent } from "../../util/isTouchEvent";
13
- import {
14
- tooltipParentWillReceiveProps,
15
- tooltipParentWillUnmount,
16
- tooltipMouseMove,
17
- tooltipMouseLeave,
18
- tooltipParentDidMount,
19
- } from "../overlay/tooltip-ops";
20
- import { stopPropagation, preventDefault } from "../../util/eventCallbacks";
21
- import ClearIcon from "../icons/clear";
22
- import DropdownIcon from "../icons/drop-down";
23
- import { getSearchQueryPredicate } from "../../util/getSearchQueryPredicate";
24
- import { KeyCode } from "../../util/KeyCode";
25
- import { Localization } from "../../ui/Localization";
26
- import { StringTemplate } from "../../data/StringTemplate";
27
- import { Icon } from "../Icon";
28
- import { isString } from "../../util/isString";
29
- import { isDefined } from "../../util/isDefined";
30
- import { isArray } from "../../util/isArray";
31
- import { isNonEmptyArray } from "../../util/isNonEmptyArray";
32
- import { addEventListenerWithOptions } from "../../util/addEventListenerWithOptions";
33
- import { List } from "../List";
34
- import { Selection } from "../../ui/selection/Selection";
35
- import { HighlightedSearchText } from "../HighlightedSearchText";
36
- import { autoFocus } from "../autoFocus";
37
- import { bind } from "../../ui";
38
- import { isAccessorChain } from "../../data/createAccessorModelProxy";
39
-
40
- export class LookupField extends Field {
41
- declareData() {
42
- let additionalAttributes = this.multiple
43
- ? { values: undefined, records: undefined }
44
- : { value: undefined, text: undefined };
45
-
46
- super.declareData(
47
- {
48
- disabled: undefined,
49
- enabled: undefined,
50
- placeholder: undefined,
51
- required: undefined,
52
- options: undefined,
53
- icon: undefined,
54
- autoOpen: undefined,
55
- readOnly: undefined,
56
- filterParams: { structured: true },
57
- },
58
- additionalAttributes,
59
- ...arguments
60
- );
61
- }
62
-
63
- init() {
64
- if (isDefined(this.hideClear)) this.showClear = !this.hideClear;
65
-
66
- if (this.alwaysShowClear) this.showClear = true;
67
-
68
- if (!this.bindings) {
69
- let b = [];
70
- if (this.value) {
71
- if (isAccessorChain(this.value)) this.value = bind(this.value);
72
- if (this.value.bind)
73
- b.push({
74
- key: true,
75
- local: this.value.bind,
76
- remote: `$option.${this.optionIdField}`,
77
- set: this.value.set,
78
- });
79
- }
80
-
81
- if (this.text) {
82
- if (isAccessorChain(this.text)) this.text = bind(this.text);
83
- if (this.text.bind)
84
- b.push({
85
- local: this.text.bind,
86
- remote: `$option.${this.optionTextField}`,
87
- set: this.text.set,
88
- });
89
- }
90
-
91
- this.bindings = b;
92
- }
93
-
94
- if (this.bindings.length == 0 && this.multiple)
95
- this.bindings = [
96
- {
97
- key: true,
98
- local: `$value.${this.valueIdField}`,
99
- remote: `$option.${this.optionIdField}`,
100
- },
101
- {
102
- local: `$value.${this.valueTextField}`,
103
- remote: `$option.${this.optionTextField}`,
104
- },
105
- ];
106
-
107
- this.keyBindings = this.bindings.filter((b) => b.key);
108
-
109
- if (!this.items && !this.children)
110
- this.items = {
111
- $type: HighlightedSearchText,
112
- text: { bind: `$option.${this.optionTextField}` },
113
- query: { bind: "$query" },
114
- };
115
-
116
- this.itemConfig = this.children || this.items;
117
-
118
- delete this.items;
119
- delete this.children;
120
-
121
- super.init();
122
- }
123
-
124
- prepareData(context, instance) {
125
- let { data, store } = instance;
126
-
127
- data.stateMods = {
128
- multiple: this.multiple,
129
- single: !this.multiple,
130
- disabled: data.disabled,
131
- readonly: data.readOnly,
132
- };
133
-
134
- data.visibleOptions = data.options;
135
- if (this.onCreateVisibleOptionsFilter && isArray(data.options)) {
136
- let filterPredicate = instance.invoke("onCreateVisibleOptionsFilter", data.filterParams, instance);
137
- data.visibleOptions = data.options.filter(filterPredicate);
138
- }
139
-
140
- data.selectedKeys = [];
141
-
142
- if (this.multiple) {
143
- if (isArray(data.values) && isArray(data.options)) {
144
- data.selectedKeys = data.values.map((v) => (this.keyBindings.length == 1 ? [v] : v));
145
- let map = {};
146
- data.options.filter(($option) => {
147
- let optionKey = getOptionKey(this.keyBindings, { $option });
148
- for (let i = 0; i < data.selectedKeys.length; i++)
149
- if (areKeysEqual(optionKey, data.selectedKeys[i])) {
150
- map[i] = convertOption(this.bindings, { $option });
151
- break;
152
- }
153
- });
154
- data.records = [];
155
- for (let i = 0; i < data.selectedKeys.length; i++) if (map[i]) data.records.push(map[i]);
156
- } else if (isArray(data.records))
157
- data.selectedKeys.push(
158
- ...data.records.map(($value) => this.keyBindings.map((b) => Binding.get(b.local).value({ $value })))
159
- );
160
- } else {
161
- let dataViewData = store.getData();
162
- data.selectedKeys.push(this.keyBindings.map((b) => Binding.get(b.local).value(dataViewData)));
163
- if (!this.text && isArray(data.options)) {
164
- let option = data.options.find(($option) =>
165
- areKeysEqual(getOptionKey(this.keyBindings, { $option }), data.selectedKeys[0])
166
- );
167
- data.text = (option && option[this.optionTextField]) || "";
168
- }
169
- }
170
-
171
- instance.lastDropdown = context.lastDropdown;
172
-
173
- super.prepareData(context, instance);
174
- }
175
-
176
- renderInput(context, instance, key) {
177
- return (
178
- <LookupComponent
179
- key={key}
180
- multiple={this.multiple}
181
- instance={instance}
182
- itemConfig={this.itemConfig}
183
- bindings={this.bindings}
184
- baseClass={this.baseClass}
185
- label={this.labelPlacement && getContent(this.renderLabel(context, instance, "label"))}
186
- help={this.helpPlacement && getContent(this.renderHelp(context, instance, "help"))}
187
- forceUpdate={context.forceUpdate}
188
- />
189
- );
190
- }
191
-
192
- filterOptions(instance, options, query) {
193
- if (!query) return options;
194
- let textPredicate = getSearchQueryPredicate(query);
195
- return options.filter((o) => isString(o[this.optionTextField]) && textPredicate(o[this.optionTextField]));
196
- }
197
-
198
- isEmpty(data) {
199
- if (this.multiple) return !isNonEmptyArray(data.values) && !isNonEmptyArray(data.records);
200
- return super.isEmpty(data);
201
- }
202
-
203
- formatValue(context, instance) {
204
- if (!this.multiple) return super.formatValue(context, instance);
205
-
206
- let { records, values, options } = instance.data;
207
- if (isArray(records)) {
208
- let valueTextFormatter =
209
- this.onGetRecordDisplayText ?? ((record) => record[this.valueTextField] || record[this.valueIdField]);
210
- return records.map((record) => valueTextFormatter(record, instance));
211
- }
212
-
213
- if (isArray(values)) {
214
- if (isArray(options))
215
- return values
216
- .map((id) => {
217
- let option = options.find((o) => o[this.optionIdField] == id);
218
- return option ? option[this.valueTextField] : id;
219
- })
220
- .filter(Boolean)
221
- .join(", ");
222
-
223
- return values.join(", ");
224
- }
225
-
226
- return null;
227
- }
228
- }
229
-
230
- LookupField.prototype.baseClass = "lookupfield";
231
- //LookupField.prototype.memoize = false;
232
- LookupField.prototype.multiple = false;
233
- LookupField.prototype.queryDelay = 150;
234
- LookupField.prototype.minQueryLength = 0;
235
- LookupField.prototype.hideSearchField = false;
236
- LookupField.prototype.minOptionsForSearchField = 7;
237
- LookupField.prototype.loadingText = "Loading...";
238
- LookupField.prototype.queryErrorText = "Error occurred while querying for lookup data.";
239
- LookupField.prototype.noResultsText = "No results found.";
240
- LookupField.prototype.optionIdField = "id";
241
- LookupField.prototype.optionTextField = "text";
242
- LookupField.prototype.valueIdField = "id";
243
- LookupField.prototype.valueTextField = "text";
244
- LookupField.prototype.suppressErrorsUntilVisited = true;
245
- LookupField.prototype.fetchAll = false;
246
- LookupField.prototype.cacheAll = false;
247
- LookupField.prototype.showClear = true;
248
- LookupField.prototype.alwaysShowClear = false;
249
- LookupField.prototype.closeOnSelect = true;
250
- LookupField.prototype.minQueryLengthMessageText = "Type in at least {0} character(s).";
251
- LookupField.prototype.icon = null;
252
- LookupField.prototype.sort = false;
253
- LookupField.prototype.listOptions = null;
254
- LookupField.prototype.autoOpen = false;
255
- LookupField.prototype.submitOnEnterKey = false;
256
- LookupField.prototype.submitOnDropdownEnterKey = false;
257
- LookupField.prototype.pageSize = 100;
258
- LookupField.prototype.infinite = false;
259
- LookupField.prototype.quickSelectAll = false;
260
- LookupField.prototype.onGetRecordDisplayText = null;
261
-
262
- Localization.registerPrototype("cx/widgets/LookupField", LookupField);
263
-
264
- Widget.alias("lookupfield", LookupField);
265
-
266
- function getOptionKey(bindings, data) {
267
- return bindings.filter((a) => a.key).map((b) => Binding.get(b.remote).value(data));
268
- }
269
-
270
- function areKeysEqual(key1, key2) {
271
- if (!key1 || !key2 || key1.length != key2.length) return false;
272
-
273
- for (let i = 0; i < key1.length; i++) if (key1[i] !== key2[i]) return false;
274
-
275
- return true;
276
- }
277
-
278
- function convertOption(bindings, data) {
279
- let result = { $value: {} };
280
- bindings.forEach((b) => {
281
- let value = Binding.get(b.remote).value(data);
282
- result = Binding.get(b.local).set(result, value);
283
- });
284
- return result.$value;
285
- }
286
-
287
- class SelectionDelegate extends Selection {
288
- constructor({ delegate }) {
289
- super();
290
- this.delegate = delegate;
291
- }
292
-
293
- getIsSelectedDelegate(store) {
294
- return (record, index) => this.delegate(record, index);
295
- }
296
-
297
- select() {
298
- return false;
299
- }
300
- }
301
-
302
- class LookupComponent extends VDOM.Component {
303
- constructor(props) {
304
- super(props);
305
- let { data, store } = this.props.instance;
306
- this.dom = {};
307
- this.state = {
308
- options: [],
309
- formatted: data.formatted,
310
- value: data.formatted,
311
- dropdownOpen: false,
312
- focus: false,
313
- };
314
-
315
- this.itemStore = new ReadOnlyDataView({
316
- store: store,
317
- });
318
- }
319
-
320
- getOptionKey(data) {
321
- return this.props.bindings.filter((a) => a.key).map((b) => Binding.get(b.remote).value(data));
322
- }
323
-
324
- getLocalKey(data) {
325
- return this.props.bindings.filter((a) => a.key).map((b) => Binding.get(b.local).value(data));
326
- }
327
-
328
- findOption(options, key) {
329
- if (!key) return -1;
330
- for (let i = 0; i < options.length; i++) {
331
- let optionKey = this.getOptionKey({ $option: options[i] });
332
- if (areKeysEqual(key, optionKey)) return i;
333
- }
334
- return -1;
335
- }
336
-
337
- getDropdown() {
338
- if (this.dropdown) return this.dropdown;
339
-
340
- let { widget, lastDropdown } = this.props.instance;
341
-
342
- this.list = Widget.create(
343
- <cx>
344
- <List
345
- sortField={widget.sort && widget.optionTextField}
346
- sortDirection="ASC"
347
- mod="dropdown"
348
- scrollSelectionIntoView
349
- cached={widget.infinite}
350
- {...widget.listOptions}
351
- records-bind="$options"
352
- recordName="$option"
353
- onItemClick={(e, inst) => this.onItemClick(e, inst)}
354
- pipeKeyDown={(kd) => {
355
- this.listKeyDown = kd;
356
- }}
357
- selectOnTab
358
- focusable={false}
359
- selection={{
360
- type: SelectionDelegate,
361
- delegate: (data) =>
362
- this.props.instance.data.selectedKeys.find((x) =>
363
- areKeysEqual(x, this.getOptionKey({ $option: data }))
364
- ) != null,
365
- }}
366
- >
367
- {this.props.itemConfig}
368
- </List>
369
- </cx>
370
- );
371
-
372
- let dropdown = {
373
- constrain: true,
374
- scrollTracking: true,
375
- inline: !isTouchDevice() || !!lastDropdown,
376
- placementOrder: "down-right down-left up-right up-left",
377
- ...widget.dropdownOptions,
378
- type: Dropdown,
379
- relatedElement: this.dom.input,
380
- renderChildren: () => this.renderDropdownContents(),
381
- onFocusOut: (e) => this.closeDropdown(e),
382
- memoize: false,
383
- touchFriendly: isTouchDevice(),
384
- onMeasureNaturalContentSize: () => {
385
- if (this.dom.dropdown && this.dom.list) {
386
- return {
387
- height:
388
- this.dom.dropdown.offsetHeight -
389
- this.dom.list.offsetHeight +
390
- (this.dom.list.firstElementChild?.offsetHeight || 0),
391
- };
392
- }
393
- },
394
- onDismissAfterScroll: () => {
395
- this.closeDropdown(null, true);
396
- return false;
397
- },
398
- };
399
-
400
- return (this.dropdown = Widget.create(dropdown));
401
- }
402
-
403
- renderDropdownContents() {
404
- let content;
405
- let { instance } = this.props;
406
- let { data, widget } = instance;
407
- let { CSS, baseClass } = widget;
408
-
409
- let searchVisible =
410
- !widget.hideSearchField &&
411
- (!isArray(data.visibleOptions) ||
412
- (widget.minOptionsForSearchField && data.visibleOptions.length >= widget.minOptionsForSearchField));
413
-
414
- if (this.state.status == "loading") {
415
- content = (
416
- <div key="msg" className={CSS.element(baseClass, "message", "loading")}>
417
- {widget.loadingText}
418
- </div>
419
- );
420
- } else if (this.state.status == "error") {
421
- content = (
422
- <div key="msg" className={CSS.element(baseClass, "message", "error")}>
423
- {widget.queryErrorText}
424
- </div>
425
- );
426
- } else if (this.state.status == "info") {
427
- content = (
428
- <div key="msg" className={CSS.element(baseClass, "message", "info")}>
429
- {this.state.message}
430
- </div>
431
- );
432
- } else if (this.state.options.length == 0) {
433
- content = (
434
- <div key="msg" className={CSS.element(baseClass, "message", "no-results")}>
435
- {widget.noResultsText}
436
- </div>
437
- );
438
- } else {
439
- content = (
440
- <div
441
- key="msg"
442
- ref={(el) => {
443
- this.dom.list = el;
444
- this.subscribeListOnWheel(el);
445
- this.subscribeListOnScroll(el);
446
- }}
447
- className={CSS.element(baseClass, "scroll-container")}
448
- >
449
- <Cx widget={this.list} store={this.itemStore} options={{ name: "lookupfield-list" }} />
450
- </div>
451
- );
452
- }
453
-
454
- return (
455
- <div
456
- key="dropdown"
457
- ref={(el) => {
458
- this.dom.dropdown = el;
459
- }}
460
- className={CSS.element(baseClass, "dropdown")}
461
- tabIndex={0}
462
- onFocus={(e) => this.onDropdownFocus(e)}
463
- onKeyDown={(e) => this.onDropdownKeyPress(e)}
464
- >
465
- {searchVisible && (
466
- <input
467
- key="query"
468
- ref={(el) => {
469
- this.dom.query = el;
470
- }}
471
- type="text"
472
- className={CSS.element(baseClass, "query")}
473
- onClick={(e) => {
474
- e.preventDefault();
475
- e.stopPropagation();
476
- }}
477
- onChange={(e) => this.query(e.target.value)}
478
- onBlur={(e) => this.onQueryBlur(e)}
479
- />
480
- )}
481
- {content}
482
- </div>
483
- );
484
- }
485
-
486
- onListWheel(e) {
487
- let { list } = this.dom;
488
- if (
489
- (list.scrollTop + list.offsetHeight == list.scrollHeight && e.deltaY > 0) ||
490
- (list.scrollTop == 0 && e.deltaY < 0)
491
- ) {
492
- e.preventDefault();
493
- e.stopPropagation();
494
- }
495
- }
496
-
497
- onListScroll() {
498
- if (!this.dom.list) return;
499
- var el = this.dom.list;
500
- if (el.scrollTop > el.scrollHeight - 2 * el.offsetHeight) {
501
- this.loadAdditionalOptionPages();
502
- }
503
- }
504
-
505
- onDropdownFocus(e) {
506
- if (this.dom.query && !isFocused(this.dom.query) && !isTouchDevice()) FocusManager.focus(this.dom.query);
507
- }
508
-
509
- getPlaceholder(text) {
510
- let { CSS, baseClass } = this.props.instance.widget;
511
-
512
- if (text) return <span className={CSS.element(baseClass, "placeholder")}>{text}</span>;
513
-
514
- return <span className={CSS.element(baseClass, "placeholder")}>&nbsp;</span>;
515
- }
516
-
517
- render() {
518
- let { instance, label, help } = this.props;
519
- let { data, widget, state } = instance;
520
- let { CSS, baseClass, suppressErrorsUntilVisited } = widget;
521
-
522
- let icon = data.icon && (
523
- <div
524
- key="icon"
525
- className={CSS.element(baseClass, "left-icon")}
526
- onMouseDown={preventDefault}
527
- onClick={(e) => {
528
- this.openDropdown(e);
529
- e.stopPropagation();
530
- e.preventDefault();
531
- }}
532
- >
533
- {Icon.render(data.icon, {
534
- className: CSS.element(baseClass, "icon"),
535
- })}
536
- </div>
537
- );
538
-
539
- let dropdown;
540
- if (this.state.dropdownOpen) {
541
- this.itemStore.setData({
542
- $options: this.state.options,
543
- $query: this.lastQuery,
544
- });
545
- dropdown = (
546
- <Cx widget={this.getDropdown()} store={this.itemStore} options={{ name: "lookupfield-dropdown" }} />
547
- );
548
- }
549
-
550
- let insideButton = null;
551
- let multipleEntries = this.props.multiple && isArray(data.records) && data.records.length > 1;
552
-
553
- if (!data.readOnly) {
554
- if (
555
- widget.showClear &&
556
- !data.disabled &&
557
- !data.empty &&
558
- (widget.alwaysShowClear || (!data.required && !this.props.multiple) || multipleEntries)
559
- ) {
560
- insideButton = (
561
- <div
562
- key="ib"
563
- onMouseDown={preventDefault}
564
- onClick={(e) => (!this.props.multiple ? this.onClearClick(e) : this.onClearMultipleClick(e))}
565
- className={CSS.element(baseClass, "clear")}
566
- >
567
- <ClearIcon className={CSS.element(baseClass, "icon")} />
568
- </div>
569
- );
570
- } else {
571
- insideButton = (
572
- <div
573
- key="ib"
574
- className={CSS.element(baseClass, "tool")}
575
- onMouseDown={preventDefault}
576
- onClick={(e) => {
577
- this.toggleDropdown(e, true);
578
- e.stopPropagation();
579
- e.preventDefault();
580
- }}
581
- >
582
- <DropdownIcon className={CSS.element(baseClass, "icon")} />
583
- </div>
584
- );
585
- }
586
- }
587
-
588
- let text;
589
-
590
- if (this.props.multiple) {
591
- let readOnly = data.disabled || data.readOnly;
592
- if (isNonEmptyArray(data.records)) {
593
- let valueTextFormatter = widget.onGetRecordDisplayText ?? ((record) => record[widget.valueTextField]);
594
- text = data.records.map((v, i) => (
595
- <div
596
- key={i}
597
- className={CSS.element(baseClass, "tag", {
598
- readonly: readOnly,
599
- })}
600
- >
601
- <span className={CSS.element(baseClass, "tag-value")}>{valueTextFormatter(v, instance)}</span>
602
- {!readOnly && (
603
- <div
604
- className={CSS.element(baseClass, "tag-clear")}
605
- onMouseDown={(e) => {
606
- e.preventDefault();
607
- e.stopPropagation();
608
- }}
609
- onClick={(e) => this.onClearClick(e, v)}
610
- >
611
- <ClearIcon className={CSS.element(baseClass, "icon")} />
612
- </div>
613
- )}
614
- </div>
615
- ));
616
- } else {
617
- text = this.getPlaceholder(data.placeholder);
618
- }
619
- } else {
620
- text = !data.empty ? data.text || this.getPlaceholder() : this.getPlaceholder(data.placeholder);
621
- }
622
-
623
- let states = {
624
- visited: state.visited,
625
- focus: this.state.focus || this.state.dropdownOpen,
626
- icon: !!data.icon,
627
- empty: !data.placeholder && data.empty,
628
- error: data.error && (state.visited || !suppressErrorsUntilVisited || !data.empty),
629
- };
630
-
631
- return (
632
- <div
633
- className={CSS.expand(data.classNames, CSS.state(states))}
634
- style={data.style}
635
- onMouseDown={stopPropagation}
636
- onTouchStart={stopPropagation}
637
- onKeyDown={(e) => this.onKeyDown(e)}
638
- >
639
- <div
640
- id={data.id}
641
- className={CSS.expand(CSS.element(widget.baseClass, "input"), data.inputClass)}
642
- style={data.inputStyle}
643
- tabIndex={data.disabled ? null : data.tabIndex || 0}
644
- ref={(el) => {
645
- this.dom.input = el;
646
- }}
647
- aria-labelledby={data.id + "-label"}
648
- onMouseMove={(e) => tooltipMouseMove(e, ...getFieldTooltip(this.props.instance))}
649
- onMouseLeave={(e) => tooltipMouseLeave(e, ...getFieldTooltip(this.props.instance))}
650
- onClick={(e) => this.onClick(e)}
651
- onInput={(e) => this.onChange(e, "input")}
652
- onChange={(e) => this.onChange(e, "change")}
653
- onKeyDown={(e) => this.onInputKeyDown(e)}
654
- onMouseDown={(e) => this.onMouseDown(e)}
655
- onBlur={(e) => this.onBlur(e)}
656
- onFocus={(e) => this.onFocus(e)}
657
- >
658
- {text}
659
- </div>
660
- {insideButton}
661
- {icon}
662
- {dropdown}
663
- {label}
664
- {help}
665
- </div>
666
- );
667
- }
668
-
669
- onMouseDown(e) {
670
- //skip touch start to allow touch scrolling
671
- if (isTouchEvent()) return;
672
- e.preventDefault();
673
- e.stopPropagation();
674
- this.toggleDropdown(e, true);
675
- }
676
-
677
- onClick(e) {
678
- //mouse down will handle it for non-touch events
679
- if (!isTouchEvent()) return;
680
- e.preventDefault();
681
- e.stopPropagation();
682
- this.toggleDropdown(e, true);
683
- }
684
-
685
- onItemClick(e, { store }) {
686
- this.select(e, [store.getData()]);
687
- if (!this.props.instance.widget.submitOnEnterKey || e.type != "keydown") e.stopPropagation();
688
- if (e.keyCode != KeyCode.tab) e.preventDefault();
689
- }
690
-
691
- onClearClick(e, value) {
692
- let { instance } = this.props;
693
- let { data, store, widget } = instance;
694
- let { keyBindings } = widget;
695
- e.stopPropagation();
696
- e.preventDefault();
697
- if (widget.multiple) {
698
- if (isArray(data.records)) {
699
- let itemKey = this.getLocalKey({ $value: value });
700
- let newRecords = data.records.filter((v) => !areKeysEqual(this.getLocalKey({ $value: v }), itemKey));
701
-
702
- instance.set("records", newRecords);
703
-
704
- let newValues = newRecords
705
- .map((rec) => this.getLocalKey({ $value: rec }))
706
- .map((k) => (keyBindings.length == 1 ? k[0] : k));
707
-
708
- instance.set("values", newValues);
709
- }
710
- } else {
711
- this.props.bindings.forEach((b) => {
712
- store.set(b.local, widget.emptyValue);
713
- });
714
- }
715
-
716
- if (!isTouchEvent(e)) this.dom.input.focus();
717
- }
718
-
719
- onClearMultipleClick(e) {
720
- let { instance } = this.props;
721
- instance.set("records", []);
722
- instance.set("values", []);
723
- }
724
-
725
- select(e, itemsData, reset) {
726
- let { instance } = this.props;
727
- let { store, data, widget } = instance;
728
- let { bindings, keyBindings } = widget;
729
-
730
- if (widget.multiple) {
731
- let { selectedKeys, records } = data;
732
-
733
- let newRecords = reset ? [] : [...(records || [])];
734
- let singleSelect = itemsData.length == 1;
735
- let optionKey = null;
736
- if (singleSelect) optionKey = this.getOptionKey(itemsData[0]);
737
-
738
- // deselect
739
- if (singleSelect && selectedKeys.find((k) => areKeysEqual(optionKey, k))) {
740
- newRecords = records.filter((v) => !areKeysEqual(optionKey, this.getLocalKey({ $value: v })));
741
- } else {
742
- itemsData.forEach((itemData) => {
743
- let valueData = {
744
- $value: {},
745
- };
746
- bindings.forEach((b) => {
747
- valueData = Binding.get(b.local).set(valueData, Binding.get(b.remote).value(itemData));
748
- });
749
- newRecords.push(valueData.$value);
750
- });
751
- }
752
-
753
- instance.set("records", newRecords);
754
-
755
- let newValues = newRecords
756
- .map((rec) => this.getLocalKey({ $value: rec }))
757
- .map((k) => (keyBindings.length == 1 ? k[0] : k));
758
-
759
- instance.set("values", newValues);
760
- } else {
761
- bindings.forEach((b) => {
762
- let v = Binding.get(b.remote).value(itemsData[0]);
763
- if (b.set) b.set(v, instance);
764
- else store.set(b.local, v);
765
- });
766
- }
767
-
768
- if (widget.closeOnSelect) {
769
- //Pressing Tab should work it's own thing. Focus will move elsewhere and the dropdown will close.
770
- if (e.keyCode != KeyCode.tab) {
771
- if (!isTouchEvent(e)) this.dom.input.focus();
772
- this.closeDropdown(e);
773
- }
774
- }
775
-
776
- if (e.keyCode == KeyCode.enter && widget.submitOnDropdownEnterKey) {
777
- this.submitOnEnter(e);
778
- }
779
- }
780
-
781
- onDropdownKeyPress(e) {
782
- switch (e.keyCode) {
783
- case KeyCode.esc:
784
- this.closeDropdown(e);
785
- this.dom.input.focus();
786
- break;
787
-
788
- case KeyCode.tab:
789
- // if tab needs to do a list selection, we have to first call List's handleKeyDown
790
- if (this.listKeyDown) this.listKeyDown(e);
791
- // if next focusable element is disabled, recalculate and update the dom before switching focus
792
- this.props.forceUpdate();
793
- break;
794
-
795
- case KeyCode.a:
796
- if (!e.ctrlKey) return;
797
-
798
- let { quickSelectAll, multiple } = this.props.instance.widget;
799
- if (!quickSelectAll || !multiple) return;
800
-
801
- let optionsToSelect = this.state.options.map((o) => ({
802
- $option: o,
803
- }));
804
- this.select(e, optionsToSelect, true);
805
- e.stopPropagation();
806
- e.preventDefault();
807
- break;
808
-
809
- default:
810
- if (this.listKeyDown) this.listKeyDown(e);
811
- break;
812
- }
813
- }
814
-
815
- onKeyDown(e) {
816
- switch (e.keyCode) {
817
- case KeyCode.pageDown:
818
- case KeyCode.pageUp:
819
- if (this.state.dropdownOpen) e.preventDefault();
820
- break;
821
- }
822
- }
823
-
824
- onInputKeyDown(e) {
825
- let { instance } = this.props;
826
- if (instance.widget.handleKeyDown(e, instance) === false) return;
827
-
828
- switch (e.keyCode) {
829
- case KeyCode.delete:
830
- this.onClearClick(e);
831
- return;
832
-
833
- case KeyCode.shift:
834
- case KeyCode.ctrl:
835
- case KeyCode.tab:
836
- case KeyCode.left:
837
- case KeyCode.right:
838
- case KeyCode.pageUp:
839
- case KeyCode.pageDown:
840
- case KeyCode.insert:
841
- case KeyCode.esc:
842
- break;
843
-
844
- case KeyCode.down:
845
- this.openDropdown(e);
846
- e.stopPropagation();
847
- break;
848
-
849
- case KeyCode.enter:
850
- if (this.props.instance.widget.submitOnEnterKey) {
851
- this.submitOnEnter(e);
852
- } else {
853
- this.openDropdown(e);
854
- }
855
- break;
856
-
857
- default:
858
- this.openDropdown(e);
859
- break;
860
- }
861
- }
862
-
863
- onQueryBlur(e) {
864
- FocusManager.nudge();
865
- }
866
-
867
- onFocus(e) {
868
- let { instance } = this.props;
869
- let { widget } = instance;
870
- if (widget.trackFocus) {
871
- this.setState({
872
- focus: true,
873
- });
874
- }
875
-
876
- if (this.props.instance.data.autoOpen) this.openDropdown(null);
877
- }
878
-
879
- onBlur(e) {
880
- if (!this.state.dropdownOpen) this.props.instance.setState({ visited: true });
881
-
882
- if (this.state.focus)
883
- this.setState({
884
- focus: false,
885
- });
886
- }
887
-
888
- toggleDropdown(e, keepFocus) {
889
- if (this.state.dropdownOpen) this.closeDropdown(e, keepFocus);
890
- else this.openDropdown(e);
891
- }
892
-
893
- closeDropdown(e, keepFocus) {
894
- if (this.state.dropdownOpen) {
895
- this.setState(
896
- {
897
- dropdownOpen: false,
898
- },
899
- () => keepFocus && this.dom.input.focus()
900
- );
901
-
902
- this.props.instance.setState({
903
- visited: true,
904
- });
905
- }
906
-
907
- //delete results valid only while the dropdown is open
908
- delete this.tmpCachedResult;
909
- }
910
-
911
- openDropdown(e) {
912
- let { instance } = this.props;
913
- let { data } = instance;
914
- if (!this.state.dropdownOpen && !data.disabled && !data.readOnly) {
915
- this.query("");
916
- this.setState(
917
- {
918
- dropdownOpen: true,
919
- },
920
- () => {
921
- if (this.dom.dropdown) this.dom.dropdown.focus();
922
- }
923
- );
924
- }
925
- }
926
-
927
- query(q) {
928
- /*
929
- In fetchAll mode onQuery should fetch all data and after
930
- that everything is done filtering is done client-side.
931
- If cacheAll is set results are cached for the lifetime of the
932
- widget, otherwise cache is invalidated when dropdown closes.
933
- */
934
-
935
- let { instance } = this.props;
936
- let { widget, data } = instance;
937
-
938
- this.lastQuery = q;
939
-
940
- //do not make duplicate queries if fetchAll is enabled
941
- if (widget.fetchAll && this.state.status == "loading") return;
942
-
943
- if (this.queryTimeoutId) clearTimeout(this.queryTimeoutId);
944
-
945
- if (q.length < widget.minQueryLength) {
946
- this.setState({
947
- status: "info",
948
- message: StringTemplate.format(widget.minQueryLengthMessageText, widget.minQueryLength),
949
- });
950
- return;
951
- }
952
-
953
- if (isArray(data.visibleOptions)) {
954
- let results = widget.filterOptions(this.props.instance, data.visibleOptions, q);
955
- this.setState({
956
- options: results,
957
- status: "loaded",
958
- });
959
- }
960
-
961
- if (widget.onQuery) {
962
- let { queryDelay, fetchAll, cacheAll, pageSize } = widget;
963
-
964
- if (fetchAll) queryDelay = 0;
965
-
966
- if (!this.cachedResult) {
967
- this.setState({
968
- status: "loading",
969
- });
970
- }
971
-
972
- this.queryTimeoutId = setTimeout(() => {
973
- delete this.queryTimeoutId;
974
-
975
- let result = this.tmpCachedResult || this.cachedResult;
976
- let query = fetchAll ? "" : q;
977
- let params = !widget.infinite
978
- ? query
979
- : {
980
- query,
981
- page: 1,
982
- pageSize,
983
- };
984
-
985
- if (!result) result = instance.invoke("onQuery", params, instance);
986
-
987
- let queryId = (this.lastQueryId = Date.now());
988
-
989
- Promise.resolve(result)
990
- .then((results) => {
991
- //discard results which do not belong to the last query
992
- if (queryId !== this.lastQueryId) return;
993
-
994
- if (!isArray(results)) results = [];
995
-
996
- if (fetchAll) {
997
- if (cacheAll) this.cachedResult = results;
998
- else this.tmpCachedResult = results;
999
-
1000
- results = widget.filterOptions(this.props.instance, results, this.lastQuery);
1001
- }
1002
-
1003
- this.setState(
1004
- {
1005
- page: 1,
1006
- query,
1007
- options: results,
1008
- status: "loaded",
1009
- },
1010
- () => {
1011
- if (widget.infinite) this.onListScroll();
1012
- }
1013
- );
1014
- })
1015
- .catch((err) => {
1016
- this.setState({ status: "error" });
1017
- debug("Lookup query error:", err);
1018
- });
1019
- }, queryDelay);
1020
- }
1021
- }
1022
-
1023
- loadAdditionalOptionPages() {
1024
- let { instance } = this.props;
1025
- let { widget } = instance;
1026
- if (!widget.infinite) return;
1027
-
1028
- let { query, page, status, options } = this.state;
1029
-
1030
- let blockerKey = query;
1031
-
1032
- if (status != "loaded") return;
1033
-
1034
- if (options.length < page * widget.pageSize) return; //some pages were not full which means we reached the end
1035
-
1036
- if (this.extraPageLoadingBlocker === blockerKey) return;
1037
-
1038
- this.extraPageLoadingBlocker = blockerKey;
1039
-
1040
- let params = {
1041
- page: page + 1,
1042
- query,
1043
- pageSize: widget.pageSize,
1044
- };
1045
-
1046
- var result = instance.invoke("onQuery", params, instance);
1047
-
1048
- Promise.resolve(result)
1049
- .then((results) => {
1050
- //discard results which do not belong to the last query
1051
- if (this.extraPageLoadingBlocker !== blockerKey) return;
1052
-
1053
- this.extraPageLoadingBlocker = false;
1054
-
1055
- if (!isArray(results)) return;
1056
-
1057
- this.setState(
1058
- {
1059
- page: params.page,
1060
- query,
1061
- options: [...options, ...results],
1062
- },
1063
- () => {
1064
- this.onListScroll();
1065
- }
1066
- );
1067
- })
1068
- .catch((err) => {
1069
- if (this.extraPageLoadingBlocker !== blockerKey) return;
1070
- this.extraPageLoadingBlocker = false;
1071
- this.setState({ status: "error" });
1072
- debug("Lookup query error:", err);
1073
- console.error(err);
1074
- });
1075
- }
1076
-
1077
- UNSAFE_componentWillReceiveProps(props) {
1078
- tooltipParentWillReceiveProps(this.dom.input, ...getFieldTooltip(props.instance));
1079
- }
1080
-
1081
- componentDidMount() {
1082
- tooltipParentDidMount(this.dom.input, ...getFieldTooltip(this.props.instance));
1083
- autoFocus(this.dom.input, this);
1084
- }
1085
-
1086
- componentDidUpdate() {
1087
- autoFocus(this.dom.input, this);
1088
- }
1089
-
1090
- componentWillUnmount() {
1091
- if (this.queryTimeoutId) clearTimeout(this.queryTimeoutId);
1092
- tooltipParentWillUnmount(this.props.instance);
1093
- this.subscribeListOnWheel(null);
1094
- }
1095
-
1096
- subscribeListOnWheel(list) {
1097
- if (this.unsubscribeListOnWheel) {
1098
- this.unsubscribeListOnWheel();
1099
- this.unsubscribeListOnWheel = null;
1100
- }
1101
- if (list) {
1102
- this.unsubscribeListOnWheel = addEventListenerWithOptions(list, "wheel", (e) => this.onListWheel(e), {
1103
- passive: false,
1104
- });
1105
- }
1106
- }
1107
-
1108
- subscribeListOnScroll(list) {
1109
- if (this.unsubscribeListOnScroll) {
1110
- this.unsubscribeListOnScroll();
1111
- this.unsubscribeListOnScroll = null;
1112
- }
1113
- if (list) {
1114
- this.unsubscribeListOnScroll = addEventListenerWithOptions(list, "scroll", (e) => this.onListScroll(e), {
1115
- passive: false,
1116
- });
1117
- }
1118
- }
1119
-
1120
- submitOnEnter(e) {
1121
- let instance = this.props.instance.parent;
1122
- while (instance) {
1123
- if (instance.events && instance.events.onSubmit) {
1124
- instance.events.onSubmit(e, instance);
1125
- break;
1126
- } else {
1127
- instance = instance.parent;
1128
- }
1129
- }
1130
- }
1131
- }
1
+ import { Widget, VDOM, getContent } from "../../ui/Widget";
2
+ import { Cx } from "../../ui/Cx";
3
+ import { Field, getFieldTooltip } from "./Field";
4
+ import { ReadOnlyDataView } from "../../data/ReadOnlyDataView";
5
+ import { HtmlElement } from "../HtmlElement";
6
+ import { Binding } from "../../data/Binding";
7
+ import { debug } from "../../util/Debug";
8
+ import { Dropdown } from "../overlay/Dropdown";
9
+ import { FocusManager } from "../../ui/FocusManager";
10
+ import { isFocused } from "../../util/DOM";
11
+ import { isTouchDevice } from "../../util/isTouchDevice";
12
+ import { isTouchEvent } from "../../util/isTouchEvent";
13
+ import {
14
+ tooltipParentWillReceiveProps,
15
+ tooltipParentWillUnmount,
16
+ tooltipMouseMove,
17
+ tooltipMouseLeave,
18
+ tooltipParentDidMount,
19
+ } from "../overlay/tooltip-ops";
20
+ import { stopPropagation, preventDefault } from "../../util/eventCallbacks";
21
+ import ClearIcon from "../icons/clear";
22
+ import DropdownIcon from "../icons/drop-down";
23
+ import { getSearchQueryPredicate } from "../../util/getSearchQueryPredicate";
24
+ import { KeyCode } from "../../util/KeyCode";
25
+ import { Localization } from "../../ui/Localization";
26
+ import { StringTemplate } from "../../data/StringTemplate";
27
+ import { Icon } from "../Icon";
28
+ import { isString } from "../../util/isString";
29
+ import { isDefined } from "../../util/isDefined";
30
+ import { isArray } from "../../util/isArray";
31
+ import { isNonEmptyArray } from "../../util/isNonEmptyArray";
32
+ import { addEventListenerWithOptions } from "../../util/addEventListenerWithOptions";
33
+ import { List } from "../List";
34
+ import { Selection } from "../../ui/selection/Selection";
35
+ import { HighlightedSearchText } from "../HighlightedSearchText";
36
+ import { autoFocus } from "../autoFocus";
37
+ import { bind } from "../../ui";
38
+ import { isAccessorChain } from "../../data/createAccessorModelProxy";
39
+
40
+ export class LookupField extends Field {
41
+ declareData() {
42
+ let additionalAttributes = this.multiple
43
+ ? { values: undefined, records: undefined }
44
+ : { value: undefined, text: undefined };
45
+
46
+ super.declareData(
47
+ {
48
+ disabled: undefined,
49
+ enabled: undefined,
50
+ placeholder: undefined,
51
+ required: undefined,
52
+ options: undefined,
53
+ icon: undefined,
54
+ autoOpen: undefined,
55
+ readOnly: undefined,
56
+ filterParams: { structured: true },
57
+ },
58
+ additionalAttributes,
59
+ ...arguments
60
+ );
61
+ }
62
+
63
+ init() {
64
+ if (isDefined(this.hideClear)) this.showClear = !this.hideClear;
65
+
66
+ if (this.alwaysShowClear) this.showClear = true;
67
+
68
+ if (!this.bindings) {
69
+ let b = [];
70
+ if (this.value) {
71
+ if (isAccessorChain(this.value)) this.value = bind(this.value);
72
+ if (this.value.bind)
73
+ b.push({
74
+ key: true,
75
+ local: this.value.bind,
76
+ remote: `$option.${this.optionIdField}`,
77
+ set: this.value.set,
78
+ });
79
+ }
80
+
81
+ if (this.text) {
82
+ if (isAccessorChain(this.text)) this.text = bind(this.text);
83
+ if (this.text.bind)
84
+ b.push({
85
+ local: this.text.bind,
86
+ remote: `$option.${this.optionTextField}`,
87
+ set: this.text.set,
88
+ });
89
+ }
90
+
91
+ this.bindings = b;
92
+ }
93
+
94
+ if (this.bindings.length == 0 && this.multiple)
95
+ this.bindings = [
96
+ {
97
+ key: true,
98
+ local: `$value.${this.valueIdField}`,
99
+ remote: `$option.${this.optionIdField}`,
100
+ },
101
+ {
102
+ local: `$value.${this.valueTextField}`,
103
+ remote: `$option.${this.optionTextField}`,
104
+ },
105
+ ];
106
+
107
+ this.keyBindings = this.bindings.filter((b) => b.key);
108
+
109
+ if (!this.items && !this.children)
110
+ this.items = {
111
+ $type: HighlightedSearchText,
112
+ text: { bind: `$option.${this.optionTextField}` },
113
+ query: { bind: "$query" },
114
+ };
115
+
116
+ this.itemConfig = this.children || this.items;
117
+
118
+ delete this.items;
119
+ delete this.children;
120
+
121
+ super.init();
122
+ }
123
+
124
+ prepareData(context, instance) {
125
+ let { data, store } = instance;
126
+
127
+ data.stateMods = {
128
+ multiple: this.multiple,
129
+ single: !this.multiple,
130
+ disabled: data.disabled,
131
+ readonly: data.readOnly,
132
+ };
133
+
134
+ data.visibleOptions = data.options;
135
+ if (this.onCreateVisibleOptionsFilter && isArray(data.options)) {
136
+ let filterPredicate = instance.invoke("onCreateVisibleOptionsFilter", data.filterParams, instance);
137
+ data.visibleOptions = data.options.filter(filterPredicate);
138
+ }
139
+
140
+ data.selectedKeys = [];
141
+
142
+ if (this.multiple) {
143
+ if (isArray(data.values) && isArray(data.options)) {
144
+ data.selectedKeys = data.values.map((v) => (this.keyBindings.length == 1 ? [v] : v));
145
+ let map = {};
146
+ data.options.filter(($option) => {
147
+ let optionKey = getOptionKey(this.keyBindings, { $option });
148
+ for (let i = 0; i < data.selectedKeys.length; i++)
149
+ if (areKeysEqual(optionKey, data.selectedKeys[i])) {
150
+ map[i] = convertOption(this.bindings, { $option });
151
+ break;
152
+ }
153
+ });
154
+ data.records = [];
155
+ for (let i = 0; i < data.selectedKeys.length; i++) if (map[i]) data.records.push(map[i]);
156
+ } else if (isArray(data.records))
157
+ data.selectedKeys.push(
158
+ ...data.records.map(($value) => this.keyBindings.map((b) => Binding.get(b.local).value({ $value })))
159
+ );
160
+ } else {
161
+ let dataViewData = store.getData();
162
+ data.selectedKeys.push(this.keyBindings.map((b) => Binding.get(b.local).value(dataViewData)));
163
+ if (!this.text && isArray(data.options)) {
164
+ let option = data.options.find(($option) =>
165
+ areKeysEqual(getOptionKey(this.keyBindings, { $option }), data.selectedKeys[0])
166
+ );
167
+ data.text = (option && option[this.optionTextField]) || "";
168
+ }
169
+ }
170
+
171
+ instance.lastDropdown = context.lastDropdown;
172
+
173
+ super.prepareData(context, instance);
174
+ }
175
+
176
+ renderInput(context, instance, key) {
177
+ return (
178
+ <LookupComponent
179
+ key={key}
180
+ multiple={this.multiple}
181
+ instance={instance}
182
+ itemConfig={this.itemConfig}
183
+ bindings={this.bindings}
184
+ baseClass={this.baseClass}
185
+ label={this.labelPlacement && getContent(this.renderLabel(context, instance, "label"))}
186
+ help={this.helpPlacement && getContent(this.renderHelp(context, instance, "help"))}
187
+ forceUpdate={context.forceUpdate}
188
+ />
189
+ );
190
+ }
191
+
192
+ filterOptions(instance, options, query) {
193
+ if (!query) return options;
194
+ let textPredicate = getSearchQueryPredicate(query);
195
+ return options.filter((o) => isString(o[this.optionTextField]) && textPredicate(o[this.optionTextField]));
196
+ }
197
+
198
+ isEmpty(data) {
199
+ if (this.multiple) return !isNonEmptyArray(data.values) && !isNonEmptyArray(data.records);
200
+ return super.isEmpty(data);
201
+ }
202
+
203
+ formatValue(context, instance) {
204
+ if (!this.multiple) return super.formatValue(context, instance);
205
+
206
+ let { records, values, options } = instance.data;
207
+ if (isArray(records)) {
208
+ let valueTextFormatter =
209
+ this.onGetRecordDisplayText ?? ((record) => record[this.valueTextField] || record[this.valueIdField]);
210
+ return records.map((record) => valueTextFormatter(record, instance));
211
+ }
212
+
213
+ if (isArray(values)) {
214
+ if (isArray(options))
215
+ return values
216
+ .map((id) => {
217
+ let option = options.find((o) => o[this.optionIdField] == id);
218
+ return option ? option[this.valueTextField] : id;
219
+ })
220
+ .filter(Boolean)
221
+ .join(", ");
222
+
223
+ return values.join(", ");
224
+ }
225
+
226
+ return null;
227
+ }
228
+ }
229
+
230
+ LookupField.prototype.baseClass = "lookupfield";
231
+ //LookupField.prototype.memoize = false;
232
+ LookupField.prototype.multiple = false;
233
+ LookupField.prototype.queryDelay = 150;
234
+ LookupField.prototype.minQueryLength = 0;
235
+ LookupField.prototype.hideSearchField = false;
236
+ LookupField.prototype.minOptionsForSearchField = 7;
237
+ LookupField.prototype.loadingText = "Loading...";
238
+ LookupField.prototype.queryErrorText = "Error occurred while querying for lookup data.";
239
+ LookupField.prototype.noResultsText = "No results found.";
240
+ LookupField.prototype.optionIdField = "id";
241
+ LookupField.prototype.optionTextField = "text";
242
+ LookupField.prototype.valueIdField = "id";
243
+ LookupField.prototype.valueTextField = "text";
244
+ LookupField.prototype.suppressErrorsUntilVisited = true;
245
+ LookupField.prototype.fetchAll = false;
246
+ LookupField.prototype.cacheAll = false;
247
+ LookupField.prototype.showClear = true;
248
+ LookupField.prototype.alwaysShowClear = false;
249
+ LookupField.prototype.closeOnSelect = true;
250
+ LookupField.prototype.minQueryLengthMessageText = "Type in at least {0} character(s).";
251
+ LookupField.prototype.icon = null;
252
+ LookupField.prototype.sort = false;
253
+ LookupField.prototype.listOptions = null;
254
+ LookupField.prototype.autoOpen = false;
255
+ LookupField.prototype.submitOnEnterKey = false;
256
+ LookupField.prototype.submitOnDropdownEnterKey = false;
257
+ LookupField.prototype.pageSize = 100;
258
+ LookupField.prototype.infinite = false;
259
+ LookupField.prototype.quickSelectAll = false;
260
+ LookupField.prototype.onGetRecordDisplayText = null;
261
+
262
+ Localization.registerPrototype("cx/widgets/LookupField", LookupField);
263
+
264
+ Widget.alias("lookupfield", LookupField);
265
+
266
+ function getOptionKey(bindings, data) {
267
+ return bindings.filter((a) => a.key).map((b) => Binding.get(b.remote).value(data));
268
+ }
269
+
270
+ function areKeysEqual(key1, key2) {
271
+ if (!key1 || !key2 || key1.length != key2.length) return false;
272
+
273
+ for (let i = 0; i < key1.length; i++) if (key1[i] !== key2[i]) return false;
274
+
275
+ return true;
276
+ }
277
+
278
+ function convertOption(bindings, data) {
279
+ let result = { $value: {} };
280
+ bindings.forEach((b) => {
281
+ let value = Binding.get(b.remote).value(data);
282
+ result = Binding.get(b.local).set(result, value);
283
+ });
284
+ return result.$value;
285
+ }
286
+
287
+ class SelectionDelegate extends Selection {
288
+ constructor({ delegate }) {
289
+ super();
290
+ this.delegate = delegate;
291
+ }
292
+
293
+ getIsSelectedDelegate(store) {
294
+ return (record, index) => this.delegate(record, index);
295
+ }
296
+
297
+ select() {
298
+ return false;
299
+ }
300
+ }
301
+
302
+ class LookupComponent extends VDOM.Component {
303
+ constructor(props) {
304
+ super(props);
305
+ let { data, store } = this.props.instance;
306
+ this.dom = {};
307
+ this.state = {
308
+ options: [],
309
+ formatted: data.formatted,
310
+ value: data.formatted,
311
+ dropdownOpen: false,
312
+ focus: false,
313
+ };
314
+
315
+ this.itemStore = new ReadOnlyDataView({
316
+ store: store,
317
+ });
318
+ }
319
+
320
+ getOptionKey(data) {
321
+ return this.props.bindings.filter((a) => a.key).map((b) => Binding.get(b.remote).value(data));
322
+ }
323
+
324
+ getLocalKey(data) {
325
+ return this.props.bindings.filter((a) => a.key).map((b) => Binding.get(b.local).value(data));
326
+ }
327
+
328
+ findOption(options, key) {
329
+ if (!key) return -1;
330
+ for (let i = 0; i < options.length; i++) {
331
+ let optionKey = this.getOptionKey({ $option: options[i] });
332
+ if (areKeysEqual(key, optionKey)) return i;
333
+ }
334
+ return -1;
335
+ }
336
+
337
+ getDropdown() {
338
+ if (this.dropdown) return this.dropdown;
339
+
340
+ let { widget, lastDropdown } = this.props.instance;
341
+
342
+ this.list = Widget.create(
343
+ <cx>
344
+ <List
345
+ sortField={widget.sort && widget.optionTextField}
346
+ sortDirection="ASC"
347
+ mod="dropdown"
348
+ scrollSelectionIntoView
349
+ cached={widget.infinite}
350
+ {...widget.listOptions}
351
+ records-bind="$options"
352
+ recordName="$option"
353
+ onItemClick={(e, inst) => this.onItemClick(e, inst)}
354
+ pipeKeyDown={(kd) => {
355
+ this.listKeyDown = kd;
356
+ }}
357
+ selectOnTab
358
+ focusable={false}
359
+ selection={{
360
+ type: SelectionDelegate,
361
+ delegate: (data) =>
362
+ this.props.instance.data.selectedKeys.find((x) =>
363
+ areKeysEqual(x, this.getOptionKey({ $option: data }))
364
+ ) != null,
365
+ }}
366
+ >
367
+ {this.props.itemConfig}
368
+ </List>
369
+ </cx>
370
+ );
371
+
372
+ let dropdown = {
373
+ constrain: true,
374
+ scrollTracking: true,
375
+ inline: !isTouchDevice() || !!lastDropdown,
376
+ placementOrder: "down-right down-left up-right up-left",
377
+ ...widget.dropdownOptions,
378
+ type: Dropdown,
379
+ relatedElement: this.dom.input,
380
+ renderChildren: () => this.renderDropdownContents(),
381
+ onFocusOut: (e) => this.closeDropdown(e),
382
+ memoize: false,
383
+ touchFriendly: isTouchDevice(),
384
+ onMeasureNaturalContentSize: () => {
385
+ if (this.dom.dropdown && this.dom.list) {
386
+ return {
387
+ height:
388
+ this.dom.dropdown.offsetHeight -
389
+ this.dom.list.offsetHeight +
390
+ (this.dom.list.firstElementChild?.offsetHeight || 0),
391
+ };
392
+ }
393
+ },
394
+ onDismissAfterScroll: () => {
395
+ this.closeDropdown(null, true);
396
+ return false;
397
+ },
398
+ };
399
+
400
+ return (this.dropdown = Widget.create(dropdown));
401
+ }
402
+
403
+ renderDropdownContents() {
404
+ let content;
405
+ let { instance } = this.props;
406
+ let { data, widget } = instance;
407
+ let { CSS, baseClass } = widget;
408
+
409
+ let searchVisible =
410
+ !widget.hideSearchField &&
411
+ (!isArray(data.visibleOptions) ||
412
+ (widget.minOptionsForSearchField && data.visibleOptions.length >= widget.minOptionsForSearchField));
413
+
414
+ if (this.state.status == "loading") {
415
+ content = (
416
+ <div key="msg" className={CSS.element(baseClass, "message", "loading")}>
417
+ {widget.loadingText}
418
+ </div>
419
+ );
420
+ } else if (this.state.status == "error") {
421
+ content = (
422
+ <div key="msg" className={CSS.element(baseClass, "message", "error")}>
423
+ {widget.queryErrorText}
424
+ </div>
425
+ );
426
+ } else if (this.state.status == "info") {
427
+ content = (
428
+ <div key="msg" className={CSS.element(baseClass, "message", "info")}>
429
+ {this.state.message}
430
+ </div>
431
+ );
432
+ } else if (this.state.options.length == 0) {
433
+ content = (
434
+ <div key="msg" className={CSS.element(baseClass, "message", "no-results")}>
435
+ {widget.noResultsText}
436
+ </div>
437
+ );
438
+ } else {
439
+ content = (
440
+ <div
441
+ key="msg"
442
+ ref={(el) => {
443
+ this.dom.list = el;
444
+ this.subscribeListOnWheel(el);
445
+ this.subscribeListOnScroll(el);
446
+ }}
447
+ className={CSS.element(baseClass, "scroll-container")}
448
+ >
449
+ <Cx widget={this.list} store={this.itemStore} options={{ name: "lookupfield-list" }} />
450
+ </div>
451
+ );
452
+ }
453
+
454
+ return (
455
+ <div
456
+ key="dropdown"
457
+ ref={(el) => {
458
+ this.dom.dropdown = el;
459
+ }}
460
+ className={CSS.element(baseClass, "dropdown")}
461
+ tabIndex={0}
462
+ onFocus={(e) => this.onDropdownFocus(e)}
463
+ onKeyDown={(e) => this.onDropdownKeyPress(e)}
464
+ >
465
+ {searchVisible && (
466
+ <input
467
+ key="query"
468
+ ref={(el) => {
469
+ this.dom.query = el;
470
+ }}
471
+ type="text"
472
+ className={CSS.element(baseClass, "query")}
473
+ onClick={(e) => {
474
+ e.preventDefault();
475
+ e.stopPropagation();
476
+ }}
477
+ onChange={(e) => this.query(e.target.value)}
478
+ onBlur={(e) => this.onQueryBlur(e)}
479
+ />
480
+ )}
481
+ {content}
482
+ </div>
483
+ );
484
+ }
485
+
486
+ onListWheel(e) {
487
+ let { list } = this.dom;
488
+ if (
489
+ (list.scrollTop + list.offsetHeight == list.scrollHeight && e.deltaY > 0) ||
490
+ (list.scrollTop == 0 && e.deltaY < 0)
491
+ ) {
492
+ e.preventDefault();
493
+ e.stopPropagation();
494
+ }
495
+ }
496
+
497
+ onListScroll() {
498
+ if (!this.dom.list) return;
499
+ var el = this.dom.list;
500
+ if (el.scrollTop > el.scrollHeight - 2 * el.offsetHeight) {
501
+ this.loadAdditionalOptionPages();
502
+ }
503
+ }
504
+
505
+ onDropdownFocus(e) {
506
+ if (this.dom.query && !isFocused(this.dom.query) && !isTouchDevice()) FocusManager.focus(this.dom.query);
507
+ }
508
+
509
+ getPlaceholder(text) {
510
+ let { CSS, baseClass } = this.props.instance.widget;
511
+
512
+ if (text) return <span className={CSS.element(baseClass, "placeholder")}>{text}</span>;
513
+
514
+ return <span className={CSS.element(baseClass, "placeholder")}>&nbsp;</span>;
515
+ }
516
+
517
+ render() {
518
+ let { instance, label, help } = this.props;
519
+ let { data, widget, state } = instance;
520
+ let { CSS, baseClass, suppressErrorsUntilVisited } = widget;
521
+
522
+ let icon = data.icon && (
523
+ <div
524
+ key="icon"
525
+ className={CSS.element(baseClass, "left-icon")}
526
+ onMouseDown={preventDefault}
527
+ onClick={(e) => {
528
+ this.openDropdown(e);
529
+ e.stopPropagation();
530
+ e.preventDefault();
531
+ }}
532
+ >
533
+ {Icon.render(data.icon, {
534
+ className: CSS.element(baseClass, "icon"),
535
+ })}
536
+ </div>
537
+ );
538
+
539
+ let dropdown;
540
+ if (this.state.dropdownOpen) {
541
+ this.itemStore.setData({
542
+ $options: this.state.options,
543
+ $query: this.lastQuery,
544
+ });
545
+ dropdown = (
546
+ <Cx widget={this.getDropdown()} store={this.itemStore} options={{ name: "lookupfield-dropdown" }} />
547
+ );
548
+ }
549
+
550
+ let insideButton = null;
551
+ let multipleEntries = this.props.multiple && isArray(data.records) && data.records.length > 1;
552
+
553
+ if (!data.readOnly) {
554
+ if (
555
+ widget.showClear &&
556
+ !data.disabled &&
557
+ !data.empty &&
558
+ (widget.alwaysShowClear || (!data.required && !this.props.multiple) || multipleEntries)
559
+ ) {
560
+ insideButton = (
561
+ <div
562
+ key="ib"
563
+ onMouseDown={preventDefault}
564
+ onClick={(e) => (!this.props.multiple ? this.onClearClick(e) : this.onClearMultipleClick(e))}
565
+ className={CSS.element(baseClass, "clear")}
566
+ >
567
+ <ClearIcon className={CSS.element(baseClass, "icon")} />
568
+ </div>
569
+ );
570
+ } else {
571
+ insideButton = (
572
+ <div
573
+ key="ib"
574
+ className={CSS.element(baseClass, "tool")}
575
+ onMouseDown={preventDefault}
576
+ onClick={(e) => {
577
+ this.toggleDropdown(e, true);
578
+ e.stopPropagation();
579
+ e.preventDefault();
580
+ }}
581
+ >
582
+ <DropdownIcon className={CSS.element(baseClass, "icon")} />
583
+ </div>
584
+ );
585
+ }
586
+ }
587
+
588
+ let text;
589
+
590
+ if (this.props.multiple) {
591
+ let readOnly = data.disabled || data.readOnly;
592
+ if (isNonEmptyArray(data.records)) {
593
+ let valueTextFormatter = widget.onGetRecordDisplayText ?? ((record) => record[widget.valueTextField]);
594
+ text = data.records.map((v, i) => (
595
+ <div
596
+ key={i}
597
+ className={CSS.element(baseClass, "tag", {
598
+ readonly: readOnly,
599
+ })}
600
+ >
601
+ <span className={CSS.element(baseClass, "tag-value")}>{valueTextFormatter(v, instance)}</span>
602
+ {!readOnly && (
603
+ <div
604
+ className={CSS.element(baseClass, "tag-clear")}
605
+ onMouseDown={(e) => {
606
+ e.preventDefault();
607
+ e.stopPropagation();
608
+ }}
609
+ onClick={(e) => this.onClearClick(e, v)}
610
+ >
611
+ <ClearIcon className={CSS.element(baseClass, "icon")} />
612
+ </div>
613
+ )}
614
+ </div>
615
+ ));
616
+ } else {
617
+ text = this.getPlaceholder(data.placeholder);
618
+ }
619
+ } else {
620
+ text = !data.empty ? data.text || this.getPlaceholder() : this.getPlaceholder(data.placeholder);
621
+ }
622
+
623
+ let states = {
624
+ visited: state.visited,
625
+ focus: this.state.focus || this.state.dropdownOpen,
626
+ icon: !!data.icon,
627
+ empty: !data.placeholder && data.empty,
628
+ error: data.error && (state.visited || !suppressErrorsUntilVisited || !data.empty),
629
+ };
630
+
631
+ return (
632
+ <div
633
+ className={CSS.expand(data.classNames, CSS.state(states))}
634
+ style={data.style}
635
+ onMouseDown={stopPropagation}
636
+ onTouchStart={stopPropagation}
637
+ onKeyDown={(e) => this.onKeyDown(e)}
638
+ >
639
+ <div
640
+ id={data.id}
641
+ className={CSS.expand(CSS.element(widget.baseClass, "input"), data.inputClass)}
642
+ style={data.inputStyle}
643
+ tabIndex={data.disabled ? null : data.tabIndex || 0}
644
+ ref={(el) => {
645
+ this.dom.input = el;
646
+ }}
647
+ aria-labelledby={data.id + "-label"}
648
+ onMouseMove={(e) => tooltipMouseMove(e, ...getFieldTooltip(this.props.instance))}
649
+ onMouseLeave={(e) => tooltipMouseLeave(e, ...getFieldTooltip(this.props.instance))}
650
+ onClick={(e) => this.onClick(e)}
651
+ onInput={(e) => this.onChange(e, "input")}
652
+ onChange={(e) => this.onChange(e, "change")}
653
+ onKeyDown={(e) => this.onInputKeyDown(e)}
654
+ onMouseDown={(e) => this.onMouseDown(e)}
655
+ onBlur={(e) => this.onBlur(e)}
656
+ onFocus={(e) => this.onFocus(e)}
657
+ >
658
+ {text}
659
+ </div>
660
+ {insideButton}
661
+ {icon}
662
+ {dropdown}
663
+ {label}
664
+ {help}
665
+ </div>
666
+ );
667
+ }
668
+
669
+ onMouseDown(e) {
670
+ //skip touch start to allow touch scrolling
671
+ if (isTouchEvent()) return;
672
+ e.preventDefault();
673
+ e.stopPropagation();
674
+ this.toggleDropdown(e, true);
675
+ }
676
+
677
+ onClick(e) {
678
+ //mouse down will handle it for non-touch events
679
+ if (!isTouchEvent()) return;
680
+ e.preventDefault();
681
+ e.stopPropagation();
682
+ this.toggleDropdown(e, true);
683
+ }
684
+
685
+ onItemClick(e, { store }) {
686
+ this.select(e, [store.getData()]);
687
+ if (!this.props.instance.widget.submitOnEnterKey || e.type != "keydown") e.stopPropagation();
688
+ if (e.keyCode != KeyCode.tab) e.preventDefault();
689
+ }
690
+
691
+ onClearClick(e, value) {
692
+ let { instance } = this.props;
693
+ let { data, store, widget } = instance;
694
+ let { keyBindings } = widget;
695
+ e.stopPropagation();
696
+ e.preventDefault();
697
+ if (widget.multiple) {
698
+ if (isArray(data.records)) {
699
+ let itemKey = this.getLocalKey({ $value: value });
700
+ let newRecords = data.records.filter((v) => !areKeysEqual(this.getLocalKey({ $value: v }), itemKey));
701
+
702
+ instance.set("records", newRecords);
703
+
704
+ let newValues = newRecords
705
+ .map((rec) => this.getLocalKey({ $value: rec }))
706
+ .map((k) => (keyBindings.length == 1 ? k[0] : k));
707
+
708
+ instance.set("values", newValues);
709
+ }
710
+ } else {
711
+ this.props.bindings.forEach((b) => {
712
+ store.set(b.local, widget.emptyValue);
713
+ });
714
+ }
715
+
716
+ if (!isTouchEvent(e)) this.dom.input.focus();
717
+ }
718
+
719
+ onClearMultipleClick(e) {
720
+ let { instance } = this.props;
721
+ instance.set("records", []);
722
+ instance.set("values", []);
723
+ }
724
+
725
+ select(e, itemsData, reset) {
726
+ let { instance } = this.props;
727
+ let { store, data, widget } = instance;
728
+ let { bindings, keyBindings } = widget;
729
+
730
+ if (widget.multiple) {
731
+ let { selectedKeys, records } = data;
732
+
733
+ let newRecords = reset ? [] : [...(records || [])];
734
+ let singleSelect = itemsData.length == 1;
735
+ let optionKey = null;
736
+ if (singleSelect) optionKey = this.getOptionKey(itemsData[0]);
737
+
738
+ // deselect
739
+ if (singleSelect && selectedKeys.find((k) => areKeysEqual(optionKey, k))) {
740
+ newRecords = records.filter((v) => !areKeysEqual(optionKey, this.getLocalKey({ $value: v })));
741
+ } else {
742
+ itemsData.forEach((itemData) => {
743
+ let valueData = {
744
+ $value: {},
745
+ };
746
+ bindings.forEach((b) => {
747
+ valueData = Binding.get(b.local).set(valueData, Binding.get(b.remote).value(itemData));
748
+ });
749
+ newRecords.push(valueData.$value);
750
+ });
751
+ }
752
+
753
+ instance.set("records", newRecords);
754
+
755
+ let newValues = newRecords
756
+ .map((rec) => this.getLocalKey({ $value: rec }))
757
+ .map((k) => (keyBindings.length == 1 ? k[0] : k));
758
+
759
+ instance.set("values", newValues);
760
+ } else {
761
+ bindings.forEach((b) => {
762
+ let v = Binding.get(b.remote).value(itemsData[0]);
763
+ if (b.set) b.set(v, instance);
764
+ else store.set(b.local, v);
765
+ });
766
+ }
767
+
768
+ if (widget.closeOnSelect) {
769
+ //Pressing Tab should work it's own thing. Focus will move elsewhere and the dropdown will close.
770
+ if (e.keyCode != KeyCode.tab) {
771
+ if (!isTouchEvent(e)) this.dom.input.focus();
772
+ this.closeDropdown(e);
773
+ }
774
+ }
775
+
776
+ if (e.keyCode == KeyCode.enter && widget.submitOnDropdownEnterKey) {
777
+ this.submitOnEnter(e);
778
+ }
779
+ }
780
+
781
+ onDropdownKeyPress(e) {
782
+ switch (e.keyCode) {
783
+ case KeyCode.esc:
784
+ this.closeDropdown(e);
785
+ this.dom.input.focus();
786
+ break;
787
+
788
+ case KeyCode.tab:
789
+ // if tab needs to do a list selection, we have to first call List's handleKeyDown
790
+ if (this.listKeyDown) this.listKeyDown(e);
791
+ // if next focusable element is disabled, recalculate and update the dom before switching focus
792
+ this.props.forceUpdate();
793
+ break;
794
+
795
+ case KeyCode.a:
796
+ if (!e.ctrlKey) return;
797
+
798
+ let { quickSelectAll, multiple } = this.props.instance.widget;
799
+ if (!quickSelectAll || !multiple) return;
800
+
801
+ let optionsToSelect = this.state.options.map((o) => ({
802
+ $option: o,
803
+ }));
804
+ this.select(e, optionsToSelect, true);
805
+ e.stopPropagation();
806
+ e.preventDefault();
807
+ break;
808
+
809
+ default:
810
+ if (this.listKeyDown) this.listKeyDown(e);
811
+ break;
812
+ }
813
+ }
814
+
815
+ onKeyDown(e) {
816
+ switch (e.keyCode) {
817
+ case KeyCode.pageDown:
818
+ case KeyCode.pageUp:
819
+ if (this.state.dropdownOpen) e.preventDefault();
820
+ break;
821
+ }
822
+ }
823
+
824
+ onInputKeyDown(e) {
825
+ let { instance } = this.props;
826
+ if (instance.widget.handleKeyDown(e, instance) === false) return;
827
+
828
+ switch (e.keyCode) {
829
+ case KeyCode.delete:
830
+ this.onClearClick(e);
831
+ return;
832
+
833
+ case KeyCode.shift:
834
+ case KeyCode.ctrl:
835
+ case KeyCode.tab:
836
+ case KeyCode.left:
837
+ case KeyCode.right:
838
+ case KeyCode.pageUp:
839
+ case KeyCode.pageDown:
840
+ case KeyCode.insert:
841
+ case KeyCode.esc:
842
+ break;
843
+
844
+ case KeyCode.down:
845
+ this.openDropdown(e);
846
+ e.stopPropagation();
847
+ break;
848
+
849
+ case KeyCode.enter:
850
+ if (this.props.instance.widget.submitOnEnterKey) {
851
+ this.submitOnEnter(e);
852
+ } else {
853
+ this.openDropdown(e);
854
+ }
855
+ break;
856
+
857
+ default:
858
+ this.openDropdown(e);
859
+ break;
860
+ }
861
+ }
862
+
863
+ onQueryBlur(e) {
864
+ FocusManager.nudge();
865
+ }
866
+
867
+ onFocus(e) {
868
+ let { instance } = this.props;
869
+ let { widget } = instance;
870
+ if (widget.trackFocus) {
871
+ this.setState({
872
+ focus: true,
873
+ });
874
+ }
875
+
876
+ if (this.props.instance.data.autoOpen) this.openDropdown(null);
877
+ }
878
+
879
+ onBlur(e) {
880
+ if (!this.state.dropdownOpen) this.props.instance.setState({ visited: true });
881
+
882
+ if (this.state.focus)
883
+ this.setState({
884
+ focus: false,
885
+ });
886
+ }
887
+
888
+ toggleDropdown(e, keepFocus) {
889
+ if (this.state.dropdownOpen) this.closeDropdown(e, keepFocus);
890
+ else this.openDropdown(e);
891
+ }
892
+
893
+ closeDropdown(e, keepFocus) {
894
+ if (this.state.dropdownOpen) {
895
+ this.setState(
896
+ {
897
+ dropdownOpen: false,
898
+ },
899
+ () => keepFocus && this.dom.input.focus()
900
+ );
901
+
902
+ this.props.instance.setState({
903
+ visited: true,
904
+ });
905
+ }
906
+
907
+ //delete results valid only while the dropdown is open
908
+ delete this.tmpCachedResult;
909
+ }
910
+
911
+ openDropdown(e) {
912
+ let { instance } = this.props;
913
+ let { data } = instance;
914
+ if (!this.state.dropdownOpen && !data.disabled && !data.readOnly) {
915
+ this.query("");
916
+ this.setState(
917
+ {
918
+ dropdownOpen: true,
919
+ },
920
+ () => {
921
+ if (this.dom.dropdown) this.dom.dropdown.focus();
922
+ }
923
+ );
924
+ }
925
+ }
926
+
927
+ query(q) {
928
+ /*
929
+ In fetchAll mode onQuery should fetch all data and after
930
+ that everything is done filtering is done client-side.
931
+ If cacheAll is set results are cached for the lifetime of the
932
+ widget, otherwise cache is invalidated when dropdown closes.
933
+ */
934
+
935
+ let { instance } = this.props;
936
+ let { widget, data } = instance;
937
+
938
+ this.lastQuery = q;
939
+
940
+ //do not make duplicate queries if fetchAll is enabled
941
+ if (widget.fetchAll && this.state.status == "loading") return;
942
+
943
+ if (this.queryTimeoutId) clearTimeout(this.queryTimeoutId);
944
+
945
+ if (q.length < widget.minQueryLength) {
946
+ this.setState({
947
+ status: "info",
948
+ message: StringTemplate.format(widget.minQueryLengthMessageText, widget.minQueryLength),
949
+ });
950
+ return;
951
+ }
952
+
953
+ if (isArray(data.visibleOptions)) {
954
+ let results = widget.filterOptions(this.props.instance, data.visibleOptions, q);
955
+ this.setState({
956
+ options: results,
957
+ status: "loaded",
958
+ });
959
+ }
960
+
961
+ if (widget.onQuery) {
962
+ let { queryDelay, fetchAll, cacheAll, pageSize } = widget;
963
+
964
+ if (fetchAll) queryDelay = 0;
965
+
966
+ if (!this.cachedResult) {
967
+ this.setState({
968
+ status: "loading",
969
+ });
970
+ }
971
+
972
+ this.queryTimeoutId = setTimeout(() => {
973
+ delete this.queryTimeoutId;
974
+
975
+ let result = this.tmpCachedResult || this.cachedResult;
976
+ let query = fetchAll ? "" : q;
977
+ let params = !widget.infinite
978
+ ? query
979
+ : {
980
+ query,
981
+ page: 1,
982
+ pageSize,
983
+ };
984
+
985
+ if (!result) result = instance.invoke("onQuery", params, instance);
986
+
987
+ let queryId = (this.lastQueryId = Date.now());
988
+
989
+ Promise.resolve(result)
990
+ .then((results) => {
991
+ //discard results which do not belong to the last query
992
+ if (queryId !== this.lastQueryId) return;
993
+
994
+ if (!isArray(results)) results = [];
995
+
996
+ if (fetchAll) {
997
+ if (cacheAll) this.cachedResult = results;
998
+ else this.tmpCachedResult = results;
999
+
1000
+ results = widget.filterOptions(this.props.instance, results, this.lastQuery);
1001
+ }
1002
+
1003
+ this.setState(
1004
+ {
1005
+ page: 1,
1006
+ query,
1007
+ options: results,
1008
+ status: "loaded",
1009
+ },
1010
+ () => {
1011
+ if (widget.infinite) this.onListScroll();
1012
+ }
1013
+ );
1014
+ })
1015
+ .catch((err) => {
1016
+ this.setState({ status: "error" });
1017
+ debug("Lookup query error:", err);
1018
+ });
1019
+ }, queryDelay);
1020
+ }
1021
+ }
1022
+
1023
+ loadAdditionalOptionPages() {
1024
+ let { instance } = this.props;
1025
+ let { widget } = instance;
1026
+ if (!widget.infinite) return;
1027
+
1028
+ let { query, page, status, options } = this.state;
1029
+
1030
+ let blockerKey = query;
1031
+
1032
+ if (status != "loaded") return;
1033
+
1034
+ if (options.length < page * widget.pageSize) return; //some pages were not full which means we reached the end
1035
+
1036
+ if (this.extraPageLoadingBlocker === blockerKey) return;
1037
+
1038
+ this.extraPageLoadingBlocker = blockerKey;
1039
+
1040
+ let params = {
1041
+ page: page + 1,
1042
+ query,
1043
+ pageSize: widget.pageSize,
1044
+ };
1045
+
1046
+ var result = instance.invoke("onQuery", params, instance);
1047
+
1048
+ Promise.resolve(result)
1049
+ .then((results) => {
1050
+ //discard results which do not belong to the last query
1051
+ if (this.extraPageLoadingBlocker !== blockerKey) return;
1052
+
1053
+ this.extraPageLoadingBlocker = false;
1054
+
1055
+ if (!isArray(results)) return;
1056
+
1057
+ this.setState(
1058
+ {
1059
+ page: params.page,
1060
+ query,
1061
+ options: [...options, ...results],
1062
+ },
1063
+ () => {
1064
+ this.onListScroll();
1065
+ }
1066
+ );
1067
+ })
1068
+ .catch((err) => {
1069
+ if (this.extraPageLoadingBlocker !== blockerKey) return;
1070
+ this.extraPageLoadingBlocker = false;
1071
+ this.setState({ status: "error" });
1072
+ debug("Lookup query error:", err);
1073
+ console.error(err);
1074
+ });
1075
+ }
1076
+
1077
+ UNSAFE_componentWillReceiveProps(props) {
1078
+ tooltipParentWillReceiveProps(this.dom.input, ...getFieldTooltip(props.instance));
1079
+ }
1080
+
1081
+ componentDidMount() {
1082
+ tooltipParentDidMount(this.dom.input, ...getFieldTooltip(this.props.instance));
1083
+ autoFocus(this.dom.input, this);
1084
+ }
1085
+
1086
+ componentDidUpdate() {
1087
+ autoFocus(this.dom.input, this);
1088
+ }
1089
+
1090
+ componentWillUnmount() {
1091
+ if (this.queryTimeoutId) clearTimeout(this.queryTimeoutId);
1092
+ tooltipParentWillUnmount(this.props.instance);
1093
+ this.subscribeListOnWheel(null);
1094
+ }
1095
+
1096
+ subscribeListOnWheel(list) {
1097
+ if (this.unsubscribeListOnWheel) {
1098
+ this.unsubscribeListOnWheel();
1099
+ this.unsubscribeListOnWheel = null;
1100
+ }
1101
+ if (list) {
1102
+ this.unsubscribeListOnWheel = addEventListenerWithOptions(list, "wheel", (e) => this.onListWheel(e), {
1103
+ passive: false,
1104
+ });
1105
+ }
1106
+ }
1107
+
1108
+ subscribeListOnScroll(list) {
1109
+ if (this.unsubscribeListOnScroll) {
1110
+ this.unsubscribeListOnScroll();
1111
+ this.unsubscribeListOnScroll = null;
1112
+ }
1113
+ if (list) {
1114
+ this.unsubscribeListOnScroll = addEventListenerWithOptions(list, "scroll", (e) => this.onListScroll(e), {
1115
+ passive: false,
1116
+ });
1117
+ }
1118
+ }
1119
+
1120
+ submitOnEnter(e) {
1121
+ let instance = this.props.instance.parent;
1122
+ while (instance) {
1123
+ if (instance.events && instance.events.onSubmit) {
1124
+ instance.events.onSubmit(e, instance);
1125
+ break;
1126
+ } else {
1127
+ instance = instance.parent;
1128
+ }
1129
+ }
1130
+ }
1131
+ }