-
Notifications
You must be signed in to change notification settings - Fork 7
/
DropDown.js
3050 lines (2503 loc) · 112 KB
/
DropDown.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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <container name="Fit.Controls.DropDown" extends="Fit.Controls.ControlBase">
/// Drop Down Menu control allowing for single and multi selection.
/// Supports data selection using any control extending from Fit.Controls.PickerBase.
/// This control is extending from Fit.Controls.ControlBase.
/// </container>
/// <function container="Fit.Controls.DropDown" name="DropDown" access="public">
/// <description> Create instance of DropDown control </description>
/// <param name="ctlId" type="string" default="undefined"> Unique control ID that can be used to access control using Fit.Controls.Find(..) </param>
/// </function>
Fit.Controls.DropDown = function(ctlId)
{
Fit.Validation.ExpectStringValue(ctlId, true);
Fit.Core.Extend(this, Fit.Controls.ControlBase).Apply(ctlId);
var me = this; // Access to members from event handlers (where "this" may have a different meaning)
var itemContainer = null; // Container for selected items and input fields
var itemCollection = {}; // Indexed collection for selected items (for fast lookup)
var itemCollectionOrdered = []; // Ordered item collection (item order can be changed using drag and drop)
var itemDropZones = {}; // Indexed collection of dropzones used to enable item dragging/dropping
var placeholder = ""; // Placeholder value displayed when no selection is made
var arrow = null; // Arrow button used to open/close drop down menu
var txtPrimary = null; // Primary input (search) field initially available
var txtActive = null; // Currently active input (search) field
var txtEnabled = false; // Flag indicating whether user can enter text
var dropDownMenu = null; // Drop down menu element
var picker = null; // Picker control within drop down menu
var orgSelections = []; // Original selection set using Value(..) function - used to determine whether control is dirty
var invalidMessage = "Invalid selection"; // Mouse over text for invalid selections
var invalidMessageChanged = false; // Flag indicating whether built-in Invalid Selection Message has been overridden or not
var initialFocus = true; // Flag indicating first focus of control
var maxHeight = { Value: 150, Unit: "px"}; // Picker max height (px)
var maxWidth = { Value: -1, Unit: "px" }; // Picker max width (px)
var prevValue = ""; // Previous input value - used to determine whether OnChange should be fired
var focusAssigned = false; // Boolean ensuring that control is only given focus when AddSelection is called, if user assigned focus to control
var closeHandlers = []; // Events (IDs) responsible for closing drop down when user clicks outside of control
var dropZone = null; // Active DropZone (drag and drop support)
var isMobile = false; // Flag indicating whether control is running on a mobile (touch) device
var focusInputOnMobile = true; // Flag indicating whether control should focus input fields (and potentially bring up a virtual keyboard) based on configuration, platform (computer vs touch) and where user initially clicked/touched DropDown to activate it
var detectBoundaries = false; // Flag indicating whether drop down menu should detect viewport collision and open upwards when needed
var detectBoundariesRelToViewPort = false; // Flag indicating whether drop down menu should be positioned relative to viewport (true) or scroll parent (false)
var persistView = false; // Flag indicating whether picker controls should remember and restore its scroll position and highlighted item when reopened
var highlightFirst = false; // Flag indicating whether picker controls should focus its first node automatically when opened
var searchModeOnFocus = false; // Flag indicating whether control goes into search mode when it is focused (search mode clears input field and displays "search.." placeholder)
var onInputChangedHandlers = []; // Invoked when input value is changed - takes two arguments (sender (this), text value)
var onPasteHandlers = []; // Invoked when a value is pasted - takes two arguments (sender (this), text value)
var onOpenHandlers = []; // Invoked when drop down is opened - takes one argument (sender (this))
var onCloseHandlers = []; // Invoked when drop down is closed - takes one argument (sender (this))
// Picker - suppress events
var suppressUpdateItemSelectionState = false;
var suppressOnItemSelectionChanged = false;
// Text selection mode
var clearTextSelectionOnInputChange = false;
var prevTextSelection = null;
var textSelectionCallback = null;
var cmdToggleTextMode = null;
function init()
{
Fit.Internationalization.OnLocaleChanged(localize);
localize();
// Initial settings
me._internal.Data("multiselect", "false");
me._internal.Data("selectionmode", "visual");
me._internal.Data("selectionmodetoggle", "false");
me._internal.Data("open", "false");
isMobile = Fit.Device.OptimizeForTouch;
// if (Fit.Browser.GetInfo().IsMobile === true)
// isMobile = true;
// Create item container
itemContainer = document.createElement("div");
itemContainer.tabIndex = -1; // Make it focusable but not part of tab flow
itemContainer.onclick = function(e) // Not triggered when user clicks arrow button - it has its own logic and suppresses event propagation
{
var target = Fit.Events.GetTarget(e);
if (target.tagName !== "INPUT") // Focus input unless already focused (if input was clicked)
{
focusInputOnMobile = me.InputEnabled() === true; // Focus input on mobile only if input is enabled - otherwise we get a virtual keyboard presented which does nothing - user can still click/touch an input between selected items in Visual Selection Mode to place an item between two existing selections
focusAssigned = true; // Clicking the item container causes blur to fire for input fields in drop down which changes focusAssigned to false - it must be true for focusInput(..) to assign focus
focusInput(txtPrimary);
}
me.OpenDropDown();
}
Fit.Dom.AddClass(itemContainer, "FitUiControlDropDownItems");
// Create arrow button used to open drop down
arrow = document.createElement("i");
Fit.Dom.AddClass(arrow, "fa");
Fit.Dom.AddClass(arrow, "fa-chevron-down");
arrow.tabIndex = -1; // Make it focusable but not part of tab flow
arrow.onclick = function(e)
{
focusInputOnMobile = false; // On mobile, do not focus input fields when interacting with control, when DropDown was initially activated by clicking/touching arrow icon
// Close drop down if already open
if (me.IsDropDownOpen() === true)
{
me.CloseDropDown();
if (isMobile === true)
{
me.Focused(false); // Force control to lose focus when closed on mobile, to have the OnBlur event fire
}
}
else // DropDown is closed - open it
{
me.OpenDropDown();
}
if (isMobile === false)
{
focusAssigned = true; // Clicking the arrow causes blur to fire for input fields in drop down which changes focusAssigned to false - it must be true for focusInput(..) to assign focus
focusInput(txtPrimary);
}
Fit.Events.StopPropagation(e); // Prevent event from reaching itemContainer.onclick which opens DropDown and might assign a different value to focusInputOnMobile
}
arrow.onfocus = function(e)
{
focusAssigned = true;
}
arrow.onblur = function(e)
{
if (me === null)
{
// Fix for Chrome which fires OnChange and OnBlur (in both capturering and bubbling phase)
// if control has focus while being removed from DOM, e.g. if used in a dialog closed using ESC.
// More details here: https://bugs.chromium.org/p/chromium/issues/detail?id=866242
return;
}
focusAssigned = false;
}
// Create primary search textbox
txtPrimary = createSearchField();
txtActive = txtPrimary;
// Create drop down menu
dropDownMenu = document.createElement("div");
if (Fit.Browser.GetBrowser() !== "MSIE" || Fit.Browser.GetVersion() >= 9) // OnMouseWheel event is buggy in IE8
{
dropDownMenu.onmousewheel = function(e) // Handler prevents scroll on page when scrolling picker
{
var ev = Fit.Events.GetEvent(e);
dropDownMenu.firstChild.scrollTop -= ((ev.wheelDeltaY !== undefined) ? ev.wheelDeltaY : ev.wheelDelta); // Expecting PickerControl's container (firstChild) to be scrollable for this to work
Fit.Events.PreventDefault(ev);
}
}
Fit.Dom.AddClass(dropDownMenu, "FitUiControlDropDownPicker");
dropDownMenu.style.display = "none"; // Considered closed by default (prevent OnClose from firing if CloseDropDown() is called on closed drop down)
// Make drop down close when user clicks outside of control
if (isMobile === false)
{
var eventId = Fit.Events.AddHandler(document, "click", function(e)
{
var target = Fit.Events.GetTarget(e);
if (target !== document.documentElement && target !== document.body && Fit.Dom.IsRooted(target) === false)
{
return; // Do not close DropDown if target no longer exists - this may happen if something is removed within DropDown (e.g. an item in the WSDropDown's action menu)
}
if (me.IsDropDownOpen() === true && target !== me.GetDomElement() && Fit.Dom.Contained(me.GetDomElement(), target) === false)
{
me.CloseDropDown();
}
});
Fit.Array.Add(closeHandlers, eventId);
}
else
{
// OnClick does not work reliably on mobile (at least not on iOS 9 and 10), so using touch events instead
var coords = null;
var eventId = -1;
eventId = Fit.Events.AddHandler(document, "touchstart", function(e)
{
var target = Fit.Events.GetTarget(e);
coords = null;
if (target !== document.documentElement && target !== document.body && Fit.Dom.IsRooted(target) === false)
{
return; // Do not close DropDown if target no longer exists - this may happen if something is removed within DropDown (e.g. an item in the WSDropDown's action menu)
}
if (me.IsDropDownOpen() === true && target !== me.GetDomElement() && Fit.Dom.Contained(me.GetDomElement(), target) === false)
{
coords = Fit.Events.GetPointerState().Coordinates.Document;
}
});
Fit.Array.Add(closeHandlers, eventId);
eventId = Fit.Events.AddHandler(document, "touchend", function(e)
{
if (coords === null)
return;
// Determine whether user moved finger (e.g. to scroll page) in which case we do not want to close the menu
var curCoords = Fit.Events.GetPointerState().Coordinates.Document;
var moved = (Math.abs(coords.X - curCoords.X) > 10 || Math.abs(coords.Y - curCoords.Y) > 10); // Must be moved at least 10px left/right or up/down
if (moved === false)
{
me.CloseDropDown();
me.Focused(false);
}
});
Fit.Array.Add(closeHandlers, eventId);
}
// Make drop down close if focus is lost on mobile
// which happens when onscreen keyboard is closed.
me.OnBlur(function()
{
focusInputOnMobile = true; // Reset to initial value when focus is lost
if (isMobile === true)
{
me.CloseDropDown();
}
});
// Suppress context menu (except for input fields)
Fit.Events.AddHandler(me.GetDomElement(), "contextmenu", function(e)
{
if (Fit.Events.GetTarget(e).tagName !== "INPUT")
return Fit.Events.PreventDefault(e);
});
// Text selection mode
me.OnFocus(function()
{
if (me.TextSelectionMode() === true)
{
if (Fit.Browser.GetBrowser() === "MSIE" || Fit.Browser.GetBrowser() === "Edge")
{
txtPrimary.readOnly = false; // ReadOnly set to true to make text-overflow:ellipsis work
setTimeout(function() { txtPrimary.blur(); txtPrimary.focus(); }, 0); // Change to ReadOnly is not applied immediately unless blurred and re-focused
}
clearTextSelectionOnInputChange = true;
//me.OpenDropDown(); // DISABLED - will also open control when gaining focus from tab navigation
}
});
me.OnChange(function()
{
if (me.TextSelectionMode() === true)
{
updateTextSelection();
}
});
me.OnBlur(function()
{
if (me.TextSelectionMode() === true)
{
updateTextSelection(); // Update when blurred in case user have entered a value
if (Fit.Browser.GetBrowser() === "MSIE" || Fit.Browser.GetBrowser() === "Edge")
{
txtPrimary.readOnly = true; // ReadOnly set to true to make text-overflow:ellipsis work
}
}
});
// Support for SearchModeOnFocus
me.OnFocus(function(sender)
{
if (searchModeOnFocus === true)
{
searchModeOnFocus = false; // Temporarily disable searchModeOnFocus to allow setInputEditing(..) (which is called by ClearInputForSearch(..)) to change editing state for txtPrimary
me._internal.ClearInputForSearch(true); // True = keep DropDown open - do not auto close it
searchModeOnFocus = true;
}
});
me.OnBlur(function()
{
if (searchModeOnFocus === true)
{
searchModeOnFocus = false; // Temporarily disable searchModeOnFocus to allow setInputEditing(..) to change editing state for txtPrimary
me._internal.UndoClearInputForSearch();
searchModeOnFocus = true;
}
});
me.OnChange(function()
{
// Determine whether value was changed by user or programmatically,
// so placeholder is not set when value is assigned programmatically.
// Control might not be focused on mobile if opened using arrow icon.
// In this case we simply use the DropDown's opened state instead.
var controlIsActive = me.Focused() === true || me.IsDropDownOpen() === true;
if (searchModeOnFocus === true && controlIsActive === true)
{
if (me.GetSelections().length === 0)
{
// DropDown has a synthetic placeholder which is displayed
// when no items are selected. Remove placeholder from input
// field so we do not get two placeholders on top of each other.
txtPrimary.placeholder = "";
}
else
{
// Display placeholder in input field when items are selected
txtPrimary.placeholder = me.Placeholder();
}
}
});
// PickerBase - make picker aware of focused state of host control
me.OnFocus(function()
{
if (picker !== null)
{
picker._internal.ReportFocused(true);
}
});
me.OnBlur(function()
{
if (picker !== null)
{
picker._internal.ReportFocused(false);
}
});
// Append elements to the DOM
Fit.Dom.Add(itemContainer, txtPrimary);
Fit.Dom.Add(itemContainer, arrow);
me._internal.AddDomElement(itemContainer);
me._internal.AddDomElement(dropDownMenu);
me.AddCssClass("FitUiControlDropDown");
}
// ============================================
// Public
// ============================================
// Error message
/// <function container="Fit.Controls.DropDown" name="InvalidSelectionMessage" access="public" returns="string">
/// <description> Get/set mouse over text shown for invalid selections </description>
/// <param name="msg" type="string" default="undefined"> If defined, error message for invalid selections are set </param>
/// </function>
this.InvalidSelectionMessage = function(msg)
{
Fit.Validation.ExpectString(msg, true);
if (Fit.Validation.IsSet(msg) === true)
{
invalidMessage = msg;
invalidMessageChanged = true; // Make sure message is not changed if locale is changed on page
updateInvalidMessageForSelectedItems();
}
return invalidMessage;
}
// Dimensions
/// <function container="Fit.Controls.DropDown" name="DropDownMaxHeight" access="public" returns="Fit.TypeDefs.CssValue">
/// <description> Get/set max height of drop down - returns object with Value (number) and Unit (string) properties </description>
/// <param name="value" type="number" default="undefined"> If defined, max height is updated to specified value. A value of -1 forces picker to fit height to content. </param>
/// <param name="unit" type="Fit.TypeDefs.CssUnit" default="undefined"> If defined, max height is updated to specified CSS unit, otherwise px is assumed </param>
/// </function>
this.DropDownMaxHeight = function(value, unit)
{
Fit.Validation.ExpectNumber(value, true);
Fit.Validation.ExpectStringValue(unit, true);
if (Fit.Validation.IsSet(value) === true)
{
maxHeight = { Value: value, Unit: ((Fit.Validation.IsSet(unit) === true) ? unit : "px")};
if (picker !== null)
picker.MaxHeight(maxHeight.Value, maxHeight.Unit);
}
return maxHeight;
}
/// <function container="Fit.Controls.DropDown" name="DropDownMaxWidth" access="public" returns="Fit.TypeDefs.CssValue">
/// <description> Get/set max width of drop down - returns object with Value (number) and Unit (string) properties </description>
/// <param name="value" type="number" default="undefined"> If defined, max width is updated to specified value. A value of -1 forces drop down to use control width. </param>
/// <param name="unit" type="Fit.TypeDefs.CssUnit" default="undefined"> If defined, max width is updated to specified CSS unit, otherwise px is assumed </param>
/// </function>
this.DropDownMaxWidth = function(value, unit)
{
Fit.Validation.ExpectNumber(value, true);
Fit.Validation.ExpectStringValue(unit, true);
if (Fit.Validation.IsSet(value) === true)
{
maxWidth = { Value: value, Unit: ((Fit.Validation.IsSet(unit) === true) ? unit : "px")};
if (value !== -1)
{
dropDownMenu.style.width = "auto"; // Adjust width to content - notice that optimizeDropDownPosition(..) and resetDropDownPosition() also manipulate the width property!
dropDownMenu.style.maxWidth = maxWidth.Value + maxWidth.Unit;
}
else
{
dropDownMenu.style.width = (me.DetectBoundaries() === true ? dropDownMenu.style.width : ""); // Preserve width value if DetectBoundaries is enabled since it also modifies this property
dropDownMenu.style.maxWidth = "";
}
}
return maxWidth;
}
// ControlBase interface
// See documentation on ControlBase
this.Value = function(val, preserveDirtyState)
{
Fit.Validation.ExpectString(val, true);
Fit.Validation.ExpectBoolean(preserveDirtyState, true);
// Set
if (Fit.Validation.IsSet(val) === true)
{
if (preserveDirtyState !== true)
{
orgSelections = [];
}
var fireChange = (itemCollectionOrdered.length > 0 || val !== ""); // Fire OnChange if current selections are cleared, and/or if new selections are set
me._internal.ExecuteWithNoOnChange(function()
{
me.Clear();
if (val !== "")
{
Fit.Array.ForEach(val.split(";"), function(item)
{
var info = item.split("=");
if (info.length === 2) // Format: title1=val1;title2=val2;title3=val3
me.AddSelection(decodeReserved(info[0]), decodeReserved(info[1]));
else // Format: val1;val2;val3
me.AddSelection(decodeReserved(info[0]), decodeReserved(info[0]));
});
}
});
if (preserveDirtyState !== true)
{
orgSelections = me.GetSelections();
}
if (fireChange === true)
fireOnChange();
}
// Get
var selections = me.GetSelections(); // Invalid selections excluded
var value = "";
Fit.Array.ForEach(selections, function(item)
{
value += ((value !== "") ? ";" : "") + encodeReserved(item.Title) + "=" + encodeReserved(item.Value);
});
return value;
}
// See documentation on ControlBase
this.IsDirty = function()
{
return (Fit.Core.IsEqual(orgSelections, me.GetSelections()) === false); // Invalid selections excluded
}
// See documentation on ControlBase
this.Clear = function()
{
me.ClearSelections();
}
// See documentation on ControlBase
this.Focused = function(val)
{
Fit.Validation.ExpectBoolean(val, true);
if (Fit.Validation.IsSet(val) === true)
{
if (val === true)
{
var c = txtPrimary;
var v = c.value;
// Set focus
c.focus();
// Make cursor move to end
c.value = "";
c.value = v;
}
else if (val === false && Fit.Dom.Contained(me.GetDomElement(), Fit.Dom.GetFocused()) === true)
{
me.CloseDropDown();
Fit.Dom.GetFocused().blur(); // Focused element could be txtActive (holds reference to currently focused input field) or arrow button
}
}
return (txtActive === Fit.Dom.GetFocused() || arrow === Fit.Dom.GetFocused());
}
// See documentation on ControlBase
this.Dispose = Fit.Core.CreateOverride(this.Dispose, function()
{
// This will destroy control - it will no longer work!
if (picker !== null)
picker.Destroy();
if (Fit._internal.DropDown.Current === me)
{
Fit._internal.DropDown.Current = null;
}
Fit.Internationalization.RemoveOnLocaleChanged(localize);
Fit.Array.ForEach(closeHandlers, function(eventId)
{
Fit.Events.RemoveHandler(document, eventId);
});
Fit.Array.ForEach(itemDropZones, function(key)
{
itemDropZones[key].Dispose();
});
me = itemContainer = itemCollection = itemDropZones = arrow = txtPrimary = txtActive = txtEnabled = dropDownMenu = picker = orgSelections = invalidMessage = invalidMessageChanged = initialFocus = maxHeight = prevValue = focusAssigned = closeHandlers = dropZone = isMobile = focusInputOnMobile = detectBoundaries = detectBoundariesRelToViewPort = persistView = highlightFirst = searchModeOnFocus = onInputChangedHandlers = onPasteHandlers = onOpenHandlers = onCloseHandlers = suppressUpdateItemSelectionState = suppressOnItemSelectionChanged = clearTextSelectionOnInputChange = prevTextSelection = textSelectionCallback = cmdToggleTextMode = null;
base();
});
// Misc. options
/// <function container="Fit.Controls.DropDown" name="Placeholder" access="public" returns="string">
/// <description> Get/set value used as a placeholder on supported browsers, to indicate expected value or action </description>
/// <param name="val" type="string" default="undefined"> If defined, value is set as placeholder </param>
/// </function>
this.Placeholder = function(val)
{
Fit.Validation.ExpectString(val, true);
if (Fit.Validation.IsSet(val) === true)
{
placeholder = val;
updatePlaceholder(true);
}
return placeholder;
}
/// <function container="Fit.Controls.DropDownTypeDefs" name="SelectionToStringCallback" returns="string">
/// <description> Callback responsible for constructing string value representing selected items </description>
/// <param name="sender" type="$TypeOfThis"> Instance of control </param>
/// </function>
/// <function container="Fit.Controls.DropDown" name="TextSelectionMode" access="public" returns="boolean">
/// <description>
/// Get/set flag indicating whether to use Text Selection Mode (true) or Visual Selection Mode (false).
/// Visual Selection Mode is the default way selected items are displayed, but it may result in control
/// changing dimensions as items are added/removed. Text Selection Mode prevents this and gives the
/// user a traditional DropDown control instead.
/// </description>
/// <param name="val" type="boolean" default="undefined"> If defined, True enables Text Selection Mode, False disables it (Visual Selection Mode) </param>
/// <param name="cb" type="Fit.Controls.DropDownTypeDefs.SelectionToStringCallback" default="undefined">
/// If defined, function will be called with DropDown being passed as an argument when selection text
/// needs to be updated. Function is expected to return a string representation of the selected items.
/// </param>
/// </function>
this.TextSelectionMode = function(val, cb)
{
Fit.Validation.ExpectBoolean(val, true);
Fit.Validation.ExpectFunction(cb, true);
if (Fit.Validation.IsSet(val) === true)
{
if (val === true && me.TextSelectionMode() === false)
{
textSelectionCallback = (cb ? cb : null);
me.ClearInput(); // Clear any value entered by the user and fire OnInputChanged
updateTextSelection();
if (me.Focused() === false && (Fit.Browser.GetBrowser() === "MSIE" || Fit.Browser.GetBrowser() === "Edge"))
{
txtPrimary.readOnly = true; // Necessary to make text-overflow:ellipsis work in IE and Edge - disabled in OnFocus handler
}
}
else if (val === false && me.TextSelectionMode() === true)
{
if (txtPrimary.value === prevTextSelection)
{
txtPrimary.value = "";
}
else
{
// User has changed value - clear and fire OnInputChanged.
// This only happens if Text Selection Mode is being disabled
// while control has focus and user have entered a value,
// since selection text is always updated when control lose focus.
me.ClearInput();
}
clearTextSelectionOnInputChange = false;
prevTextSelection = null;
textSelectionCallback = null;
if (Fit.Browser.GetBrowser() === "MSIE" || Fit.Browser.GetBrowser() === "Edge")
{
txtPrimary.readOnly = false;
}
}
me._internal.Data("selectionmode", (val === true ? "text" : "visual"));
if (cmdToggleTextMode !== null)
{
if (val === true)
{
Fit.Dom.RemoveClass(cmdToggleTextMode, "fa-compress");
Fit.Dom.AddClass(cmdToggleTextMode, "fa-expand");
}
else
{
{
Fit.Dom.RemoveClass(cmdToggleTextMode, "fa-expand");
Fit.Dom.AddClass(cmdToggleTextMode, "fa-compress");
}
}
}
me._internal.Repaint();
}
return (me._internal.Data("selectionmode") === "text");
}
/// <function container="Fit.Controls.DropDown" name="SelectionModeToggle" access="public" returns="boolean">
/// <description> Get/set value indicating whether control allow user to toggle Selection Mode (Visual or Text) </description>
/// <param name="val" type="boolean" default="undefined"> If defined, True enables toggle button, False disables it </param>
/// </function>
this.SelectionModeToggle = function(val)
{
Fit.Validation.ExpectBoolean(val, true);
if (Fit.Validation.IsSet(val) === true)
{
if (val === true && cmdToggleTextMode === null)
{
cmdToggleTextMode = document.createElement("span");
cmdToggleTextMode.onclick = function()
{
me.TextSelectionMode(!me.TextSelectionMode());
}
Fit.Dom.AddClass(cmdToggleTextMode, "fa");
Fit.Dom.AddClass(cmdToggleTextMode, me.TextSelectionMode() === true ? "fa-expand" : "fa-compress");
me._internal.AddDomElement(cmdToggleTextMode);
me._internal.Data("selectionmodetoggle", "true");
}
else if (val === false && cmdToggleTextMode !== null)
{
me._internal.RemoveDomElement(cmdToggleTextMode);
cmdToggleTextMode = null;
me._internal.Data("selectionmodetoggle", "false");
}
}
return (cmdToggleTextMode !== null);
}
/// <function container="Fit.Controls.DropDown" name="MultiSelectionMode" access="public" returns="boolean">
/// <description> Get/set flag indicating whether control allows for multiple selections </description>
/// <param name="val" type="boolean" default="undefined"> If defined, True enables multi selection mode, False disables it </param>
/// </function>
this.MultiSelectionMode = function(val)
{
Fit.Validation.ExpectBoolean(val, true);
if (Fit.Validation.IsSet(val) === true && me.MultiSelectionMode() !== val)
{
me.ClearSelections();
me._internal.Data("multiselect", val.toString());
}
return (me._internal.Data("multiselect") === "true");
}
// Controlling selections
/// <function container="Fit.Controls.DropDown" name="GetPicker" access="public" returns="Fit.Controls.PickerBase">
/// <description> Get picker control used to add items to drop down control </description>
/// </function>
this.GetPicker = function()
{
return picker;
}
/// <function container="Fit.Controls.DropDown" name="SetPicker" access="public">
/// <description> Set picker control used to add items to drop down control </description>
/// <param name="pickerControl" type="Fit.Controls.PickerBase | null"> Picker control extending from PickerBase </param>
/// </function>
this.SetPicker = function(pickerControl)
{
Fit.Validation.ExpectInstance(pickerControl, Fit.Controls.PickerBase, true);
if (pickerControl === picker)
return; // Already active picker
// Remove existing picker
if (picker !== null)
Fit.Dom.Remove(picker.GetDomElement());
// Add picker
if (!pickerControl)
{
picker = null;
return;
}
pickerControl._internal.InitializePicker();
pickerControl._internal.ReportFocused(me.Focused());
picker = pickerControl;
Fit.Dom.Add(dropDownMenu, picker.GetDomElement());
// Allow picker to select items in case selections have already been set in drop down
suppressOnItemSelectionChanged = true;
picker.SetSelections(me.GetSelections());
suppressOnItemSelectionChanged = false;
// Set picker MaxHeight
picker.MaxHeight(maxHeight.Value, maxHeight.Unit);
optimizeDropDownPosition(); // In case dropdown is already open and SetPicker was called async, e.g. initiated from OnOpen event. Function may change MaxHeight on Picker.
// Persist view and initial focus
picker.PersistView(persistView);
picker.HighlightFirst(highlightFirst);
// Make sure OnItemSelectionChanged is only registered once
if (!picker._internal)
picker._internal = {};
if (picker._internal.HostControl)
return;
picker._internal.HostControl = me;
// Register OnItemSelectionChanged handler which is used to
// synchronize selections from picker control to drop down.
var fireChangeEvent = false;
picker.OnItemSelectionChanged(function(sender, eventArgs)
{
if (suppressOnItemSelectionChanged === true)
return; // Skip - already processing OnItemSelectionChanged - may be invoked multiple times if e.g. switching selection in Single Selection Mode (existing item removed + new item selected)
var txt = null;
// Prevent this.AddSelection and this.RemoveSelection from calling
// picker.UpdateItemSelection which in turn fires OnItemSelectionChanged, causing an infinite loop.
suppressUpdateItemSelectionState = true;
if (eventArgs.Selected === true && me.GetSelectionByValue(eventArgs.Value) === null) // Check whether node is already selected (PreSelection)
{
fireChangeEvent = true;
// Changing a selection in the picker control may cause OnItemSelectionChanged to be fired multiple
// times since an existing selection may first be deselected, followed by new item being selected.
// In this case we suppress OnChange fired by RemoveSelection(..) and AddSelection(..), and instead
// fire it when picker's OnItemSelectionComplete event is fired.
me._internal.ExecuteWithNoOnChange(function() { me.AddSelection(eventArgs.Title, eventArgs.Value); });
if (me.MultiSelectionMode() === false)
me.CloseDropDown();
}
else if (eventArgs.Selected === false && me.GetSelectionByValue(eventArgs.Value) !== null)
{
fireChangeEvent = true;
txt = txtActive; // RemoveSelection changes txtActive
// Changing a selection in the picker control may cause OnItemSelectionChanged to be fired multiple
// times since an existing selection may first be deselected, followed by new item being selected.
// In this case we suppress OnChange fired by RemoveSelection(..) and AddSelection(..), and instead
// fire it when picker's OnItemSelectionComplete event is fired.
me._internal.ExecuteWithNoOnChange(function() { me.RemoveSelection(eventArgs.Value) });
// Fix - if item removed was the last item, and txtActive
// was one of the input fields belonging to that selection,
// it will now have been removed.
if (txt.parentElement.parentElement === null)
txt = txtPrimary;
}
else
{
// User selected an item which is already selected
// Only update input field if picker currently active is the one providing information about selection change.
// Pickers might load and select nodes async. which allows for picker to be changed. More specifically we could
// imagine a situation where Select All is triggered in a WSTreeView picker where nodes must first be fetched from
// the server. While waiting for data, the user enters a search string which changes the picker control to WSListView.
// Soon hereafter TreeView data is received and all nodes are selected, triggering OnItemSelectionChanged (here), in
// which case we do not want the search value to be cleared away.
if (picker === sender)
{
if (me.TextSelectionMode() === true)
{
updateTextSelection(); // Make sure any search value is removed and text selection is restored
}
else
{
me.ClearInput(); // Make sure any search value is removed
}
}
}
// DISABLED: Now handled using picker.OnFocus(..) handler further down - see https://github.com/Jemt/Fit.UI/issues/86 for details
// if (eventArgs.ProgrammaticallyChanged === false && (isMobile === false || focusInputOnMobile === true))
// {
// focusAssigned = true; // Clicking the picker causes blur to fire for input fields in drop down which changes focusAssigned to false - it must be true for focusInput(..) to assign focus
// focusInput(((txt !== null) ? txt : txtActive));
// }
suppressUpdateItemSelectionState = false;
});
picker.OnItemSelectionComplete(function(sender)
{
if (suppressOnItemSelectionChanged === true)
return;
// Picker may notify about selections that has already been
// made due to PreSelections (nodes are selected when loaded).
// Only fire OnChange if control value has actually changed.
if (fireChangeEvent === true)
{
me._internal.FireOnChange();
fireChangeEvent = false;
}
});
picker.OnFocusIn(function(sender)
{
// Steal back focus - DropDown should remain the focused control
focusAssigned = true; // Clicking the picker causes blur to fire for input fields in drop down which changes focusAssigned to false - it must be true for focusInput(..) to assign focus
focusInput(txtActive);
});
}
/// <function container="Fit.Controls.DropDown" name="AddSelection" access="public">
/// <description> Add selection to control </description>
/// <param name="title" type="string"> Item title </param>
/// <param name="value" type="string"> Item value </param>
/// <param name="valid" type="boolean" default="true">
/// Flag indicating whether selection is valid or not. Invalid selections are highlighted and
/// not included when selections are retrived using Value() function, and not considered when
/// IsDirty() is called to determine whether control value has been changed by user.
/// GetSelections(true) can be used to retrive all items, including invalid selections.
/// </param>
/// </function>
this.AddSelection = function(title, value, valid)
{
Fit.Validation.ExpectString(title);
Fit.Validation.ExpectString(value);
Fit.Validation.ExpectBoolean(valid, true);
if (me.GetSelectionByValue(value) !== null)
return;
// Update picker control
// Notice: suppressUpdateItemSelectionState is True if item was added by picker,
// in which case picker.UpdateItemSelection(..) should not be called.
// What happens is that picker fires drop down's OnItemSelectionChanged when an item is
// selected, which sets suppressUpdateItemSelectionState to True, and calls AddSelection.
// Failing to prevent picker.UpdateItemSelection(..) from being called in this case could
// result in an infinite loop.
if (picker !== null && suppressUpdateItemSelectionState === false)
{
// Notice: Picker fires OnItemSelectionChanged when picker.UpdateItemSelection(..) is invoked
// below (other controls than DropDown may have registered an OnItemSelectionChanged
// handler too). In this case we set suppressOnItemSelectionChanged to True, causing
// drop down to do nothing in OnItemSelectionChanged handler when fired. Drop down's OnItemSelectionChanged
// handler is responsible for handling items added/removed by picker, but in this case the change did not
// come from the picker (since suppressUpdateItemSelectionState is False).
// Failing to set this flag could result in an infinite loop.
suppressOnItemSelectionChanged = true;
var res = true;
var error = null;
try // Make sure we can set suppressOnItemSelectionChanged false again, so drop down remains in a functioning state
{
res = picker.UpdateItemSelection(value, true, me.Focused() === false);
}
catch (err) { error = err; }
suppressOnItemSelectionChanged = false;
if (error !== null)
Fit.Validation.ThrowError(error);
if (res === false)
return; // Picker prevented selection from being added
}
// Clear selection if in Single Selection Mode
if (me.MultiSelectionMode() === false)
{
var error = null;
// ClearSelections() results in picker.UpdateItemSelection(..) being called if an item is currently selected,
// eventually resulting in picker firing OnItemSelectionChanged and OnItemSelectionComplete. However, operation has
// not completed yet, since new element has not yet been selected (done below). Skip events.
suppressOnItemSelectionChanged = true;
try // Make sure we can set suppressOnItemSelectionChanged false again, so drop down remains in a functioning state
{
me._internal.ExecuteWithNoOnChange(function() { me.ClearSelections(); });
}
catch (err) { error = err; }
suppressOnItemSelectionChanged = false;
if (error !== null)
Fit.Validation.ThrowError(error);
if (itemCollectionOrdered.length > 0) // A picker prevented selected item from being removed
return;
}
// Create new item
// Delete button
var cmdDelete = document.createElement("i");
Fit.Dom.AddClass(cmdDelete, "fa");
Fit.Dom.AddClass(cmdDelete, "fa-times");
cmdDelete.tabIndex = -1; // Prevents control from losing focus when clicking button - will not interfear with tab flow as -1 makes it focusable, but not part of tab flow
cmdDelete.onclick = function(e) // OnClick fires after MouseUp
{
// Whether OnClick fires depends on what browser is being used. A couple of tests reveal this:
// Chrome and IE: Does not fire onclick if an element is moved to another position in DOM (dragged and dropped).
// Firefox: Does not fire onclick if element is moved, unless it is dropped in a new position in DOM (drag and drop)
// - opposite of Chrome and IE. Firefox does ignore minor movements though, for the sake of usability.
me.RemoveSelection(decode(Fit.Dom.Data(cmdDelete.parentElement, "value")));
// Always focus control when removing and moving items.
// First of all it prevents OnFocus and OnBlur from firing
// a lot of times if multiple elements are removed or moved,
// secondly it's easier to ensure consistency across browsers