cx 24.0.1 → 24.0.3

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