cx 24.5.2 → 24.6.1

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