-
Notifications
You must be signed in to change notification settings - Fork 1
/
ng-material-dropmenu.js
executable file
·1256 lines (1124 loc) · 44.3 KB
/
ng-material-dropmenu.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
/*!
* Dropmenu for Angular Material Design
* https://github.com/Soopro/ng-material-dropmenu
* @license MIT
*/
(function () {
"use strict";
var SELECT_EDGE_MARGIN = 8;
var selectNextId = 0;
var PALETTES = {};
var THEMES = {};
var GENERATED = {};
var parseRules = null;
var THEME_COLOR_TYPES = ['primary', 'accent', 'warn', 'background'];
var DEFAULT_COLOR_TYPE = 'primary';
var DARK_CONTRAST_COLOR = colorToRgbaArray('rgba(0,0,0,0.87)');
var LIGHT_CONTRAST_COLOR = colorToRgbaArray('rgba(255,255,255,0.87');
var STRONG_LIGHT_CONTRAST_COLOR = colorToRgbaArray('rgb(255,255,255)');
function colorToRgbaArray(clr) {
if (angular.isArray(clr) && clr.length == 3) return clr;
if (/^rgb/.test(clr)) {
return clr.replace(/(^\s*rgba?\(|\)\s*$)/g, '').split(',').map(function(value, i) {
return i == 3 ? parseFloat(value, 10) : parseInt(value, 10);
});
}
if (clr.charAt(0) == '#') clr = clr.substring(1);
if (!/^([a-fA-F0-9]{3}){1,2}$/g.test(clr)) return;
var dig = clr.length / 3;
var red = clr.substr(0, dig);
var grn = clr.substr(dig, dig);
var blu = clr.substr(dig * 2);
if (dig === 1) {
red += red;
grn += grn;
blu += blu;
}
return [parseInt(red, 16), parseInt(grn, 16), parseInt(blu, 16)];
}
/**
* @ngdoc module
* @name ngMaterialDropmenu
* @description
*
* # ngMaterialDropmenu
*
*/
angular.module('ngMaterialDropmenu', [
'material.core',
'material.components.backdrop'
// 'ngMaterial'
])
.directive('mdDropmenu', DropmenuDirective)
.directive('mdDropMenu', DropMenuDirective)
.directive('mdDropOption', DropOptionDirective)
.directive('mdDropOptgroup', OptgroupDirective)
.provider('$mdDropmenu', DropProvider)
.config(colorPalettes)
.run(generateDropmenuThemes)
.constant("$MD_DROPMENU_THEME_CSS", "md-drop-menu.md-THEME_NAME-theme md-drop-optgroup { color: '{{foreground-2}}'; } md-drop-menu.md-THEME_NAME-theme md-drop-optgroup md-drop-option { color: '{{foreground-1}}'; } md-drop-menu.md-THEME_NAME-theme md-drop-option[selected] { color: '{{primary-500}}'; } md-drop-menu.md-THEME_NAME-theme md-drop-option[selected]:focus { color: '{{primary-600}}'; } md-drop-menu.md-THEME_NAME-theme md-drop-option[selected].md-accent { color: '{{accent-500}}'; } md-drop-menu.md-THEME_NAME-theme md-drop-option[selected].md-accent:focus { color: '{{accent-600}}'; } md-drop-menu.md-THEME_NAME-theme md-drop-option:focus:not([selected]) { background: '{{background-200}}'; }");
// Theme
function colorPalettes($mdThemingProvider) {
PALETTES = $mdThemingProvider._PALETTES;
THEMES = $mdThemingProvider._THEMES;
parseRules = $mdThemingProvider._parseRules;
}
colorPalettes.$inject = ['$mdThemingProvider'];
// Generate our themes at run time given the state of THEMES and PALETTES
function generateDropmenuThemes($injector) {
// Insert our newly minted styles into the DOM
var head = document.getElementsByTagName('head')[0];
if (!head) return;
var firstChild = head.firstElementChild;
if (!firstChild) return;
var themeCss = $injector.has('$MD_DROPMENU_THEME_CSS') ? $injector.get('$MD_DROPMENU_THEME_CSS') : '';
// Expose contrast colors for palettes to ensure that text is always readable
angular.forEach(PALETTES, sanitizePalette);
// MD_THEME_CSS is a string generated by the build process that includes all the themable
// components as templates
// Break the CSS into individual rules
var rulesByType = {};
var rules = themeCss
.split(/\}(?!(\}|'|"|;))/)
.filter(function(rule) { return rule && rule.length; })
.map(function(rule) { return rule.trim() + '}'; });
var ruleMatchRegex = new RegExp('md-(' + THEME_COLOR_TYPES.join('|') + ')', 'g');
THEME_COLOR_TYPES.forEach(function(type) {
rulesByType[type] = '';
});
// Sort the rules based on type, allowing us to do color substitution on a per-type basis
rules.forEach(function(rule) {
var match = rule.match(ruleMatchRegex);
// First: test that if the rule has '.md-accent', it goes into the accent set of rules
for (var i = 0, type; type = THEME_COLOR_TYPES[i]; i++) {
if (rule.indexOf('.md-' + type) > -1) {
return rulesByType[type] += rule;
}
}
// If no eg 'md-accent' class is found, try to just find 'accent' in the rule and guess from
// there
for (i = 0; type = THEME_COLOR_TYPES[i]; i++) {
if (rule.indexOf(type) > -1) {
return rulesByType[type] += rule;
}
}
// Default to the primary array
return rulesByType[DEFAULT_COLOR_TYPE] += rule;
});
// For each theme, use the color palettes specified for
// `primary`, `warn` and `accent` to generate CSS rules.
angular.forEach(THEMES, function(theme) {
if ( !GENERATED[theme.name] ) {
THEME_COLOR_TYPES.forEach(function(colorType) {
var styleStrings = parseRules(theme, colorType, rulesByType[colorType]);
while (styleStrings.length) {
var style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.appendChild(document.createTextNode(styleStrings.shift()));
head.insertBefore(style, firstChild);
}
});
if (theme.colors.primary.name == theme.colors.accent.name) {
console.warn("$mdThemingProvider: Using the same palette for primary and" +
" accent. This violates the material design spec.");
}
GENERATED[theme.name] = true;
}
});
// *************************
// Internal functions
// *************************
// The user specifies a 'default' contrast color as either light or dark,
// then explicitly lists which hues are the opposite contrast (eg. A100 has dark, A200 has light)
function sanitizePalette(palette) {
var defaultContrast = palette.contrastDefaultColor;
var lightColors = palette.contrastLightColors || [];
var strongLightColors = palette.contrastStrongLightColors || [];
var darkColors = palette.contrastDarkColors || [];
// These colors are provided as space-separated lists
if (typeof lightColors === 'string') lightColors = lightColors.split(' ');
if (typeof strongLightColors === 'string') strongLightColors = strongLightColors.split(' ');
if (typeof darkColors === 'string') darkColors = darkColors.split(' ');
// Cleanup after ourselves
delete palette.contrastDefaultColor;
delete palette.contrastLightColors;
delete palette.contrastStrongLightColors;
delete palette.contrastDarkColors;
// Change { 'A100': '#fffeee' } to { 'A100': { value: '#fffeee', contrast:DARK_CONTRAST_COLOR }
angular.forEach(palette, function(hueValue, hueName) {
if (angular.isObject(hueValue)) return; // Already converted
// Map everything to rgb colors
var rgbValue = colorToRgbaArray(hueValue);
if (!rgbValue) {
throw new Error("Color %1, in palette %2's hue %3, is invalid. Hex or rgb(a) color expected."
.replace('%1', hueValue)
.replace('%2', palette.name)
.replace('%3', hueName));
}
palette[hueName] = {
value: rgbValue,
contrast: getContrastColor()
};
function getContrastColor() {
if (defaultContrast === 'light') {
if (darkColors.indexOf(hueName) > -1) {
return DARK_CONTRAST_COLOR;
} else {
return strongLightColors.indexOf(hueName) > -1 ? STRONG_LIGHT_CONTRAST_COLOR
: LIGHT_CONTRAST_COLOR;
}
} else {
if (lightColors.indexOf(hueName) > -1) {
return strongLightColors.indexOf(hueName) > -1 ? STRONG_LIGHT_CONTRAST_COLOR
: LIGHT_CONTRAST_COLOR;
} else {
return DARK_CONTRAST_COLOR;
}
}
}
});
}
}
generateDropmenuThemes.$inject = ["$injector"];
// Module
function DropmenuDirective($mdDropmenu, $mdUtil, $mdTheming, $mdAria, $interpolate, $compile, $parse) {
return {
restrict: 'E',
require: ['mdDropmenu'],
compile: compile,
controller: function() { } // empty placeholder controller to be initialized in link
};
function compile(element, attr) {
// The user is allowed to provide a label for the dropmenu as md-drop-label child
var labelEl = element.find('md-drop-label').remove();
// If not provided, we automatically make one
if (!labelEl.length) {
labelEl = angular.element(
'<md-drop-label><span></span></md-drop-label>'
);
} else {
if (!labelEl[0].firstElementChild) {
var spanWrapper = angular.element('<span>');
spanWrapper.append(labelEl.contents());
labelEl.append(spanWrapper);
}
}
labelEl.addClass('md-drop-label');
labelEl.attr('id', 'drop_label_' + $mdUtil.nextUid());
// There's got to be an md-content inside. If there's not one, let's add it.
if (!element.find('md-content').length) {
element.append(
angular.element('<md-content>').append(element.contents())
);
}
// // Add progress spinner for md-drop-options-loading
// if (attr.mdOnOpen) {
// element.find('md-content').prepend(
// angular.element('<md-progress-circular>')
// .attr('md-mode', 'indeterminate')
// .attr('ng-hide', '$$loadingAsyncDone')
// .wrap('<div>')
// .parent()
// );
// }
//
// if (attr.name) {
// var autofillClone = angular.element(
// '<select class="md-visually-hidden">'
// );
// autofillClone.attr({
// 'name': '.' + attr.name,
// // 'ng-model': attr.ngModel,
// 'aria-hidden': 'true',
// 'tabindex': '-1'
// });
// var opts = element.find('md-option');
// angular.forEach(opts, function(el) {
// var newEl = angular.element('<option>' + el.innerHTML + '</option>');
// if (el.hasAttribute('ng-value')){
// newEl.attr('ng-value', el.getAttribute('ng-value'));
// } else if (el.hasAttribute('value')) {
// newEl.attr('value', el.getAttribute('value'));
// }
// autofillClone.append(newEl);
// });
//
// element.parent().append(autofillClone);
// }
// Use everything that's left inside element.contents() as the contents of the menu
var selectTemplate = '<div class="md-drop-menu-container">' +
'<md-drop-menu ' +
(angular.isDefined(attr.multiple) ? 'multiple' : '') + '>' +
element.html() +
'</md-drop-menu></div>';
element.empty().append(labelEl);
attr.tabindex = attr.tabindex || '-1';
return function postLink(scope, element, attr, ctrls) {
var isOpen;
var isDisabled;
var mdDropmenuCtrl = ctrls[0];
// var ngModel = ctrls[1];
// var formCtrl = ctrls[2];
// var labelEl = element.find('md-drop-label');
// var customLabel = labelEl.text().length !== 0;
// var selectContainer, selectScope, selectMenuCtrl;
var selectContainer, selectScope;
createDropmenu();
$mdTheming(element);
// if (attr.name && formCtrl) {
// var selectEl = element.parent()[0].querySelector('select[name=".' + attr.name + '"]')
// formCtrl.$removeControl(angular.element(selectEl).controller());
// }
// var originalRender = ngModel.$render;
// ngModel.$render = function() {
// originalRender();
// // syncLabelText();
// };
//
// mdDropmenuCtrl.setLabelText = function(text) {
// if (customLabel) return; // Assume that user is handling it on their own
// mdDropmenuCtrl.setIsPlaceholder(!text);
// text = text || attr.placeholder || '';
// var target = customLabel ? labelEl : labelEl.children().eq(0);
// target.text(text);
// };
//
// mdDropmenuCtrl.setIsPlaceholder = function(val) {
// val ? labelEl.addClass('md-placeholder') : labelEl.removeClass('md-placeholder');
// };
// scope.$$postDigest(function() {
// setAriaLabel();
// // syncLabelText();
// });
//
// function setAriaLabel() {
// var labelText = element.attr('placeholder');
// if (!labelText) {
// labelText = element.find('md-drop-label').text();
// }
// $mdAria.expect(element, 'aria-label', labelText);
// }
// function syncLabelText() {
// if (selectContainer) {
// selectMenuCtrl = selectMenuCtrl || selectContainer
// .find('md-drop-menu')
// .controller('mdDropMenu');
//
// selectMenuCtrl.selectedLabels();
// // mdDropmenuCtrl.setLabelText(selectMenuCtrl.selectedLabels());
// }
// }
// var deregisterWatcher;
// attr.$observe('ngMultiple', function(val) {
// if (deregisterWatcher) deregisterWatcher();
// var parser = $parse(val);
// deregisterWatcher = scope.$watch(function() {
// return parser(scope);
// }, function(multiple, prevVal) {
// if (multiple === undefined && prevVal === undefined) return; // assume compiler did a good job
// if (multiple) {
// element.attr('multiple', 'multiple');
// } else {
// element.removeAttr('multiple');
// }
// if (selectContainer) {
// selectMenuCtrl.setMultiple(multiple);
// // originalRender = ngModel.$render;
// // ngModel.$render = function() {
// // originalRender();
// // // syncLabelText();
// // };
// // selectMenuCtrl.refreshViewValue();
// // ngModel.$render();
// }
// });
// });
attr.$observe('disabled', function(disabled) {
if (typeof disabled == "string") {
disabled = true;
}
// Prevent click event being registered twice
if (isDisabled !== undefined && isDisabled === disabled) {
return;
}
isDisabled = disabled;
if (disabled) {
element.attr({'tabindex': -1, 'aria-disabled': 'true'});
element.off('click', openSelect);
element.off('keydown', handleKeypress);
} else {
element.attr({'tabindex': attr.tabindex, 'aria-disabled':'false'});
element.on('click', openSelect);
element.on('keydown', handleKeypress);
}
});
if (!attr.disabled && !attr.ngDisabled) {
element.attr({'tabindex': attr.tabindex, 'aria-disabled':'false'});
element.on('click', openSelect);
element.on('keydown', handleKeypress);
}
element.attr({
'role': 'combobox',
'id': 'dropmenu_' + $mdUtil.nextUid(),
'aria-expanded': 'false'
});
scope.$on('$destroy', function() {
if (isOpen) {
$mdDropmenu.cancel().then(function() {
selectContainer.remove();
});
} else {
selectContainer.remove();
}
});
// Create a fake select to find out the label value
function createDropmenu() {
selectContainer = angular.element(selectTemplate);
// var selectEl = selectContainer.find('md-drop-menu');
// selectEl.data('$ngModelController', ngModel);
// selectEl.data('$mdDropmenuController', mdDropmenuCtrl);
selectScope = scope.$new();
selectContainer = $compile(selectContainer)(selectScope);
// selectMenuCtrl = selectContainer.find('md-drop-menu')
// .controller('mdDropMenu');
}
function handleKeypress(e) {
var allowedCodes = [32, 13, 38, 40];
if (allowedCodes.indexOf(e.keyCode) != -1 ) {
// prevent page scrolling on interaction
e.preventDefault();
openSelect(e);
}
// } else {
// if (e.keyCode <= 90 && e.keyCode >= 31) {
// e.preventDefault();
// var node = selectMenuCtrl.optNodeForKeyboardSearch(e);
// if (!node) return;
// var optionCtrl = angular.element(node).controller('mdDropOption');
// // if (!selectMenuCtrl.isMultiple) {
// // selectMenuCtrl.deselect( Object.keys(selectMenuCtrl.selected)[0] );
// // }
// // selectMenuCtrl.select(optionCtrl.hashKey, optionCtrl.value);
// // selectMenuCtrl.refreshViewValue();
// // ngModel.$render();
// }
// }
}
function openSelect(e) {
scope.$evalAsync(function() {
var loading, autoFocus;
isOpen = true;
loading = attr.mdOnOpen ? scope.$eval(attr.mdOnOpen) || true : false
autoFocus = angular.isDefined(attr.disabledAutoFocus) ? false : true
$mdDropmenu.show({
scope: selectScope,
preserveScope: true,
skipCompile: true,
element: selectContainer,
target: element[0],
hasBackdrop: true,
loadingAsync: loading,
autoFocus: autoFocus,
}).then(function(selectedText) {
isOpen = false;
});
});
// prevnet page scroll to top while use a href="#"
e.preventDefault();
}
};
}
}
DropmenuDirective.$inject = ["$mdDropmenu", "$mdUtil", "$mdTheming", "$mdAria",
"$interpolate", "$compile", "$parse"];
function DropMenuDirective($parse, $mdUtil, $mdTheming) {
// DropMenuController.$inject = ["$scope", "$attrs", "$element"];
return {
restrict: 'E',
// require: ['mdDropMenu'],
// controller: DropMenuController,
link: { pre: preLink }
};
// We use preLink instead of postLink to ensure that the select is initialized before
// its child options run postLink.
function preLink(scope, element, attr, ctrls) {
// var selectCtrl = ctrls[0];
// var ngModel = ctrls[1];
$mdTheming(element);
// element.on('click', clickListener);
// element.on('keypress', keyListener);
// if (ngModel) selectCtrl.init(ngModel);
// selectCtrl.init();
configureAria();
function configureAria() {
element.attr({
'id': 'drop_menu_' + $mdUtil.nextUid(),
'role': 'listbox'
});
}
//
// function keyListener(e) {
// if (e.keyCode == 13 || e.keyCode == 32) {
// clickListener(e);
// }
// }
//
// function clickListener(ev) {
// var option = $mdUtil.getClosest(ev.target, 'md-option');
// var optionCtrl = option && angular.element(option)
// .data('$mdDropOptionController');
// if (!option || !optionCtrl) return;
//
// var optionHashKey = selectCtrl.hashGetter(optionCtrl.value);
// var isSelected = angular.isDefined(selectCtrl.selected[optionHashKey]);
// scope.$apply(function() {
// // if (selectCtrl.isMultiple) {
// // if (isSelected) {
// // selectCtrl.deselect(optionHashKey);
// // } else {
// // selectCtrl.select(optionHashKey, optionCtrl.value);
// // }
// // } else {
// // if (!isSelected) {
// // selectCtrl.deselect( Object.keys(selectCtrl.selected)[0] );
// // selectCtrl.select( optionHashKey, optionCtrl.value );
// // }
// // }
// if (!isSelected) {
// selectCtrl.deselect( Object.keys(selectCtrl.selected)[0] );
// selectCtrl.select( optionHashKey, optionCtrl.value );
// }
// // selectCtrl.refreshViewValue();
// });
// }
}
function DropMenuController($scope, $attrs, $element) {
// var self = this;
// self.isMultiple = angular.isDefined($attrs.multiple);
// // selected is an object with keys matching all of the selected options' hashed values
// self.selected = {};
// // options is an object with keys matching every option's hash value,
// // and values matching every option's controller.
// self.options = {};
//
// $scope.$watch(function() { return self.options; }, function() {
// self.ngModel.$render();
// }, true);
// var deregisterCollectionWatch;
// self.setMultiple = function(isMultiple) {
// // var ngModel = self.ngModel;
// self.isMultiple = isMultiple;
// // if (deregisterCollectionWatch) deregisterCollectionWatch();
// //
// // if (self.isMultiple) {
// // // ngModel.$validators['md-multiple'] = validateArray;
// // // ngModel.$render = renderMultiple;
// //
// // // watchCollection on the model because by default ngModel only watches the model's
// // // reference. This allowed the developer to also push and pop from their array.
// // // $scope.$watchCollection($attrs.ngModel, function(value) {
// // // if (validateArray(value)) renderMultiple(value);
// // // });
// // } else {
// // // delete ngModel.$validators['md-multiple'];
// // // ngModel.$render = renderSingular;
// // }
//
// // function validateArray(modelValue, viewValue) {
// // // If a value is truthy but not an array, reject it.
// // // If value is undefined/falsy, accept that it's an empty array.
// // return angular.isArray(modelValue || viewValue || []);
// // }
// };
// var searchStr = '';
// var clearSearchTimeout, optNodes, optText;
// var CLEAR_SEARCH_AFTER = 300;
// self.optNodeForKeyboardSearch = function(e) {
// clearSearchTimeout && clearTimeout(clearSearchTimeout);
// clearSearchTimeout = setTimeout(function() {
// clearSearchTimeout = undefined;
// searchStr = '';
// optText = undefined;
// optNodes = undefined;
// }, CLEAR_SEARCH_AFTER);
// searchStr += String.fromCharCode(e.keyCode);
// var search = new RegExp('^' + searchStr, 'i');
// if (!optNodes) {
// optNodes = $element.find('md-option');
// optText = new Array(optNodes.length);
// angular.forEach(optNodes, function(el, i) {
// optText[i] = el.textContent.trim();
// });
// }
// for (var i = 0; i < optText.length; ++i) {
// if (search.test(optText[i])) {
// return optNodes[i];
// }
// }
// };
//
// self.init = function(ngModel) {
// // self.ngModel = ngModel;
//
// // Allow users to provide `ng-model="foo" ng-model-options="{trackBy: 'foo.id'}"` so
// // that we can properly compare objects set on the model to the available options
// // if (ngModel.$options && ngModel.$options.trackBy) {
// // var trackByLocals = {};
// // var trackByParsed = $parse(ngModel.$options.trackBy);
// // self.hashGetter = function(value, valueScope) {
// // trackByLocals.$value = value;
// // return trackByParsed(valueScope || $scope, trackByLocals);
// // };
// // // If the user doesn't provide a trackBy, we automatically generate an id for every
// // // value passed in
// // } else {
// // self.hashGetter = function getHashValue(value) {
// // if (angular.isObject(value)) {
// // return '$$object_' + (value.$$mdDropmenuId || (value.$$mdDropmenuId = ++selectNextId));
// // }
// // return value;
// // };
// // }
// self.setMultiple(self.isMultiple);
// };
// self.init = function() {
// self.hashGetter = function getHashValue(value) {
// if (angular.isObject(value)) {
// if(!value.$$mdDropmenuId){
// (value.$$mdDropmenuId = ++selectNextId)
// }
// var _obj = value.$$mdDropmenuId;
// return '$$object_' + _obj
// }
// return value;
// };
// };
// self.selectedLabels = function() {
// var selectedOptionEls = nodesToArray(
// $element[0].querySelectorAll('md-drop-option[selected]')
// );
// if (selectedOptionEls.length) {
// return selectedOptionEls.map(
// function(el) { return el.textContent; }
// ).join(', ');
// } else {
// return '';
// }
// };
//
// self.select = function(hashKey, hashedValue) {
// var option = self.options[hashKey];
// option && option.setSelected(true);
// self.selected[hashKey] = hashedValue;
// };
// self.deselect = function(hashKey) {
// var option = self.options[hashKey];
// option && option.setSelected(false);
// delete self.selected[hashKey];
// };
//
// self.addOption = function(hashKey, optionCtrl) {
// if (angular.isDefined(self.options[hashKey])) {
// throw new Error('Duplicate md-option values are not '+
// 'allowed in a select. ' +
// 'Duplicate value "' + optionCtrl.value + '" found.');
// }
// self.options[hashKey] = optionCtrl;
//
// // If this option's value was already in our ngModel, go ahead and select it.
// if (angular.isDefined(self.selected[hashKey])) {
// self.select(hashKey, optionCtrl.value);
// // self.refreshViewValue();
// }
// };
// self.removeOption = function(hashKey) {
// delete self.options[hashKey];
// // Don't deselect an option when it's removed - the user's ngModel should be allowed
// // to have values that do not match a currently available option.
// };
//
// self.refreshViewValue = function() {
// // var values = [];
// // var option;
// // for (var hashKey in self.selected) {
// // // If this hashKey has an associated option, push that option's value to the model.
// // if ((option = self.options[hashKey])) {
// // values.push(option.value);
// // } else {
// // // Otherwise, the given hashKey has no associated option, and we got it
// // // from an ngModel value at an earlier time. Push the unhashed value of
// // // this hashKey to the model.
// // // This allows the developer to put a value in the model that doesn't yet have
// // // an associated option.
// // values.push(self.selected[hashKey]);
// // }
// // }
// // self.ngModel.$setViewValue(self.isMultiple ? values : values[0]);
// };
// function renderMultiple() {
// var newSelectedValues = self.ngModel.$modelValue || self.ngModel.$viewValue;
// if (!angular.isArray(newSelectedValues)) return;
//
// var oldSelected = Object.keys(self.selected);
//
// var newSelectedHashes = newSelectedValues.map(self.hashGetter);
// var deselected = oldSelected.filter(function(hash) {
// return newSelectedHashes.indexOf(hash) === -1;
// });
//
// deselected.forEach(self.deselect);
// newSelectedHashes.forEach(function(hashKey, i) {
// self.select(hashKey, newSelectedValues[i]);
// });
// }
// function renderSingular() {
// var value = self.ngModel.$viewValue || self.ngModel.$modelValue;
// Object.keys(self.selected).forEach(self.deselect);
// self.select( self.hashGetter(value), value );
// }
}
}
DropMenuDirective.$inject = ["$parse", "$mdUtil", "$mdTheming"];
function DropOptionDirective($mdButtonInkRipple, $mdUtil) {
OptionController.$inject = ["$element"];
return {
restrict: 'E',
// require: ['mdDropOption','^^mdDropMenu'],
require: ['mdDropOption'],
controller: OptionController,
compile: compile,
link: postLink
};
function compile(element, attr) {
// Manual transclusion to avoid the extra inner <span> that ng-transclude generates
element.append(
angular.element('<div class="md-text">').append(element.contents())
);
element.attr('tabindex', attr.tabindex || '0');
return postLink
}
function postLink(scope, element, attr, ctrls) {
// var optionCtrl = ctrls[0];
// var selectCtrl = ctrls[1];
// if (angular.isDefined(attr.ngValue)) {
// scope.$watch(attr.ngValue, setOptionValue);
// } else if (angular.isDefined(attr.value)) {
// setOptionValue(attr.value);
// } else {
// scope.$watch(function() { return element.text(); }, setOptionValue);
// }
// scope.$$postDigest(function() {
// attr.$observe('selected', function(selected) {
// if (!angular.isDefined(selected)) return;
// if (selected) {
// if (!selectCtrl.isMultiple) {
// selectCtrl.deselect( Object.keys(selectCtrl.selected)[0] );
// }
// selectCtrl.select(optionCtrl.hashKey, optionCtrl.value);
// } else {
// selectCtrl.deselect(optionCtrl.hashKey);
// }
// // selectCtrl.refreshViewValue();
// // selectCtrl.ngModel.$render();
// });
// });
$mdButtonInkRipple.attach(scope, element);
configureAria();
// function setOptionValue(newValue, oldValue) {
// var oldHashKey = selectCtrl.hashGetter(oldValue, scope);
// var newHashKey = selectCtrl.hashGetter(newValue, scope);
//
// optionCtrl.hashKey = newHashKey;
// optionCtrl.value = newValue;
//
// selectCtrl.removeOption(oldHashKey, optionCtrl);
// selectCtrl.addOption(newHashKey, optionCtrl);
// }
//
// scope.$on('$destroy', function() {
// selectCtrl.removeOption(optionCtrl.hashKey, optionCtrl);
// });
function configureAria() {
element.attr({
'role': 'option',
'aria-selected': 'false',
'id': 'drop_option_'+ $mdUtil.nextUid()
});
}
}
function OptionController($element) {
this.selected = false;
this.setSelected = function(isSelected) {
if (isSelected && !this.selected) {
$element.attr({
'selected': 'selected',
'aria-selected': 'true'
});
} else if (!isSelected && this.selected) {
$element.removeAttr('selected');
$element.attr('aria-selected', 'false');
}
this.selected = isSelected;
};
}
}
DropOptionDirective.$inject = ["$mdButtonInkRipple", "$mdUtil"];
function OptgroupDirective() {
return {
restrict: 'E',
compile: compile
};
function compile(el, attrs) {
var labelElement = el.find('label');
if (!labelElement.length) {
labelElement = angular.element('<label>');
el.prepend(labelElement);
}
if (attrs.label) labelElement.text(attrs.label);
}
}
function DropProvider($$interimElementProvider) {
selectDefaultOptions.$inject = ["$mdDropmenu", "$mdConstant", "$$rAF",
"$mdUtil", "$mdTheming", "$timeout",
"$window"];
return $$interimElementProvider('$mdDropmenu')
.setDefaults({
methods: ['target'],
options: selectDefaultOptions
});
/* @ngInject */
function selectDefaultOptions($mdDropmenu, $mdConstant, $$rAF, $mdUtil,
$mdTheming, $timeout, $window ) {
return {
parent: 'body',
onShow: onShow,
onRemove: onRemove,
hasBackdrop: true,
disableParentScroll: true,
themable: true
};
function onShow(scope, element, opts) {
if (!opts.target) {
throw new Error(
'$mdDropmenu.show() expected a target element in '+
'options.target but got "' + opts.target + '"!');
}
angular.extend(opts, {
isRemoved: false,
target: angular.element(opts.target),
//make sure it's not a naked dom node
parent: angular.element(opts.parent),
selectEl: element.find('md-drop-menu'),
contentEl: element.find('md-content'),
backdrop: opts.hasBackdrop && angular.element(
'<md-backdrop class="md-dropmenu-backdrop md-click-catcher">'
)
});
opts.resizeFn = function() {
$$rAF(function() {
$$rAF(function() {
animateSelect(scope, element, opts);
});
});
};
angular.element($window).on('resize', opts.resizeFn);
angular.element($window).on('orientationchange', opts.resizeFn);
configureAria();
element.removeClass('md-leave');
var optionNodes = opts.selectEl[0]
.getElementsByTagName('md-drop-option');
// create fake option for auto focus disabled
if(!opts.autoFocus && optionNodes.length > 0 && !optionNodes[0].getAttribute("fake")){
var fakeOption = document.createElement("md-drop-option");
var parentE = optionNodes[0].parentElement;
// fakeOption.style.visibility = "hidden";
fakeOption.style.height = "1px";
fakeOption.style.width = "0";
fakeOption.style.maxHeight = "1px";
fakeOption.style.maxWidth = "0";
fakeOption.style.opacity = "0";
fakeOption.setAttribute("tabindex", "0");
fakeOption.setAttribute("fake", true);
parentE.insertBefore(fakeOption, optionNodes[0]);
optionNodes = opts.selectEl[0].getElementsByTagName('md-drop-option');
}
// console.log(opts.selectEl[0], optionNodes);
if (opts.loadingAsync && opts.loadingAsync.then) {
opts.loadingAsync.then(function() {
scope.$$loadingAsyncDone = true;
// Give ourselves two frames for the progress loader to clear out.
$$rAF(function() {
$$rAF(function() {
// Don't go forward if the select has been removed in this time...
if (opts.isRemoved) return;
animateSelect(scope, element, opts);
});
});
});
} else if (opts.loadingAsync) {
scope.$$loadingAsyncDone = true;
}
if (opts.disableParentScroll
&& !$mdUtil.getClosest(opts.target, 'MD-DIALOG')) {
opts.restoreScroll = $mdUtil.disableScrollAround(opts.target);
} else {
opts.disableParentScroll = false;
}
// Only activate click listeners after a short time to stop accidental double taps/clicks
// from clicking the wrong item
$timeout(activateInteraction, 75, false);
if (opts.backdrop) {
$mdTheming.inherit(opts.backdrop, opts.parent);
opts.parent.append(opts.backdrop);
}
opts.parent.append(element);
// Give the select a frame to 'initialize' in the DOM,
// so we can read its height/width/position
$$rAF(function() {
$$rAF(function() {
if (opts.isRemoved) return;
animateSelect(scope, element, opts);
});
});
return $mdUtil.transitionEndPromise(opts.selectEl, {timeout: 350});
function configureAria() {
opts.target.attr('aria-expanded', 'true');
}
function activateInteraction() {
if (opts.isRemoved) return;
// var selectCtrl = opts.selectEl.controller('mdDropMenu') || {};
element.addClass('md-clickable');
opts.backdrop && opts.backdrop.on('click', function(e) {
e.preventDefault();
e.stopPropagation();
opts.restoreFocus = false;
scope.$apply($mdDropmenu.cancel);
});
// Escape to close
opts.selectEl.on('keydown', function(ev) {
switch (ev.keyCode) {