forked from ryanve/response.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.js
1179 lines (1011 loc) · 47.4 KB
/
response.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
/*!
* Response Responsive design toolkit
* @link http://responsejs.com
* @author Ryan Van Etten (c) 2011-2012
* @license MIT
* @version 0.7.8
* @requires jQuery 1.7+
* -or- ender build jeesh (ender.jit.su)
* -or- zepto 0.8+ (zeptojs.com)
*/
/*jslint browser: true, devel: true, node: true, passfail: false, bitwise: true, continue: true
, debug: true, eqeq: true, es5: true, forin: true, newcap: true, nomen: true, plusplus: true
, regexp: true, undef: true, sloppy: true, stupid: true, sub: true, vars: true, white: true
, indent: 4, maxerr: 180 */
(function(root, name, factory) {// github.com/umdjs/umd
var dep = root['jQuery'] || root['Zepto'] || root['ender'] || root['elo'];
if ( typeof module != 'undefined' && module['exports'] ) {
module['exports'] = factory(dep); // common / ender
} else { root[name] = factory(dep); } // browser
// see @link github.com/ryanve/response.js/pull/9
// AMD @example `define(['jquery'], factory)`
}(this, 'Response', function($) {
if (typeof $ != 'function') {
try {// Exit gracefully if dependency is missing:
console.log('Response was unable to run due to missing dependency.');
} catch (e) {}
}
// Combine local vars/funcs into one statement:
var Response
, root = this
, name = 'Response'
, old = root[name]
, initContentKey = 'init' + name // key for storing initial content
, win = window
, doc = document
, docElem = doc.documentElement
, ready = $.domReady || $
, $win = $(win) // cache selector
, screen = win.screen
, AP = Array.prototype
, OP = Object.prototype
, slice = AP.slice
, concat = AP.concat
, toString = OP.toString
, owns = OP.hasOwnProperty
, isArray = Array.isArray || function(item) {
return '[object Array]' === toString.call(item);
}
, defaultBreakpoints = {
width: [0, 320, 481, 641, 961, 1025, 1281] // width | device-width (ideal for 960 grids)
, height: [0, 481] // height | device-height (maybe add 801 too)
, ratio: [1, 1.5, 2] // device-pixel-ratio (!omit trailing zeros!)
}
// these are defined later
, Elemset, band, wave, device = {}
, propTests = {}
, isCustom = {}
, sets = { all: [] }
, suid = 1
// responsejs.com/labs/dimensions/#device
// device dims stay the same regardless of viewport size or rotation
, screenW = screen.width
, screenH = screen.height
, screenMax = screenW > screenH ? screenW : screenH
, screenMin = screenW + screenH - screenMax
, deviceW = function() { return screenW; }
, deviceH = function() { return screenH; }
// cache expressions
, regexFunkyPunc = /[^a-z0-9_\-\.]/gi
, regexTrimPunc = /^[\W\s]+|[\W\s]+$|/g
, regexCamels = /([a-z])([A-Z])/g
, regexDashB4 = /-(.)/g
, regexDataPrefix = /^data-(.+)$/
// Local version of Object.create with polyfill that supports only the first arg.
// It creates an empty object whose prototype is set to the specified proto param.
// developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create
// FYI there is a full polyfill @link github.com/kriskowal/es5-shim
// This gets exposed as Response.object since 0.4.0
, objectCreate = Object.create || function(proto) {
/** @constructor */
function Type() {} // Function to output empty object.
Type.prototype = proto; // Set prototype property to the proto.
return new Type; // Instantiate the new object.
}
, namespaceIt = function(eventName, customNamespace) {// namepace defaults to 'Response'
customNamespace = customNamespace || name;
return eventName.replace(regexTrimPunc, '') + '.' + customNamespace.replace(regexTrimPunc, '');
}
, event = {// Custom Events
allLoaded: namespaceIt('allLoaded') // fires on lazy elemsets when all elems in a set have been loaded once
//, update: namespaceIt('update') // fires on each elem in a set each time that elem is updated
, crossover: namespaceIt('crossover') // fires on window each time dynamic breakpoint bands is crossed
}
// Response.media (normalized matchMedia)
// @example Response.media("(orientation:landscape)").matches
// If both versions are undefined, .matches will equal undefined
// Also see: band / wave / device.band / device.wave / dpr
, matchMedia = win.matchMedia || win.msMatchMedia
, media = matchMedia || function() { return {}; }
// @link responsejs.com/labs/dimensions/#viewport
// @link github.com/ryanve/response.js/issues/17
, viewportW = (function(win, docElem, mM) {
var client = docElem['clientWidth']
, inner = win['innerWidth'];
return ( mM && client < inner && true === mM('(min-width:' + inner + 'px)')['matches']
? function() { return win['innerWidth']; }
: function() { return docElem['clientWidth']; }
);
}(win, docElem, matchMedia))
, viewportH = (function(win, docElem, mM) {
var client = docElem['clientHeight']
, inner = win['innerHeight'];
return ( mM && client < inner && true === mM('(min-height:' + inner + 'px)')['matches']
? function() { return win['innerHeight']; }
: function() { return docElem['clientHeight']; }
);
}(win, docElem, matchMedia))
;
function doError(msg) {
// Error handling. (Throws exception.)
// Use Ctrl+F to find specific @errors
throw new TypeError(msg ? name + '.' + msg : name);
}
function isNumber(item) {// inlined @minification
return typeof item == 'number' && item === item; // second part stuffs NaN
}
function map(ob, fn, scope) {
var i, l = ob.length, ret = [];
for (i = 0; i < l; i++) {
ret[i] = fn.call(scope, ob[i], i, ob);
}
return ret;
}
function ssvToArr(ukn) {
// Convert space separated values to array. Always returns a compact array:
return typeof ukn == 'string' ? sift(ukn.split(' ')) : isArray(ukn) ? sift(ukn) : [];
}
/**
* Response.each()
* @since 0.4.0
* omits `in` check and supports scope since 0.6.2
*/
function each(ob, callback, scope) {
if ( null == ob ) { return ob; }
var i = 0, len = ob.length;
while ( i < len ) {
callback.call(scope || ob[i], ob[i], i++, ob);
}
return ob; // chain
}
// revamped affix method reintroduced in version 0.4.0:
// updated again in 0.6.2 to skip null|undef values
function affix(arr, prefix, suffix) {
// Return new array with prefix/suffix added to each value.
// null|undefined values are not included in the new array
var r = [], l = arr.length, i = 0, v;
prefix = prefix || '';
suffix = suffix || '';
while ( i < l ) {
v = arr[i++];
null == v || r.push(prefix + v + suffix);
}
return r;
}
/**
* @param {Array|Object} ob is an array or collection to iterate over.
* @param {(Function|string|*)=} fn is a callback or typestring - callbacks receive (v, i, ob)
* @param {(Object|boolean|*)=} scope thisArg or invert
*/
/**
* Response.sift Filter out array values that don't pass a callback,
* or (if no callback provided) filter out falsey values.
* Similar (but more capable that) jQuery.grep or the native [].filter
*
* @since 0.4.0 Updated in 0.6.2 to support scope and typestrings
* @example Response.sift([5, 0, 'seven'], isFinite) // [5, 0]
* @example Response.sift([5, 0, '', undefined, null]) // [5]
*
*/
function sift(ob, fn, scope) {
var l, u = 0, i = 0, v, ret = [], invert, isF = typeof fn == 'function';
if ( !ob ) { return ret; }
scope = (invert = true === scope) ? null : scope;
for ( l = ob.length; i < l; i++ ) {
v = ob[i]; // save reference to value in case `fn` mutates `ob[i]`
// Use `=== !` to ensure that the comparison is bool-to-bool
invert === !(isF ? fn.call(scope, v, i, ob) : fn ? typeof v === fn : v) && (ret[u++] = v);
}
return ret;
}
/**
* Response.merge
* @since 0.3.0
* Generic method for merging objects and/or arrays.
* Undefined values in `adds` are skipped.
* When `adds` is array-like, this behaves similar to jQuery.merge(base, adds)
* Otherwise it behaves similar to jQuery.extend(base, adds)
* @param {Object|Array|Function|*} base
* @param {Object|Array|Function|*} adds
*/
function merge(base, adds) {
var k, l;
if ( !base || !adds ) { return base; }
if ( typeof adds != 'function' && isNumber(l = adds.length) ) {
for ( k = 0; k < l; k++ ) {
void 0 === adds[k] || (base[k] = adds[k]);
}
base.length > k || (base.length = k); // non-arrays
} else {
for ( k in adds ) {
owns.call(adds, k) && void 0 !== adds[k] && (base[k] = adds[k]);
}
}
return base;
}
/**
* Response.route() Handler method for accepting args as arrays or singles, for
* callbacks. Returns self for chaining.
*
* @since 0.3.0 (scope support added in 0.6.2)
*
* @param {*} item If `item` is an array or array-like object then `callback` gets called
* on each member. Otherwise `callback` is called on the `item` itself.
* @param {Function} fn The function to call on item(s).
* @param {*=} scope thisArg (defaults to current item)
*/
function route(item, fn, scope) {
// If item is array-like then call the callback on each item. Otherwise call directly on item.
if ( null == item ) { return item; } // Skip null|undefined
if ( typeof item == 'object' && !item.nodeType && isNumber(item.length) ) {
each(item, fn, scope);
} else {
fn.call(scope || item, item);
}
return item; // chainable
}
/**
* ranger() Make a range comparison tester.
* @param {Function} fn gets a value to compare against
* @return {Function}
*/
function ranger(fn) {
/**
* @param {string|number} min
* @param {(string|number)=} max
*/
return function(min, max) {
var n = fn();
min = n >= (min || 0);
return max ? min && n <= max : min;
};
}
/**
* Range comparison booleans
* @link responsejs.com/#booleans
*/
band = ranger(viewportW); // Response.band
wave = ranger(viewportH); // Response.wave
device.band = ranger(deviceW); // Response.device.band
device.wave = ranger(deviceH); // Response.device.wave
/**
* Response.dpr(decimal) Tests if a minimum device pixel ratio is active.
* Or (version added in 0.3.0) returns the device-pixel-ratio
* @param number decimal is the integer or float to test.
* @return boolean|number
* @example Response.dpr(); // get the device-pixel-ratio (or 0 if undetectable)
* @example Response.dpr(1.5); // true when device-pixel-ratio is 1.5+
* @example Response.dpr(2); // true when device-pixel-ratio is 2+
*/
function dpr(decimal) {
var dPR = win.devicePixelRatio;
if ( null == decimal ) {//Return exact value or kinda iterate for approx:
return dPR || (dpr(2) ? 2 : dpr(1.5) ? 1.5 : dpr(1) ? 1 : 0);
}
if ( !isFinite(decimal) ) {// Shh. Actually allows numeric strings too. ;)
return false;
}
// Use window.devicePixelRatio if supported - supported by Webkit
// (Safari/Chrome/Android) and Presto 2.8+ (Opera) browsers.
if ( dPR && dPR > 0 ) {
return dPR >= decimal;
}
// Fallback to .matchMedia/.msMatchMedia. Supported by Gecko (FF6+) and more:
// @link developer.mozilla.org/en/DOM/window.matchMedia
// -webkit-min- and -o-min- omitted (Webkit/Opera supported above)
// The generic min-device-pixel-ratio is expected to be added to the W3 spec.
// Return false if neither method is available.
decimal = 'only all and (min--moz-device-pixel-ratio:' + decimal + ')';
if ( media(decimal).matches ) { return true; }
return !!media(decimal.replace('-moz-', '')).matches;
}
/**
* Response.camelize Converts data-pulp-fiction to pulpFiction
* via camelize @link github.com/ded/bonzo
* Used in dataset methods.
*
* @example Response.camelize('data-casa-blanca') // casaBlanca
*/
function camelize(s) {
// Remove data- prefix and convert remaining dashed string to camelCase:
return s.replace(regexDataPrefix, '$1').replace(regexDashB4, function(m, m1) {
return m1.toUpperCase();
});
}
/**
* Response.datatize Converts pulpFiction (or data-pulpFiction) to data-pulp-fiction
* Adapted from decamelize @link github.com/ded/bonzo
* Used in dataset methods.
*
* @example Response.datatize('casaBlanca') // data-casa-blanca
*/
function datatize(s) {
// Make sure there's no data- already in s for it to work right in IE8.
return 'data-' + (s ? s.replace(regexDataPrefix, '$1').replace(regexCamels, '$1-$2').toLowerCase() : s);
}
/**
* Response.render Converts stringified primitives back to JavaScript.
* Adapted from dataValue() @link github.com/ded/bonzo
* @since 0.3.0
*
* @param string|other s String to render back to its correct JavaScript value.
* If s is not a string then it is returned unaffected.
* @return converted data
*
*/
function render(s) {
var n; // < undefined
return ( !s || typeof s != 'string' ? s // unchanged
: 'true' === s ? true // convert "true" to true
: 'false' === s ? false // convert "false" to false
: 'undefined' === s ? n // convert "undefined" to undefined
: 'null' === s ? null // convert "null" to null
: (n = parseFloat(s)) === +n ? n // convert "1000" to 1000
: s // unchanged
);
}
// Isolate native element:
function getNative(e) {
// stackoverflow.com/questions/9119823/safest-way-to-detect-native-dom-element
// See @link jsperf.com/get-native
// If e is a native element then return it. If not check if index 0 exists and is
// a native elem. If so then return that. Otherwise return false.
return !e ? false : e.nodeType === 1 ? e : e[0] && e[0].nodeType === 1 ? e[0] : false;
}
/**
* .dataset() Cross browser implementation of HTML5 dataset
* The chainable syntax is disabled by default and can be
* enabled by calling Response.chain() (See Response.chain)
*
* @since 0.3.0
*
* Chainable form: $('div').dataset(key) // get (from first matched element)
* $('div').dataset([key]) // get and render (See Response.render)
* $('div').dataset(key, value) // set (sets all matched elems)
* $('div').dataset({k1:val, k2:val}) // set multiple attrs at once (on all matched elems)
* $('div').deletes(keys) // delete attrs (space-separated string)
*
* Non-chainable: Response.dataset(elem, key) // get (elem can be native or jQuery elem)
* Response.dataset(elem, [key]) // get and render (See Response.render)
* Response.dataset(elem, key, value) // set
* Response.dataset(elem, {k1:val, k2:val}) // set multiple attrs at once
* Response.deletes(elem, keys) // delete attrs (space-separated string)
*
*/
function datasetChainable(key, value) {
var numOfArgs = arguments.length
, elem = getNative(this)
, ret = {}
, renderData = false
, n;
if ( numOfArgs ) {
if ( isArray(key) ) {
renderData = true;
key = key[0];
}
if ( typeof key === 'string' ) {
key = datatize(key);
if ( 1 === numOfArgs ) {//GET
ret = elem.getAttribute(key);
return renderData ? render(ret) : ret;
}
if ( this === elem || 2 > (n = this.length || 1) ) {//SET single elem
elem.setAttribute(key, value);
} else {//SET for group of selected elems
while( n-- ) {// n starts as # of elems in selector and stops at 0
if (n in this) {
datasetChainable.apply(this[n], arguments);
}
}
}
} else if ( key instanceof Object ) {//SET
for (n in key) {
key.hasOwnProperty(n) && datasetChainable.call(this, n, key[n]);
}
}
return this; // chain
}//1 or more args
// ** Zero args **
// Return object containing all the data attributes.
// Use the native dataset when available:
if ( elem.dataset && DOMStringMap ) {
return elem.dataset;
}
// adapted from Bonzo @link github.com/ded/bonzo/blob/master/bonzo.js
each(elem.attributes, function(a) {
if (a && (n = String(a.name).match(regexDataPrefix))) {
ret[camelize(n[1])] = a.value;
}
});
return ret; // plain object
}
/**
* .deletes()
* @since 0.3.0
*/
function deletesChainable(keys) {
if (this && typeof keys === 'string') {
keys = ssvToArr(keys);
route(this, function(el) {
each(keys, function(key) {
if (key) {
el.removeAttribute(datatize(key));
}
});
});
}
return this;
}
/**
* Response.dataset() See datasetChainable above
* This is the non-chainable version. It grabs the thisArg
* and calls the chainable version
*
* @since 0.3.0
*/
function dataset(elem, key, value) {
return datasetChainable.apply(elem, slice.call(arguments, 1));
}
/**
* Response.deletes(elem, keys) Delete HTML5 data attributes (remove them from them DOM)
*
* @since 0.3.0
* Where native DOM dataset is supported you can do: `delete elem.dataset.foo`
*
* @param object elem is a native element or jQuery object e.g. document.body or $('body')
*
* @param string keys one or more space-separated data attribute keys (names) to delete (removed
* from the DOM) Should be camelCased or lowercase.
*
* @example Response.deletes(document.body, 'casaBlanca movie'); // Removes data-casa-blanca and data-movie
* // from the <body> element.
*
* @example Response.deletes($(div), 'casaBlanca movie') // Removes data-casa-blanca and data-movie
* // from all divs.
*/
function deletes(elem, keys) {
return deletesChainable.call(elem, keys);
}
function selectify(keys) {
// Convert an array of data keys into a selector string
// Converts ["a","b","c"] into "[data-a],[data-b],[data-c]"
// Double-slash escapes periods so that attrs like data-density-1.5 will work
// @link api.jquery.com/category/selectors/
// @link github.com/jquery/sizzle/issues/76
var k, r = [], i = 0, l = keys.length;
while ( i < l ) {
(k = keys[i++]) && r.push('[' + datatize(k.replace(regexTrimPunc, '').replace('.', '\\.')) + ']');
}
return r.join();
}
/**
* Response.target() Get the corresponding data attributes for an array of data keys.
* @since 0.1.9
* @param array keys is the array of data keys whose attributes you want to select.
* @return object jQuery selector
* @example Response.target(['a', 'b', 'c']) // $('[data-a],[data-b],[data-c]')
* @example Response.target('a b c']) // $('[data-a],[data-b],[data-c]')
*/
function target(keys) {
return $(selectify(ssvToArr(keys)));
}
// Cross-browser versions of window.scrollX and window.scrollY
// Compatibiliy notes @link developer.mozilla.org/en/DOM/window.scrollY
// Performance tests @link jsperf.com/scrollx-cross-browser-compatible
// Using native here b/c Zepto doesn't support .scrollLeft() /scrollTop()
// In jQuery you can do $(window).scrollLeft() and $(window).scrollTop()
/**
* Response.scrollX() Cross-browser version of window.scrollX
* @since 0.3.0
* @return integer
*/
function scrollX() {
return window.pageXOffset || docElem.scrollLeft;
}
/**
* Response.scrollY() Cross-browser version of window.scrollY
* @since 0.3.0
* @return integer
*/
function scrollY() {
return window.pageYOffset || docElem.scrollTop;
}
/**
* area methods inX/inY/inViewport
* @since 0.3.0
*/
function rectangle(el, verge) {
// Local handler for area methods:
// adapted from github.com/ryanve/dime
// The native object is read-only so we
// have use a copy in order to modify it.
var r = el.getBoundingClientRect ? el.getBoundingClientRect() : {};
verge = typeof verge == 'number' ? verge || 0 : 0;
return {
top: (r.top || 0) - verge
, left: (r.left || 0) - verge
, bottom: (r.bottom || 0) + verge
, right: (r.right || 0) + verge
};
}
// The verge is the amount of pixels to act as a cushion around the viewport. It can be any
// integer. If verge is zero, then the inX/inY/inViewport methods are exact. If verge is set to 100,
// then those methods return true when for elements that are are in the viewport *or* near it,
// with *near* being defined as within 100 pixels outside the viewport edge. Elements immediately
// outside the viewport are 'on the verge' of being scrolled to.
function inX(elem, verge) {
var r = rectangle(getNative(elem), verge);
return !!r && r.right >= 0 && r.left <= viewportW();
}
function inY(elem, verge) {
var r = rectangle(getNative(elem), verge);
return !!r && r.bottom >= 0 && r.top <= viewportH();
}
function inViewport(elem, verge) {
// equiv to: inX(elem, verge) && inY(elem, verge)
// But just manually do both to avoid calling rectangle() and getNative() twice.
// It actually gzips smaller this way too:
var r = rectangle(getNative(elem), verge);
return !!r && r.bottom >= 0 && r.top <= viewportH() && r.right >= 0 && r.left <= viewportW();
}
function detectMode(elem) {
// Detect whether elem should act in src or markup mode.
// @param elem is a DOM element
// @return number
// @link dev.w3.org/html5/spec-author-view/index.html#attributes-1
// @link stackoverflow.com/q/8715689/770127
// @link stackoverflow.com/a/4878963/770127
// Normalize to lowercase to ensure compatibility across HTML/XHTML/XML.
// These are the elems that can use src attr per the W3 spec:
var srcElems = { img:1, input:1, source:3, embed:3, track:3, iframe:5, audio:5, video:5, script:5 }
, modeID = srcElems[ elem.nodeName.toLowerCase() ] || -1;
// -5 => markup mode for video/audio/iframe w/o src attr.
// -1 => markup mode for any elem not in the array above.
// 1 => src mode for img/input (empty content model). Images.
// 3 => src mode for source/embed/track (empty content model). Media *or* time data.
// 5 => src mode for audio/video/iframe/script *with* src attr.
// If we at some point we need to differentiate <track> we'll use 4, but for now
// it's grouped with the other non-image empty content elems that use src.
// hasAttribute is not supported in IE7 so check elem.getAttribute('src')
return 4 > modeID ? modeID : null != elem.getAttribute('src') ? 5 : -5;
}
/**
* Response.store()
* @since 0.1.9
*
* Store a data value on each elem targeted by a jQuery selector. We use this for storing an
* elem's orig (no-js) state. This gives us the ability to return the elem to its orig state.
* The data it stores is either the src attr or the innerHTML based on result of detectMode().
*
* @param {Object} $elems DOM element | jQuery object | nodeList | array of elements
* @param {string} key is the key to use to store the orig value w/ @link api.jquery.com/data/
* @param {string=} source (@since 0.6.2) an optional attribute name to read data from
*
*/
function store($elems, key, source) {
var valToStore;
if ( !$elems || null == key) { doError('store'); }
source = typeof source == 'string' && source;
route($elems, function(el) {
if ( source ) { valToStore = el.getAttribute(source); }
else if ( 0 < detectMode(el) ) { valToStore = el.getAttribute('src'); }
else { valToStore = el.innerHTML; }
null == valToStore ? deletes(el, key) : dataset(el, key, valToStore);
});
return Response;
}
/**
* Response.access() Access data-* values for element from an array of data-* keys.
*
* @since 0.1.9 (added support for space-separated strings in 0.3.1)
*
* @param object elem is a native or jQuery element whose values to access.
* @param array|string keys is an array or space-separated string of data keys whose
* values you want to access.
*
* @return array of dataset values corresponding to each key. Since 0.4.0 if
* the params are wrong then the return is an empty array.
*/
function access(elem, keys) {
// elem becomes thisArg for datasetChainable:
var ret = [];
elem && keys && each(ssvToArr(keys), function(k, i) {
ret.push(dataset(elem, k));
}, elem);
return ret;
}
/**
* Response.addTest
*
*/
function addTest(prop, fn) {
if (typeof prop == 'string' && typeof fn == 'function') {
propTests[prop] = fn;
isCustom[prop] = 1;
}
return Response;
}
/*
* Elemset Prototype object for element sets used in Response.create
* Each element in the set inherits this as well, so some of the
* methods apply to the set, while others apply to single elements.
*/
Elemset = (function() {
var crossover = event.crossover
//, update = event.update
, min = Math.min;
// Techically data attributes names can contain uppercase in HTML, but, The DOM lowercases
// attributes, so they must be lowercase regardless when we target them in jQuery. Force them
// lowercase here to prevent issues. Removing all punc marks except for dashes, underscores,
// and periods so that we don't have to worry about escaping anything crazy.
// Rules @link dev.w3.org/html5/spec/Overview.html#custom-data-attribute
// jQuery selectors @link api.jquery.com/category/selectors/
function sanitize (key) {
// Allow lowercase alphanumerics, dashes, underscores, and periods:
return typeof key == 'string' ? key.toLowerCase().replace(regexFunkyPunc, '') : '';
}
return {
$e: 0 // object jQuery object
, mode: 0 // integer defined per element
, breakpoints: null // array validated @ configure()
, prefix: null // string validated @ configure()
, prop: 'width' // string validated @ configure()
, keys: [] // array defined @ configure()
, dynamic: null // boolean defined @ configure()
, custom: 0 // boolean see addTest()
, values: [] // array available values
, fn: 0 // callback the test fn, defined @ configure()
, verge: null // integer defaults to Math.min(screenMax, 500)
, newValue: 0
, currValue: 1
, aka: null
, lazy: null
, i: 0 // integer the index of the current highest active breakpoint min
, uid: null
, reset: function() {// Reset / fire crossover events:
var subjects = this.breakpoints
, i = subjects.length
, tempIndex = 0;
// This is similar to the decideValue loop
while( !tempIndex && i-- ) {
this.fn(subjects[i]) && (tempIndex = i);
}
// Fire the crossover event if crossover has occured:
if (tempIndex !== this.i) {
$win.trigger(crossover) // fires for each set
.trigger(this.prop + crossover); // fires
this.i = tempIndex || 0;
}
return this; // chainable
}
, configure: function(options) {
merge(this, options);
var i, prefix, aliases, aliasKeys, isNumeric = true, arr, prop = this.prop;
this.uid = suid++;
this.verge = isFinite(this.verge) ? this.verge : min(screenMax, 500);
this.fn = propTests[prop] || doError('create @fn');
// If we get to here then we know the prop is one one our supported props:
// 'width', 'height', 'device-width', 'device-height', 'device-pixel-ratio'
// device- props => NOT dynamic
if (typeof this.dynamic != 'boolean') {
this.dynamic = !!('device' !== prop.substring(0, 6));
}
this.custom = isCustom[prop];
prefix = this.prefix ? sift(map(ssvToArr(this.prefix), sanitize)) : ['min-' + prop + '-'];
aliases = 1 < prefix.length ? prefix.slice(1) : 0;
this.prefix = prefix[0];
arr = this.breakpoints;
// Sort and validate (#valid8) custom breakpoints if supplied.
// Must be done before keys are created so that the keys match:
if ( isArray(arr) ) {// custom breakpoints
each(arr, function(v) {
if ( !v && v !== 0 ) { throw 'invalid breakpoint'; } // null|undefined|''|NaN
isNumeric = isNumeric && isFinite(v);
});
arr = isNumeric ? arr.sort(function(a, b) {
return (a - b); // sort lowest to highest
}) : arr;
arr.length || doError('create @breakpoints');
} else {// default breakpoints:
// The defaults are presorted so we can skip the need to sort when using the defaults. Omit
// trailing decimal zeros b/c for example if you put 1.0 as a devicePixelRatio breakpoint,
// then the target would be data-pre1 (NOT data-pre1.0) so drop the zeros.
// If no breakpoints are supplied, then get the default breakpoints for the specified prop.
// Supported props: 'width', 'height', 'device-width', 'device-height', 'device-pixel-ratio'
arr = defaultBreakpoints[prop] || defaultBreakpoints[prop.split('-').pop()] || doError('create @prop');
}
// Remove breakpoints that are above the device's max dimension,
// in order to reduce the number of iterations needed later.
this.breakpoints = isNumeric ? sift(arr, function(n) {
return n <= screenMax;
}) : arr;
// Use the breakpoints array to create array of data keys:
this.keys = affix(this.breakpoints, this.prefix);
this.aka = null; // Reset to just in case a value was merged in.
if ( aliases ) {// There may be one of more aliases:
aliasKeys = [];
i = aliases.length;
while ( i-- ) { aliasKeys.push(affix(this.breakpoints, aliases[i])); }
this.aka = aliasKeys; // this.aka is an array of arrays (one for each alias)
this.keys = concat.apply(this.keys, aliasKeys); // flatten aliases into this.keys
}
sets.all = sets.all.concat(sets[this.uid] = this.keys); // combined keys ===> sets.all
return this; // chainable
}
, target: function() {// Stuff that can't happen until the DOM is ready:
this.$e = $(selectify(sets[this.uid])); // Cache jQuery object for the set.
store(this.$e, initContentKey); // Store original (no-js) value to data key.
this.keys.push(initContentKey); // Add key onto end of keys array. (# keys now equals # breakpoints + 1)
return this; // chainable
}
// The rest of the methods are designed for use with single elements.
// They are for use in a cloned instances within a loop.
, decideValue: function() {
// Return the first value from the values array that passes the boolean
// test callback. If none pass the test, then return the fallback value.
// this.breakpoints.length === this.values.length + 1
// The extra member in the values array is the initContentKey value.
var val = null
, subjects = this.breakpoints
, sL = subjects.length
, i = sL;
while( val == null && i-- ) {
this.fn(subjects[i]) && (val = this.values[i]);
}
this.newValue = typeof val === 'string' ? val : this.values[sL];
return this; // chainable
}
, prepareData: function(elem) {
this.$e = $(elem); // jQuery selector
this.mode = detectMode(elem); // Detect the mode of the element.
this.values = access(this.$e, this.keys); // Access Response data- values for the element.
if (this.aka) {
var i = this.aka.length;
// If there are alias keys then there may be alias values. Merge the values from
// all the aliases into the values array. The merge method only merges in truthy values
// and prevents falsey values from overwriting truthy ones. (See Response.merge)
while ( i-- ) {// loops down and stops at index 0
// Each of the this.aka arrays has the same length as the this.values
// array, so no new indexes will be added, just filled if there's truthy values.
this.values = merge(this.values, access(this.$e, this.aka[i]));
}
}
return this.decideValue(); // chainable
}
, updateDOM: function() {
// Apply the method that performs the actual swap. When updateDOM called this.$e and this.e refer
// to single elements. Only update the DOM when the new value is different than the current value.
if (this.currValue === this.newValue) { return this; }
this.currValue = this.newValue;
if ( 0 < this.mode ) {
this.$e[0].setAttribute('src', this.newValue);
} else if ( null == this.newValue ) {
this.$e.empty && this.$e.empty();
} else {
if (this.$e.html) {
this.$e.html(this.newValue);
} else {
this.$e.empty && this.$e.empty();
this.$e[0].innerHTML = this.newValue;
}
}
// this.$e.trigger(update); // may add this event in future
return this;
}
};//return
}());//Elemset
// The keys are the prop and the values are the method that tests that prop.
// The props with dashes in them are added via array notation below.
// Props marked as dynamic change when the viewport is resized:
propTests['width'] = band; // dynamic
propTests['height'] = wave; // dynamic
propTests['device-width'] = device.band;
propTests['device-height'] = device.wave;
propTests['device-pixel-ratio'] = dpr;
/**
* Response.resize
*/
function resize(fn) {
$win.on('resize', fn);
return Response; // chain
}
/**
* Response.crossover
*
*/
function crossover(prop, fn) {
var temp, eventToFire, eventCrossover = event.crossover;
if (typeof prop == 'function') {// support args in reverse
temp = fn;
fn = prop;
prop = temp;
}
eventToFire = prop ? ('' + prop + eventCrossover) : eventCrossover;
$win.on(eventToFire, fn);
return Response; // chain
}
/**
* Response.action A facade for calling functions on both the ready and resize events.
*
* @link http://responsejs.com/#action
* @since 0.1.3
* @param callback|array action is the callback name or array of callback names to call.
*
* @example Response.action(myFunc1); // call myFunc1() on ready/resize
* @example Response.action([myFunc1, myFunc2]); // call myFunc1(), myFunc2() ...
*/
function action(fnOrArr) {
route(fnOrArr, function(fn) {
ready(fn);
resize(fn);
});
return Response; // chain
}
/**
* Response.create() Create their own Response attribute sets, with custom
* breakpoints and data-* names.
* @since 0.1.9
*
* @param object|array args is an options object or an array of options objects.
*
* @link http://responsejs.com/#create
*
* @example Ideally this method is only called once:
* To create a single set, use the form: Response.create(object);
* To create multiple sets, use the form: Response.create([object1, object2]);
*/
function create(args) {
route(args, function(options) {
typeof options == 'object' || doError('create @args');
var elemset = objectCreate(Elemset).configure(options)
, lowestNonZeroBP
, verge = elemset.verge
, breakpoints = elemset.breakpoints
, scrollName = namespaceIt('scroll')
, resizeName = namespaceIt('resize')
;
if ( !breakpoints.length ) { return; } // Quit if there are zero breakpoints.