cx 23.6.0 → 23.8.0

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