This repository has been archived by the owner on Mar 21, 2024. It is now read-only.
/
LookupField.js
796 lines (740 loc) · 29.2 KB
/
LookupField.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
/* Copyright (c) 2010, Sage Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The LookupField is similiar to an Edit View in that it is a field that takes the user to another
* view but the difference is that an EditorField takes the user to an Edit View, whereas LookupField
* takes the user to a List View.
*
* Meaning that LookupField is meant for establishing relationships by only storing the key for a value
* and with displayed text.
*
* ###Example:
* {
* name: 'Owner',
* property: 'Owner',
* label: this.ownerText,
* type: 'lookup',
* view: 'user_list'
* }
*
* @alternateClassName LookupField
* @extends _Field
* @mixins _TemplatedWidgetMixin
* @mixins _MessageMapMixin
* @requires utility
* @requires Scene
*/
define('argos/Fields/LookupField', [
'dojo/_base/array',
'dojo/_base/declare',
'dojo/_base/event',
'dojo/_base/lang',
'dojo/string',
'dojo/query',
'../_TemplatedWidgetMixin',
'../_MessageMapMixin',
'./_Field',
'../utility',
'argos!scene'
], function(
array,
declare,
event,
lang,
string,
query,
_TemplatedWidgetMixin,
_MessageMapMixin,
_Field,
utility,
scene
) {
return declare('argos.Fields.LookupField', [_Field, _TemplatedWidgetMixin, _MessageMapMixin], {
messages: {
'onSelection': '_onSelection'
},
/**
* @property {Simplate}
* Simplate that defines the fields HTML Markup
*
* * `$` => Field instance
* * `$$` => Owner View instance
*
*/
widgetTemplate: new Simplate([
'<button class="button simpleSubHeaderButton" aria-label="{%: $.lookupLabelText %}"><span aria-hidden="true">{%: $.lookupText %}</span></button>',
'<input data-dojo-attach-point="inputNode" type="text" placeholder="{%: $.placeHolder %}" {% if ($.requireSelection) { %}readonly="readonly"{% } %} />'
]),
_setInputValueAttr: { node: 'inputNode', type: 'attribute', attribute: 'value' },
_setInputDisabledAttr: { node: 'inputNode', type: 'attribute', attribute: 'disabled' },
_setInputReadOnlyAttr: { node: 'inputNode', type: 'attribute', attribute: 'readonly' },
// Localization
/**
* @property {String}
* Error text shown when validation fails.
*
* * `${0}` is the label text of the field
*/
dependentErrorText: "A value for '${0}' must be selected.",
/**
* @cfg {String}
* Text displayed when the field is cleared or set to null
*/
emptyText: '',
/**
* @cfg {String}
* Text used for the label in the toolbar item Complete passed in the navigation options.
*/
completeText: 'Select',
/**
* @cfg {String}
* Text used for the label in the toolbar item Cancel passed in the navigation options.
*/
cancelText: 'Cancel',
/**
* @property {String}
* The ARIA label text in the lookup button
*/
lookupLabelText: 'lookup',
/**
* @property {String}
* The text placed inside the lookup button
*/
lookupText: '...',
/**
* @cfg {String}
* Required. Must be set to a view id of the target lookup view
*/
view: false,
/**
* @property {String}
* The default `valueKeyProperty` if `valueKeyProperty` is not defined.
*/
keyProperty: '$key',
/**
* @property {String}
* The default `valueTextProperty` if `valueTextProperty` is not defined.
*/
textProperty: '$descriptor',
/**
* @cfg {String}
* Adds a watermark/placeholder into the input field when no value is set.
*/
placeHolder: null,
/**
* @cfg {Simplate}
* If provided the displayed textProperty is transformed with the given Simplate.
*
* * `$` => value extracted
* * `$$` => field instance
*
* Note that this (and renderer) are destructive, meaning once transformed the stored
* text value will be the result of the template/renderer. Typically this is not a concern
* as SData will only use the key property. But be aware if any other fields use this field as
* context.
*
*/
textTemplate: null,
/**
* @cfg {Function}
* If provided the displayed textProperty is transformed with the given function.
*
* The function is passed the current value and should return a string to be displayed.
*
* Note that this (and renderer) are destructive, meaning once transformed the stored
* text value will be the result of the template/renderer. Typically this is not a concern
* as SData will only use the key property. But be aware if any other fields use this field as
* context.
*
*/
textRenderer: null,
/**
* @cfg {String}
* The property name of the returned entry to use as the key
*/
valueKeyProperty: null,
/**
* @cfg {String}
* The property name of the returned entry to use as the displayed text/description
*/
valueTextProperty: null,
/**
* @cfg {Boolean}
* Flag that indicates the field is required and that a choice has to be made. If false,
* it passes the navigation option that {@link List List} views listen for for adding a "Empty"
* selection choice.
*/
requireSelection: true,
/**
* @property {Boolean}
* Sets the singleSelect navigation option and if true limits gather the value from the
* target list view to the first selection.
*/
singleSelect: true,
/**
* @property {String}
* The data-action of the toolbar item (which will be hidden) sent in navigation options. This
* with `singleSelect` is listened to in {@link List List} so clicking a row invokes the action,
* which is the function name defined (on the field instance in this case).
*/
singleSelectAction: 'complete',
/**
* @cfg {String}
* Name of the field in which this fields depends on before going to the target view. The value
* is retrieved from the dependOn field and passed to expandable navigation options (resourceKind,
* where, resourcePredicate and previousSelections).
*
* If dependsOn is set, the target field does not have a value and a user attempts to do a lookup
* an error will be shown.
*
*/
dependsOn: null,
/**
* @cfg {String/Function}
* May be set and passed in the navigation options to the target List view.
*
* Used to indicate the entity type.
*
*/
resourceKind: null,
/**
* @cfg {String/Function}
* May be set and passed in the navigation options to the target List view.
*/
resourcePredicate: null,
/**
* @cfg {String/Function}
* May be set and passed in the navigation options to the target List view.
*
* Sets the where expression used in the SData query of the List view.
*/
where: null,
/**
* @cfg {String/Function}
* May be set and passed in the navigation options to the target List view.
*
* Sets the orderBy expression used in the SData query of the List view.
*/
orderBy: null,
/**
* @property {Object}
* The current value object defined using the extracted key/text properties from the selected
* entry.
*/
currentValue: null,
/**
* @property {Object}
* The entire selected entry from the target view (not just the key/text properties).
*/
currentSelection: null,
/**
* @cfg {Boolean}
*
*/
useSelectionForNew: null,
/**
* Extends startup to connect to the click event, if the field is read only disable and
* if require selection is false connect to onkeyup and onblur.
*/
startup: function() {
this.inherited(arguments);
this.connect(this.containerNode, 'onclick', this._onClick);
if (this.isReadOnly())
{
this.disable();
this.set('inputReadOnly', true);
}
else if (!this.requireSelection)
{
this.connect(this.inputNode, 'onkeyup', this._onKeyUp);
this.connect(this.inputNode, 'onblur', this._onBlur);
}
},
/**
* Extends enable to also remove the disabled attribute
*/
enable: function() {
this.inherited(arguments);
this.set('inputDisabled', false);
},
/**
* Extends disable to also set the disabled attribute
*/
disable: function() {
this.inherited(arguments);
this.set('inputDisabled', true);
},
/**
* Determines if the field is readonly by checking for a target view
* @return {Boolean}
*/
isReadOnly: function() {
return !this.view;
},
/**
* Retrieves the value of the field named with `this.dependsOn`
* @return {String/Object/Number/Boolean}
*/
getDependentValue: function() {
if (this.dependsOn && this.owner)
{
var field = this.owner.fields[this.dependsOn];
if (field) return field.getValue();
}
},
/**
* Retrieves the label string of the field named with `this.dependsOn`
* @return {String}
*/
getDependentLabel: function() {
if (this.dependsOn && this.owner)
{
var field = this.owner.fields[this.dependsOn];
if (field) return field.label;
}
},
/**
* Expands the passed expression if it is a function.
* @param {String/Function} expression Returns string directly, if function it is called and the result returned.
* @return {String} String expression.
*/
expandExpression: function(expression) {
if (typeof expression === 'function')
return expression.apply(this, Array.prototype.slice.call(arguments, 1));
else
return expression;
},
/**
* Creates the options to be passed in navigation to the target view
*
* Key points of the options set by default:
*
* * enableActions = false, List views should not be showing their list-actions bar this hides it
* * selectionOnly = true, List views should not allow editing/viewing, just selecting
* * negateHistory = true, disables saving of this options object when storing the history context
* * tools = {}, overrides the toolbar of the target view so that the function that fires is invoked
* in the context of this field, not the List.
*
* The following options are "expandable" meaning they can be strings or functions that return strings:
*
* resourceKind, resourcePredicate, where and previousSelections
*
* They will be passed the `dependsOn` field value (if defined).
*
*/
createNavigationOptions: function() {
var options = {
selectionOnly: true,
singleSelect: this.singleSelect,
singleSelectAction: this.singleSelectAction || 'complete',
allowEmptySelection: !this.requireSelection,
resourceKind: this.resourceKind,
resourcePredicate: this.resourcePredicate,
where: this.where,
orderBy: this.orderBy,
negateHistory: true,
notifyOnSelection: this.id,
tools: {
top: [{
name: 'complete',
cls: this.singleSelect && (this.singleSelectAction || 'complete'),
label: this.completeText,
fn: this.complete,
scope: this
},{
name: 'cancel',
label: this.cancelText,
place: 'left',
publish: '/app/scene/back'
}]
}
},
expand = ['resourceKind', 'resourcePredicate', 'where', 'previousSelections'],
dependentValue = this.getDependentValue();
if (this.dependsOn && !dependentValue)
{
alert(string.substitute(this.dependentErrorText, [this.getDependentLabel()]));
return false;
}
array.forEach(expand, function(item) {
if (this[item])
options[item] = this.dependsOn // only pass dependentValue if there is a dependency
? this.expandExpression(this[item], dependentValue)
: this.expandExpression(this[item]);
}, this);
options.dependentValue = dependentValue;
options.title = this.title;
if (this.options)
lang.mixin(options, this.options);
return options;
},
/**
* Navigates to the `this.view` id passing the options created from {@link #createNavigationOptions createNavigationOptions}.
*/
navigateToListView: function() {
if (this.disabled) return;
var options = this.createNavigationOptions();
scene().showView(this.view, options);
},
_onSelection: function(selections) {
this.setSelection(selections[0]);
this._onComplete();
},
/**
* Handler for the click event, fires {@link #navigateToListView navigateToListView} if the
* field is not disabled.
* @param evt
*/
_onClick: function(evt) {
var buttonNode = query(evt.target).closest('.button')[0];
if (!this.isDisabled() && (buttonNode || this.requireSelection))
{
event.stop(evt);
this.navigateToListView();
}
},
/**
* Handler for onkeyup, fires {@link #onNotificationTrigger onNotificationTrigger} if
* `this.notificationTrigger` is `'keyup'`.
* @param {Event} evt Click event
*/
_onKeyUp: function(evt) {
if (!this.isDisabled() && this.notificationTrigger == 'keyup')
this.onNotificationTrigger(evt);
},
/**
* Handler for onblur, fires {@link #onNotificationTrigger onNotificationTrigger} if
* `this.notificationTrigger` is `'blur'`.
* @param {Event} evt Blur event
*/
_onBlur: function(evt) {
if (!this.isDisabled() && this.notificationTrigger == 'blur')
this.onNotificationTrigger(evt);
},
/**
* Called from onkeyup and onblur handlers if the trigger is set.
*
* Checks the current value against `this.previousValue` and if different
* fires {@link #onChange onChange}.
*
* @param {Event} evt
*/
onNotificationTrigger: function(evt) {
var currentValue = this.getValue();
if (this.previousValue != currentValue)
this.onChange(currentValue, this);
this.previousValue = currentValue;
},
/**
* Sets the displayed text of the field
* @param {String} text
*/
setText: function(text) {
this.set('inputValue', text);
this.previousValue = text;
},
/**
* Returns the string text of the field (note, not the value of the field)
* @return {String}
*/
getText: function() {
return this.inputNode.value;
},
/**
* Called from the target list view when a row is selected.
*
* The intent of the complete function is to gather the value(s) from the list view and
* transfer them to the field - then handle navigating back to the Edit view.
*
* The target view must be the currently active view and must have a selection model.
*
* The values are gathered and passed to {@link #setSelection setSelection}, `ReUI.back()` is
* fired and lastly {@link #_onComplete _onComplete} is called in a setTimeout due to bizarre
* transition issues, namely in IE.
*/
complete: function(view, item) {
// todo: should there be a better way?
if (view && view.get('selectionModel'))
{
var selectionModel = view.get('selectionModel'),
selections = selectionModel.getSelections();
if (selectionModel.getSelectionCount() == 0 && view.options.allowEmptySelection)
this.clearValue(true);
if (this.singleSelect)
{
for (var selectionKey in selections)
{
var val = selections[selectionKey].data;
this.setSelection(val, selectionKey);
break;
}
}
else
{
this.setSelections(selections);
}
scene().back();
// if the event is fired before the transition, any XMLHttpRequest created in an event handler and
// executing during the transition can potentially fail (status 0). this might only be an issue with CORS
// requests created in this state (the pre-flight request is made, and the request ends with status 0).
// wrapping thing in a timeout and placing after the transition starts, mitigates this issue.
setTimeout(lang.hitch(this, this._onComplete), 0);
}
},
/**
* Forces {@link #onChange onChange} to fire
*/
_onComplete: function() {
this.onChange(this.currentValue, this);
},
/**
* Determines if the field has been altered from the default/template value.
* @return {Boolean}
*/
isDirty: function() {
if (this.originalValue && this.currentValue)
{
if (this.originalValue.key != this.currentValue.key)
return true;
if (this.originalValue.text != this.currentValue.text)
return true;
if (!this.requireSelection && !this.textTemplate)
if (this.originalValue.text != this.getText())
return true;
return false;
}
if (this.originalValue)
{
if (!this.requireSelection && !this.textTemplate)
if (this.originalValue.text != this.getText())
return true;
}
else
{
if (!this.requireSelection && !this.textTemplate)
{
var text = this.getText();
if (text && text.length > 0)
return true;
}
}
return (this.originalValue != this.currentValue);
},
/**
* Returns the current selection that was set from the target list view.
* @return {Object}
*/
getSelection: function() {
return this.currentSelection;
},
/**
* Returns the current value either by extracting the valueKeyProperty and valueTextProperty or
* several other methods of getting it to that state.
* @return {Object/String}
*/
getValue: function() {
var value = null,
text = this.getText() || '',
// if valueKeyProperty or valueTextProperty IS NOT EXPLICITLY set to false
// and IS NOT defined use keyProperty or textProperty in its place.
keyProperty = this.valueKeyProperty !== false
? this.valueKeyProperty || this.keyProperty
: false,
textProperty = this.valueTextProperty !== false
? this.valueTextProperty || this.textProperty
: false;
if (keyProperty || textProperty)
{
if (this.currentValue)
{
if (this.useSelectionForNew && !this.currentValue.key)
{
return this.currentSelection;
}
if (keyProperty)
value = utility.setValue(value || {}, keyProperty, this.currentValue.key || this.currentValue.text); /* todo: validate change from just `text` */
// if a text template has been applied there is no way to guarantee a correct
// mapping back to the property
if (textProperty && !this.textTemplate)
value = utility.setValue(value || {}, textProperty, this.requireSelection ? this.currentValue.text : text);
}
else if (!this.requireSelection)
{
if (keyProperty && text.length > 0)
value = utility.setValue(value || {}, keyProperty, text);
// if a text template has been applied there is no way to guarantee a correct
// mapping back to the property
if (textProperty && !this.textTemplate && text.length > 0)
{
value = utility.setValue(value || {}, textProperty, text);
}
}
}
else
{
if (this.currentValue)
{
value = this.requireSelection
? this.currentValue.key || this.currentValue.text /* todo: validate change from just `key` */
: this.currentValue.text != text && !this.textTemplate
? text
: this.currentValue.key || this.currentValue.text; /* todo: validate change from just `key` */
}
else if (!this.requireSelection && text.length > 0)
{
value = text;
}
}
return value;
},
/**
* If using a multi-select enabled lookup then the view will return multiple objects as the value.
*
* This function takes that array and returns the single value that should be used for `this.currentValue`.
*
* @template
* @param {Object[]} values
* @return {Object/String}
*/
formatValue: function(values) {
return values;
},
/**
* If using a multi-select enabled lookup this function will be called by {@link #complete complete}
* in that the target view returned multiple entries.
*
* Sets the currentValue using {@link #formatValue formatValue}.
*
* Sets the displayed text using `this.textRenderer`.
*
* @param {Object[]} values
*/
setSelections: function(values) {
this.currentValue = (this.formatValue)
? this.formatValue.call(this, values)
: values;
var text = (this.textRenderer)
? this.textRenderer.call(this, values)
: '';
this.setText(text);
},
/**
* If using a singleSelect enabled lookup this function will be called by {@link #complete complete}
* and the single entry's data and key will be passed to this function.
*
* Sets the `this.currentSelection` to the passed data (entire entry)
*
* Sets the `this.currentValue` to the extract key/text properties
*
* Calls {@link #setText setText} with the extracted text property.
*
* @param {Object} val Entire selection entry
* @param {String} key data-key attribute of the selected row (typically $key from SData)
*/
setSelection: function(val, sourceKey) {
var key = utility.getValue(val, this.keyProperty),
text = utility.getValue(val, this.textProperty);
// if we can extract the key as requested, use it instead of the selection key
if (!key) key = sourceKey;
if (text && this.textTemplate)
text = this.textTemplate.apply(text, this);
else if (this.textRenderer)
text = this.textRenderer.call(this, val, key, text);
this.currentSelection = val;
this.currentValue = {
key: key, /* todo: validate change from `key || text` */
text: text || key
};
this.setText(text);
},
/**
* Sets the given value to `this.currentValue` using the initial flag if to set it as
* clean/unmodified or false for dirty.
* @param {Object/String} val Value to set
* @param {Boolean} initial Dirty flag (true is clean)
*/
setValue: function(val, initial) {
// if valueKeyProperty or valueTextProperty IS NOT EXPLICITLY set to false
// and IS NOT defined use keyProperty or textProperty in its place.
var key,
text,
keyProperty = this.valueKeyProperty !== false
? this.valueKeyProperty || this.keyProperty
: false,
textProperty = this.valueTextProperty !== false
? this.valueTextProperty || this.textProperty
: false;
if (typeof val === 'undefined' || val == null)
{
this.currentValue = false;
if (initial) this.originalValue = this.currentValue;
this.setText(this.requireSelection ? this.emptyText : '');
return false;
}
if (keyProperty || textProperty)
{
if (keyProperty)
key = utility.getValue(val, keyProperty);
if (textProperty)
text = utility.getValue(val, textProperty);
if (text && this.textTemplate)
text = this.textTemplate.apply(text, this);
else if (this.textRenderer)
text = this.textRenderer.call(this, val, key, text);
if (key || text)
{
this.currentValue = {
key: key, /* todo: validate change from `key || text` */
text: text || key
};
if (initial) this.originalValue = this.currentValue;
this.setText(this.currentValue.text);
}
else
{
this.currentValue = false;
if (initial) this.originalValue = this.currentValue;
this.setText(this.requireSelection ? this.emptyText : '');
}
}
else
{
key = val;
text = val;
if (text && this.textTemplate)
text = this.textTemplate.apply(text, this);
else if (this.textRenderer)
text = this.textRenderer.call(this, val, key, text);
this.currentValue = {
key: key,
text: text
};
if (initial) this.originalValue = this.currentValue;
this.setText(text);
}
},
/**
* Clears the value by setting null (which triggers usage of `this.emptyText`.
*
* Flag is used to indicate if to set null as the initial value (unmodified) or not.
*
* @param {Boolean} flag
*/
clearValue: function(flag) {
var initial = flag !== true;
this.setValue(null, initial);
}
});
});