-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfoundation.js
7470 lines (6762 loc) · 229 KB
/
foundation.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
!function($) {
"use strict";
var FOUNDATION_VERSION = '6.0.5';
// Global Foundation object
// This is attached to the window, or used as a module for AMD/Browserify
var Foundation = {
version: FOUNDATION_VERSION,
/**
* Stores initialized plugins.
*/
_plugins: {},
/**
* Stores generated unique ids for plugin instances
*/
_uuids: [],
/**
* Stores currently active plugins.
*/
_activePlugins: {},
/**
* Returns a boolean for RTL support
*/
rtl: function(){
return $('html').attr('dir') === 'rtl';
},
/**
* Defines a Foundation plugin, adding it to the `Foundation` namespace and the list of plugins to initialize when reflowing.
* @param {Object} plugin - The constructor of the plugin.
*/
plugin: function(plugin, name) {
// Object key to use when adding to global Foundation object
// Examples: Foundation.Reveal, Foundation.OffCanvas
var className = (name || functionName(plugin));
// Object key to use when storing the plugin, also used to create the identifying data attribute for the plugin
// Examples: data-reveal, data-off-canvas
var attrName = hyphenate(className);
// Add to the Foundation object and the plugins list (for reflowing)
this._plugins[attrName] = this[className] = plugin;
},
/**
* @function
* Creates a pointer to an instance of a Plugin within the Foundation._activePlugins object.
* Sets the `[data-pluginName="uniqueIdHere"]`, allowing easy access to any plugin's internal methods.
* Also fires the initialization event for each plugin, consolidating repeditive code.
* @param {Object} plugin - an instance of a plugin, usually `this` in context.
* @fires Plugin#init
*/
registerPlugin: function(plugin){
var pluginName = functionName(plugin.constructor).toLowerCase();
plugin.uuid = this.GetYoDigits(6, pluginName);
if(!plugin.$element.attr('data-' + pluginName)){
plugin.$element.attr('data-' + pluginName, plugin.uuid);
}
/**
* Fires when the plugin has initialized.
* @event Plugin#init
*/
plugin.$element.trigger('init.zf.' + pluginName);
this._activePlugins[plugin.uuid] = plugin;
return;
},
/**
* @function
* Removes the pointer for an instance of a Plugin from the Foundation._activePlugins obj.
* Also fires the destroyed event for the plugin, consolidating repeditive code.
* @param {Object} plugin - an instance of a plugin, usually `this` in context.
* @fires Plugin#destroyed
*/
unregisterPlugin: function(plugin){
var pluginName = functionName(plugin.constructor).toLowerCase();
delete this._activePlugins[plugin.uuid];
plugin.$element.removeAttr('data-' + pluginName)
/**
* Fires when the plugin has been destroyed.
* @event Plugin#destroyed
*/
.trigger('destroyed.zf.' + pluginName);
return;
},
/**
* @function
* Causes one or more active plugins to re-initialize, resetting event listeners, recalculating positions, etc.
* @param {String} plugins - optional string of an individual plugin key, attained by calling `$(element).data('pluginName')`, or string of a plugin class i.e. `'dropdown'`
* @default If no argument is passed, reflow all currently active plugins.
*/
_reflow: function(plugins){
var actvPlugins = Object.keys(this._activePlugins);
var _this = this;
if(!plugins){
actvPlugins.forEach(function(p){
_this._activePlugins[p]._init();
});
}else if(typeof plugins === 'string'){
var namespace = plugins.split('-')[1];
if(namespace){
this._activePlugins[plugins]._init();
}else{
namespace = new RegExp(plugins, 'i');
actvPlugins.filter(function(p){
return namespace.test(p);
}).forEach(function(p){
_this._activePlugins[p]._init();
});
}
}
},
/**
* returns a random base-36 uid with namespacing
* @function
* @param {Number} length - number of random base-36 digits desired. Increase for more random strings.
* @param {String} namespace - name of plugin to be incorporated in uid, optional.
* @default {String} '' - if no plugin name is provided, nothing is appended to the uid.
* @returns {String} - unique id
*/
GetYoDigits: function(length, namespace){
length = length || 6;
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1) + (namespace ? '-' + namespace : '');
},
/**
* Initialize plugins on any elements within `elem` (and `elem` itself) that aren't already initialized.
* @param {Object} elem - jQuery object containing the element to check inside. Also checks the element itself, unless it's the `document` object.
* @param {String|Array} plugins - A list of plugins to initialize. Leave this out to initialize everything.
*/
reflow: function(elem, plugins) {
// If plugins is undefined, just grab everything
if (typeof plugins === 'undefined') {
plugins = Object.keys(this._plugins);
}
// If plugins is a string, convert it to an array with one item
else if (typeof plugins === 'string') {
plugins = [plugins];
}
var _this = this;
// Iterate through each plugin
$.each(plugins, function(i, name) {
// Get the current plugin
var plugin = _this._plugins[name];
// Localize the search to all elements inside elem, as well as elem itself, unless elem === document
var $elem = $(elem).find('[data-'+name+']').addBack('[data-'+name+']');
// For each plugin found, initialize it
$elem.each(function() {
var $el = $(this),
opts = {};
// Don't double-dip on plugins
if ($el.data('zf-plugin')) {
console.warn("Tried to initialize "+name+" on an element that already has a Foundation plugin.");
return;
}
if($el.attr('data-options')){
var thing = $el.attr('data-options').split(';').forEach(function(e, i){
var opt = e.split(':').map(function(el){ return el.trim(); });
if(opt[0]) opts[opt[0]] = parseValue(opt[1]);
});
}
try{
$el.data('zf-plugin', new plugin($(this), opts));
}catch(er){
console.error(er);
}finally{
return;
}
});
});
},
getFnName: functionName,
transitionend: function($elem){
var transitions = {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'otransitionend'
};
var elem = document.createElement('div'),
end;
for (var t in transitions){
if (typeof elem.style[t] !== 'undefined'){
end = transitions[t];
}
}
if(end){
return end;
}else{
end = setTimeout(function(){
$elem.triggerHandler('transitionend', [$elem]);
}, 1);
return 'transitionend';
}
}
};
Foundation.util = {
/**
* Function for applying a debounce effect to a function call.
* @function
* @param {Function} func - Function to be called at end of timeout.
* @param {Number} delay - Time in ms to delay the call of `func`.
* @returns function
*/
throttle: function (func, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
if (timer === null) {
timer = setTimeout(function () {
func.apply(context, args);
timer = null;
}, delay);
}
};
}
};
// TODO: consider not making this a jQuery function
// TODO: need way to reflow vs. re-initialize
/**
* The Foundation jQuery method.
* @param {String|Array} method - An action to perform on the current jQuery object.
*/
var foundation = function(method) {
var type = typeof method,
$meta = $('meta.foundation-mq'),
$noJS = $('.no-js');
if(!$meta.length){
$('<meta class="foundation-mq">').appendTo(document.head);
}
if($noJS.length){
$noJS.removeClass('no-js');
}
if(type === 'undefined'){//needs to initialize the Foundation object, or an individual plugin.
Foundation.MediaQuery._init();
Foundation.reflow(this);
}else if(type === 'string'){//an individual method to invoke on a plugin or group of plugins
var args = Array.prototype.slice.call(arguments, 1);//collect all the arguments, if necessary
var plugClass = this.data('zfPlugin');//determine the class of plugin
if(plugClass !== undefined && plugClass[method] !== undefined){//make sure both the class and method exist
if(this.length === 1){//if there's only one, call it directly.
plugClass[method].apply(plugClass, args);
}else{
this.each(function(i, el){//otherwise loop through the jQuery collection and invoke the method on each
plugClass[method].apply($(el).data('zfPlugin'), args);
});
}
}else{//error for no class or no method
throw new ReferenceError("We're sorry, '" + method + "' is not an available method for " + (plugClass ? functionName(plugClass) : 'this element') + '.');
}
}else{//error for invalid argument type
throw new TypeError("We're sorry, '" + type + "' is not a valid parameter. You must use a string representing the method you wish to invoke.");
}
return this;
};
window.Foundation = Foundation;
$.fn.foundation = foundation;
// Polyfill for requestAnimationFrame
(function() {
if (!Date.now || !window.Date.now)
window.Date.now = Date.now = function() { return new Date().getTime(); };
var vendors = ['webkit', 'moz'];
for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
var vp = vendors[i];
window.requestAnimationFrame = window[vp+'RequestAnimationFrame'];
window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame']
|| window[vp+'CancelRequestAnimationFrame']);
}
if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent)
|| !window.requestAnimationFrame || !window.cancelAnimationFrame) {
var lastTime = 0;
window.requestAnimationFrame = function(callback) {
var now = Date.now();
var nextTime = Math.max(lastTime + 16, now);
return setTimeout(function() { callback(lastTime = nextTime); },
nextTime - now);
};
window.cancelAnimationFrame = clearTimeout;
}
/**
* Polyfill for performance.now, required by rAF
*/
if(!window.performance || !window.performance.now){
window.performance = {
start: Date.now(),
now: function(){ return Date.now() - this.start; }
};
}
})();
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP
? this
: oThis,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
if (this.prototype) {
// native functions don't have a prototype
fNOP.prototype = this.prototype;
}
fBound.prototype = new fNOP();
return fBound;
};
}
// Polyfill to get the name of a function in IE9
function functionName(fn) {
if (Function.prototype.name === undefined) {
var funcNameRegex = /function\s([^(]{1,})\(/;
var results = (funcNameRegex).exec((fn).toString());
return (results && results.length > 1) ? results[1].trim() : "";
}
else if (fn.prototype === undefined) {
return fn.constructor.name;
}
else {
return fn.prototype.constructor.name;
}
}
function parseValue(str){
if(/true/.test(str)) return true;
else if(/false/.test(str)) return false;
else if(!isNaN(str * 1)/* && typeof (str * 1) === "number"*/) return parseFloat(str);
return str;
}
// Convert PascalCase to kebab-case
// Thank you: http://stackoverflow.com/a/8955580
function hyphenate(str) {
return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
}(jQuery);
!function(Foundation, window){
/**
* Compares the dimensions of an element to a container and determines collision events with container.
* @function
* @param {jQuery} element - jQuery object to test for collisions.
* @param {jQuery} parent - jQuery object to use as bounding container.
* @param {Boolean} lrOnly - set to true to check left and right values only.
* @param {Boolean} tbOnly - set to true to check top and bottom values only.
* @default if no parent object passed, detects collisions with `window`.
* @returns {Boolean} - true if collision free, false if a collision in any direction.
*/
var ImNotTouchingYou = function(element, parent, lrOnly, tbOnly){
var eleDims = GetDimensions(element),
top, bottom, left, right;
if(parent){
var parDims = GetDimensions(parent);
bottom = (eleDims.offset.top + eleDims.height <= parDims.height + parDims.offset.top);
top = (eleDims.offset.top >= parDims.offset.top);
left = (eleDims.offset.left >= parDims.offset.left);
right = (eleDims.offset.left + eleDims.width <= parDims.width);
}else{
bottom = (eleDims.offset.top + eleDims.height <= eleDims.windowDims.height + eleDims.windowDims.offset.top);
top = (eleDims.offset.top >= eleDims.windowDims.offset.top);
left = (eleDims.offset.left >= eleDims.windowDims.offset.left);
right = (eleDims.offset.left + eleDims.width <= eleDims.windowDims.width);
}
var allDirs = [bottom, top, left, right];
if(lrOnly){ return left === right === true; }
if(tbOnly){ return top === bottom === true; }
return allDirs.indexOf(false) === -1;
};
/**
* Uses native methods to return an object of dimension values.
* @function
* @param {jQuery || HTML} element - jQuery object or DOM element for which to get the dimensions. Can be any element other that document or window.
* @returns {Object} - nested object of integer pixel values
* TODO - if element is window, return only those values.
*/
var GetDimensions = function(elem, test){
elem = elem.length ? elem[0] : elem;
if(elem === window || elem === document){ throw new Error("I'm sorry, Dave. I'm afraid I can't do that."); }
var rect = elem.getBoundingClientRect(),
parRect = elem.parentNode.getBoundingClientRect(),
winRect = document.body.getBoundingClientRect(),
winY = window.pageYOffset,
winX = window.pageXOffset;
return {
width: rect.width,
height: rect.height,
offset: {
top: rect.top + winY,
left: rect.left + winX
},
parentDims: {
width: parRect.width,
height: parRect.height,
offset: {
top: parRect.top + winY,
left: parRect.left + winX
}
},
windowDims: {
width: winRect.width,
height: winRect.height,
offset: {
top: winY,
left: winX
}
}
};
};
/**
* Returns an object of top and left integer pixel values for dynamically rendered elements,
* such as: Tooltip, Reveal, and Dropdown
* @function
* @param {jQuery} element - jQuery object for the element being positioned.
* @param {jQuery} anchor - jQuery object for the element's anchor point.
* @param {String} position - a string relating to the desired position of the element, relative to it's anchor
* @param {Number} vOffset - integer pixel value of desired vertical separation between anchor and element.
* @param {Number} hOffset - integer pixel value of desired horizontal separation between anchor and element.
* @param {Boolean} isOverflow - if a collision event is detected, sets to true to default the element to full width - any desired offset.
* TODO alter/rewrite to work with `em` values as well/instead of pixels
*/
var GetOffsets = function(element, anchor, position, vOffset, hOffset, isOverflow){
var $eleDims = GetDimensions(element),
// var $eleDims = GetDimensions(element),
$anchorDims = anchor ? GetDimensions(anchor) : null;
// $anchorDims = anchor ? GetDimensions(anchor) : null;
switch(position){
case 'top':
return {
left: $anchorDims.offset.left,
top: $anchorDims.offset.top - ($eleDims.height + vOffset)
};
break;
case 'left':
return {
left: $anchorDims.offset.left - ($eleDims.width + hOffset),
top: $anchorDims.offset.top
};
break;
case 'right':
return {
left: $anchorDims.offset.left + $anchorDims.width + hOffset,
top: $anchorDims.offset.top
};
break;
case 'center top':
return {
left: ($anchorDims.offset.left + ($anchorDims.width / 2)) - ($eleDims.width / 2),
top: $anchorDims.offset.top - ($eleDims.height + vOffset)
};
break;
case 'center bottom':
return {
left: isOverflow ? hOffset : (($anchorDims.offset.left + ($anchorDims.width / 2)) - ($eleDims.width / 2)),
top: $anchorDims.offset.top + $anchorDims.height + vOffset
};
break;
case 'center left':
return {
left: $anchorDims.offset.left - ($eleDims.width + hOffset),
top: ($anchorDims.offset.top + ($anchorDims.height / 2)) - ($eleDims.height / 2)
};
break;
case 'center right':
return {
left: $anchorDims.offset.left + $anchorDims.width + hOffset + 1,
top: ($anchorDims.offset.top + ($anchorDims.height / 2)) - ($eleDims.height / 2)
};
break;
case 'center':
return {
left: ($eleDims.windowDims.offset.left + ($eleDims.windowDims.width / 2)) - ($eleDims.width / 2),
top: ($eleDims.windowDims.offset.top + ($eleDims.windowDims.height / 2)) - ($eleDims.height / 2)
};
break;
case 'reveal':
return {
left: ($eleDims.windowDims.width - $eleDims.width) / 2,
top: $eleDims.windowDims.offset.top + vOffset
};
case 'reveal full':
return {
left: $eleDims.windowDims.offset.left,
top: $eleDims.windowDims.offset.top
};
break;
default:
return {
left: $anchorDims.offset.left,
top: $anchorDims.offset.top + $anchorDims.height + vOffset
};
}
};
Foundation.Box = {
ImNotTouchingYou: ImNotTouchingYou,
GetDimensions: GetDimensions,
GetOffsets: GetOffsets
};
}(window.Foundation, window);
/*******************************************
* *
* This util was created by Marius Olbertz *
* Please thank Marius on GitHub /owlbertz *
* or the web http://www.mariusolbertz.de/ *
* *
******************************************/
!function($, Foundation){
'use strict';
Foundation.Keyboard = {};
var keyCodes = {
9: 'TAB',
13: 'ENTER',
27: 'ESCAPE',
32: 'SPACE',
37: 'ARROW_LEFT',
38: 'ARROW_UP',
39: 'ARROW_RIGHT',
40: 'ARROW_DOWN'
};
// constants for easier comparing Can be used like Foundation.parseKey(event) === Foundation.keys.SPACE
var keys = (function(kcs) {
var k = {};
for (var kc in kcs) k[kcs[kc]] = kcs[kc];
return k;
})(keyCodes);
Foundation.Keyboard.keys = keys;
/**
* Parses the (keyboard) event and returns a String that represents its key
* Can be used like Foundation.parseKey(event) === Foundation.keys.SPACE
* @param {Event} event - the event generated by the event handler
* @return String key - String that represents the key pressed
*/
var parseKey = function(event) {
var key = keyCodes[event.which || event.keyCode] || String.fromCharCode(event.which).toUpperCase();
if (event.shiftKey) key = 'SHIFT_' + key;
if (event.ctrlKey) key = 'CTRL_' + key;
if (event.altKey) key = 'ALT_' + key;
return key;
};
Foundation.Keyboard.parseKey = parseKey;
// plain commands per component go here, ltr and rtl are merged based on orientation
var commands = {};
/**
* Handles the given (keyboard) event
* @param {Event} event - the event generated by the event handler
* @param {Object} component - Foundation component, e.g. Slider or Reveal
* @param {Objects} functions - collection of functions that are to be executed
*/
var handleKey = function(event, component, functions) {
var commandList = commands[Foundation.getFnName(component)],
keyCode = parseKey(event),
cmds,
command,
fn;
if (!commandList) return console.warn('Component not defined!');
if (typeof commandList.ltr === 'undefined') { // this component does not differentiate between ltr and rtl
cmds = commandList; // use plain list
} else { // merge ltr and rtl: if document is rtl, rtl overwrites ltr and vice versa
if (Foundation.rtl()) cmds = $.extend({}, commandList.ltr, commandList.rtl);
else cmds = $.extend({}, commandList.rtl, commandList.ltr);
}
command = cmds[keyCode];
fn = functions[command];
if (fn && typeof fn === 'function') { // execute function with context of the component if exists
fn.apply(component);
if (functions.handled || typeof functions.handled === 'function') { // execute function when event was handled
functions.handled.apply(component);
}
} else {
if (functions.unhandled || typeof functions.unhandled === 'function') { // execute function when event was not handled
functions.unhandled.apply(component);
}
}
};
Foundation.Keyboard.handleKey = handleKey;
/**
* Finds all focusable elements within the given `$element`
* @param {jQuery} $element - jQuery object to search within
* @return {jQuery} $focusable - all focusable elements within `$element`
*/
var findFocusable = function($element) {
return $element.find('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]').filter(function() {
if (!$(this).is(':visible') || $(this).attr('tabindex') < 0) { return false; } //only have visible elements and those that have a tabindex greater or equal 0
return true;
});
};
Foundation.Keyboard.findFocusable = findFocusable;
/**
* Returns the component name name
* @param {Object} component - Foundation component, e.g. Slider or Reveal
* @return String componentName
*/
var register = function(componentName, cmds) {
commands[componentName] = cmds;
};
Foundation.Keyboard.register = register;
}(jQuery, window.Foundation);
!function($, Foundation) {
// Default set of media queries
var defaultQueries = {
'default' : 'only screen',
landscape : 'only screen and (orientation: landscape)',
portrait : 'only screen and (orientation: portrait)',
retina : 'only screen and (-webkit-min-device-pixel-ratio: 2),' +
'only screen and (min--moz-device-pixel-ratio: 2),' +
'only screen and (-o-min-device-pixel-ratio: 2/1),' +
'only screen and (min-device-pixel-ratio: 2),' +
'only screen and (min-resolution: 192dpi),' +
'only screen and (min-resolution: 2dppx)'
};
var MediaQuery = {
queries: [],
current: '',
/**
* Checks if the screen is at least as wide as a breakpoint.
* @function
* @param {String} size - Name of the breakpoint to check.
* @returns {Boolean} `true` if the breakpoint matches, `false` if it's smaller.
*/
atLeast: function(size) {
var query = this.get(size);
if (query) {
return window.matchMedia(query).matches;
}
return false;
},
/**
* Gets the media query of a breakpoint.
* @function
* @param {String} size - Name of the breakpoint to get.
* @returns {String|null} - The media query of the breakpoint, or `null` if the breakpoint doesn't exist.
*/
get: function(size) {
for (var i in this.queries) {
var query = this.queries[i];
if (size === query.name) return query.value;
}
return null;
},
/**
* Initializes the media query helper, by extracting the breakpoint list from the CSS and activating the breakpoint watcher.
* @function
* @private
*/
_init: function() {
var self = this;
var extractedStyles = $('.foundation-mq').css('font-family');
var namedQueries;
namedQueries = parseStyleToObject(extractedStyles);
for (var key in namedQueries) {
self.queries.push({
name: key,
value: 'only screen and (min-width: ' + namedQueries[key] + ')'
});
}
this.current = this._getCurrentSize();
this._watcher();
// Extend default queries
// namedQueries = $.extend(defaultQueries, namedQueries);
},
/**
* Gets the current breakpoint name by testing every breakpoint and returning the last one to match (the biggest one).
* @function
* @private
* @returns {String} Name of the current breakpoint.
*/
_getCurrentSize: function() {
var matched;
for (var i in this.queries) {
var query = this.queries[i];
if (window.matchMedia(query.value).matches) {
matched = query;
}
}
if(typeof matched === 'object') {
return matched.name;
} else {
return matched;
}
},
/**
* Activates the breakpoint watcher, which fires an event on the window whenever the breakpoint changes.
* @function
* @private
*/
_watcher: function() {
var _this = this;
$(window).on('resize.zf.mediaquery', function() {
var newSize = _this._getCurrentSize();
if (newSize !== _this.current) {
// Broadcast the media query change on the window
$(window).trigger('changed.zf.mediaquery', [newSize, _this.current]);
// Change the current media query
_this.current = newSize;
}
});
}
};
Foundation.MediaQuery = MediaQuery;
// matchMedia() polyfill - Test a CSS media type/query in JS.
// Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license
window.matchMedia || (window.matchMedia = function() {
'use strict';
// For browsers that support matchMedium api such as IE 9 and webkit
var styleMedia = (window.styleMedia || window.media);
// For those that don't support matchMedium
if (!styleMedia) {
var style = document.createElement('style'),
script = document.getElementsByTagName('script')[0],
info = null;
style.type = 'text/css';
style.id = 'matchmediajs-test';
script.parentNode.insertBefore(style, script);
// 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers
info = ('getComputedStyle' in window) && window.getComputedStyle(style, null) || style.currentStyle;
styleMedia = {
matchMedium: function(media) {
var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }';
// 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers
if (style.styleSheet) {
style.styleSheet.cssText = text;
} else {
style.textContent = text;
}
// Test if media query is true or false
return info.width === '1px';
}
};
}
return function(media) {
return {
matches: styleMedia.matchMedium(media || 'all'),
media: media || 'all'
};
};
}());
// Thank you: https://github.com/sindresorhus/query-string
function parseStyleToObject(str) {
var styleObject = {};
if (typeof str !== 'string') {
return styleObject;
}
str = str.trim().slice(1, -1); // browsers re-quote string style values
if (!str) {
return styleObject;
}
styleObject = str.split('&').reduce(function(ret, param) {
var parts = param.replace(/\+/g, ' ').split('=');
var key = parts[0];
var val = parts[1];
key = decodeURIComponent(key);
// missing `=` should be `null`:
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
val = val === undefined ? null : decodeURIComponent(val);
if (!ret.hasOwnProperty(key)) {
ret[key] = val;
} else if (Array.isArray(ret[key])) {
ret[key].push(val);
} else {
ret[key] = [ret[key], val];
}
return ret;
}, {});
return styleObject;
}
}(jQuery, Foundation)
/**
* Motion module.
* @module foundation.motion
*/
!function($, Foundation) {
var initClasses = ['mui-enter', 'mui-leave'];
var activeClasses = ['mui-enter-active', 'mui-leave-active'];
function animate(isIn, element, animation, cb) {
element = $(element).eq(0);
if (!element.length) return;
var initClass = isIn ? initClasses[0] : initClasses[1];
var activeClass = isIn ? activeClasses[0] : activeClasses[1];
// Set up the animation
reset();
element.addClass(animation)
.css('transition', 'none');
// .addClass(initClass);
// if(isIn) element.show();
requestAnimationFrame(function() {
element.addClass(initClass);
if (isIn) element.show();
});
// Start the animation
requestAnimationFrame(function() {
element[0].offsetWidth;
element.css('transition', '');
element.addClass(activeClass);
});
// Move(500, element, function(){
// // element[0].offsetWidth;
// element.css('transition', '');
// element.addClass(activeClass);
// });
// Clean up the animation when it finishes
element.one(Foundation.transitionend(element), finish);//.one('finished.zf.animate', finish);
// Hides the element (for out animations), resets the element, and runs a callback
function finish() {
if (!isIn) element.hide();
reset();
if (cb) cb.apply(element);
}
// Resets transitions and removes motion-specific classes
function reset() {
element[0].style.transitionDuration = 0;
element.removeClass(initClass + ' ' + activeClass + ' ' + animation);
}
}
var Motion = {
animateIn: function(element, animation, /*duration,*/ cb) {
animate(true, element, animation, cb);
},
animateOut: function(element, animation, /*duration,*/ cb) {
animate(false, element, animation, cb);
}
};
var Move = function(duration, elem, fn){
var anim, prog, start = null;
// console.log('called');
function move(ts){
if(!start) start = window.performance.now();
// console.log(start, ts);
prog = ts - start;
fn.apply(elem);
if(prog < duration){ anim = window.requestAnimationFrame(move, elem); }
else{
window.cancelAnimationFrame(anim);
elem.trigger('finished.zf.animate', [elem]).triggerHandler('finished.zf.animate', [elem]);
}
}
anim = window.requestAnimationFrame(move);
};
Foundation.Move = Move;
Foundation.Motion = Motion;
}(jQuery, Foundation);
!function($, Foundation){
'use strict';
Foundation.Nest = {
Feather: function(menu, type){
menu.attr('role', 'menubar');
type = type || 'zf';
var items = menu.find('li').attr({'role': 'menuitem'}),
subMenuClass = 'is-' + type + '-submenu',
subItemClass = subMenuClass + '-item',
hasSubClass = 'is-' + type + '-submenu-parent';
menu.find('a:first').attr('tabindex', 0);
items.each(function(){
var $item = $(this),
$sub = $item.children('ul');
if($sub.length){
$item.addClass('has-submenu ' + hasSubClass)
.attr({
'aria-haspopup': true,
'aria-selected': false,
'aria-expanded': false,
'aria-label': $item.children('a:first').text()
});
$sub.addClass('submenu ' + subMenuClass)
.attr({
'data-submenu': '',
'aria-hidden': true,
'role': 'menu'
});
}
if($item.parent('[data-submenu]').length){
$item.addClass('is-submenu-item ' + subItemClass);
}
});
return;
},
Burn: function(menu, type){
var items = menu.find('li').removeAttr('tabindex'),
subMenuClass = 'is-' + type + '-submenu',
subItemClass = subMenuClass + '-item',
hasSubClass = 'is-' + type + '-submenu-parent';