forked from montulli/GrooveScribe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpablo.js
3426 lines (2830 loc) · 119 KB
/
pablo.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
/*!
Pablo <http://pablojs.com>
by Premasagar Rose <http://premasagar.com>,
Dharmafly <http://dharmafly.com>
Repo: <https://github.com/premasagar/pablo>
MIT license
*/
/*jshint newcap:false */
(function(window, Object, Array, Element, SVGElement, HTMLElement, NodeList, Document, HTMLDocument, document, navigator, XMLHttpRequest, DOMParser, XMLSerializer, atob, btoa, escape, unescape, setTimeout, clearTimeout){
'use strict';
var /* SETTINGS */
pabloVersion = '0.5.1',
svgVersion = 1.1,
svgns = 'http://www.w3.org/2000/svg',
head, testElement, arrayProto, matchesProp, userAgent, camelCase;
function make(elementName){
return typeof elementName === 'string' &&
document.createElementNS(svgns, elementName) ||
null;
}
// Browser detection - based on jquery-migrate-1.2.1.js & http://stackoverflow.com/questions/17907445/how-to-detect-ie11
userAgent = (function(){
var ua = navigator.userAgent.toLowerCase(),
match = /((webkit))[ \/]([\w.]+)/.exec(ua) ||
/((o)pera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
/((trident))(?:.*? rv:([\w.]+)|)/.exec(ua) ||
/((ms)ie) ([\w.]+)/.exec(ua) ||
ua.indexOf("compatible") < 0 &&
/((moz)illa)(?:.*? rv:([\w.]+)|)/.exec(ua),
name, prefix, version;
if (match){
name = match[1];
prefix = match[2];
version = match[3];
// IE 10+
if (name === 'trident'){
name = 'msie';
prefix = 'ms';
}
}
return {
name: name || '',
version: version || '0',
prefix: prefix || '',
cssPrefix: prefix ? '-' + prefix + '-' : ''
};
}());
// e.g. 'font-color' -> 'fontColor'
// if `upperFirst === true` -> 'FontColor'
camelCase = (function(){
var uppercaseAfterHyphens = /^-|(?!^)-([a-z])/g,
uppercaseFirstAndHyphens = /(?:^|-)([a-z])/g;
return function (str, upperFirst){
var pattern = upperFirst ?
uppercaseFirstAndHyphens : uppercaseAfterHyphens;
return str.replace(pattern, function(match, letter){
return letter && letter.toUpperCase() || '';
});
};
}());
function findPrefixedProperty(prop, context){
var prefixed;
if (prop in context){
return prop;
}
if (userAgent.prefix){
prefixed = userAgent.prefix + camelCase(prop, true);
if (prefixed in context){
return prefixed;
}
}
}
/////
// TEST ENVIRONMENT CAPABILITY
if (document){
testElement = 'createElementNS' in document && make('svg');
head = document.head || document.getElementsByTagName('head')[0];
arrayProto = Array && Array.prototype;
matchesProp = findPrefixedProperty('matches', testElement) ||
findPrefixedProperty('matchesSelector', testElement);
}
if (!(
testElement && head && arrayProto && matchesProp &&
Element && SVGElement && HTMLElement && NodeList && Document &&
'createSVGRect' in testElement &&
'attributes' in testElement &&
'querySelectorAll' in testElement &&
'previousElementSibling' in testElement &&
'childNodes' in testElement && // see note on svgElement.children, below
'create' in Object &&
'keys' in Object &&
'isArray' in Array &&
'forEach' in arrayProto &&
'map' in arrayProto &&
'some' in arrayProto &&
'every' in arrayProto &&
'filter' in arrayProto &&
'DOMParser' in window &&
'XMLSerializer' in window
)){
// Incompatible environment
// Set `Pablo` to be a simple reference object
window.Pablo = {
version: pabloVersion,
isSupported: false,
userAgent: userAgent
};
// Exit the script
return;
}
// Pablo not supported in this environment. Exit.
////////////////////////////////////////////////////
(function(){
var svgElementNames = 'a altGlyph altGlyphDef altGlyphItem animate animateColor animateMotion animateTransform circle clipPath color-profile cursor defs desc ellipse feBlend feColorMatrix feComponentTransfer feComposite feConvolveMatrix feDiffuseLighting feDisplacementMap feDistantLight feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feImage feMerge feMergeNode feMorphology feOffset fePointLight feSpecularLighting feSpotLight feTile feTurbulence filter font font-face font-face-format font-face-name font-face-src font-face-uri foreignObject g glyph glyphRef hkern image line linearGradient marker mask metadata missing-glyph mpath path pattern polygon polyline radialGradient rect script set stop style svg switch symbol text textPath title tref tspan use view vkern',
xmlns = 'http://www.w3.org/2000/xmlns/',
htmlns = 'http://www.w3.org/1999/xhtml',
xlinkns = 'http://www.w3.org/1999/xlink',
svgMimeType = 'image/svg+xml',
svgDataUrlPrefix = 'data:' + svgMimeType + ';base64,',
cacheExpando = 'pablo-data',
eventsNamespace = '__events__',
support, hyphenate, resolveCssProperty, markupToSvgElement, dataUrlToSvgMarkup,
cache, cacheNextId, Events, isNumeric, cssClassApi, classlistMethod,
pabloCollectionApi;
support = (function(){
function supportsMarkup(){
var el = make('a');
el.setAttributeNS(xlinkns, 'xlink:href', '#');
return (new XMLSerializer())
.serializeToString(el)
.indexOf('xlink') !== -1;
}
var createCanvas = 'getContext' in document.createElement('canvas'),
dataUrl = !!(atob && btoa),
canvas = dataUrl && createCanvas,
imageTypes = ['png', 'jpeg'],
support = {
basic: true,
classList: 'classList' in testElement,
dataUrl: dataUrl,
image: {
svg: dataUrl
},
canvas: canvas,
download: dataUrl && 'createEvent' in document && 'download' in document.createElement('a'),
markup: supportsMarkup()
};
function callbackTrue(callback){
callback(true);
}
function callbackFalse(callback){
callback(false);
}
imageTypes.forEach(function(type){
if (!canvas){
support.image[type] = callbackFalse;
}
else {
support.image[type] = function(callback){
Pablo.line({x2:1}).dataUrl(type, function(dataUrl){
support.image[type] = dataUrl ? callbackTrue : callbackFalse;
callback(!!dataUrl);
});
};
}
});
return support;
}());
/////
// UTILITIES
function extend(target/*, any number of source objects*/){
var len = arguments.length,
withPrototype = arguments[len-1] === true,
i, obj, prop;
if (!target){
target = {};
}
for (i = 1; i < len; i++){
obj = arguments[i];
if (typeof obj === 'object'){
for (prop in obj){
if (withPrototype || obj.hasOwnProperty(prop)){
target[prop] = obj[prop];
}
}
}
}
return target;
}
// Modified from http://code.jquery.com/jquery-2.0.3.js
function isPlainObject(obj){
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if (obj === null || typeof obj !== 'object' || 'nodeType' in obj || obj === window || obj === null){
return false;
}
// Support: Firefox <20
// The try/catch suppresses exceptions thrown when attempting to access
// the "constructor" property of certain host objects, ie. |window.location|
// https://bugzilla.mozilla.org/show_bug.cgi?id=814622
try {
if (!('constructor' in obj) ||
!('prototype' in obj.constructor) ||
!obj.constructor.prototype.hasOwnProperty('isPrototypeOf')){
return false;
}
}
catch(e){
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
}
function toArray(obj){
return arrayProto.slice.call(obj);
}
function isArray(obj){
return Array.isArray(obj);
}
function isArrayLike(obj){
return obj &&
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.length === 'number';
}
function isElement(obj){
return obj instanceof Element;
}
function isElementOrDocument(el){
return isElement(el) || isDocument(el);
}
function isNodeList(obj){
return obj instanceof NodeList;
}
function isDocument(obj){
// Check constructors rather than `obj instanceof Document` for Opera 12.16
return obj && (obj.constructor === Document || obj.constructor === HTMLDocument);
}
function isSVGElement(obj){
return obj instanceof SVGElement;
}
function isHTMLElement(obj){
return obj instanceof HTMLElement;
}
// Check if obj is an element from this or another document
function hasSvgNamespace(obj){
return !!(obj && obj.namespaceURI === svgns);
}
function hasHtmlNamespace(obj){
return !!(obj && obj.namespaceURI === htmlns);
}
function canBeWrapped(obj){
return typeof obj === 'string' ||
isPablo(obj) ||
isElement(obj) ||
isNodeList(obj) ||
isDocument(obj) ||
Array.isArray(obj) ||
isArrayLike(obj) ||
hasSvgNamespace(obj);
// || isPlainObject(obj); to support Events.on() use plain objects
}
// Return node (with attributes) if a Pablo collection, otherwise create one.
function toPablo(node, attr){
if (isPablo(node)){
return attr ? node.attr(attr) : node;
}
return Pablo(node, attr);
}
function getAttributes(el){
var ret = {},
attr, len, i;
if (el){
attr = el.attributes;
for (i = 0, len = attr.length; i<len; i++){
ret[attr[i].name] = attr[i].value;
}
}
return ret;
}
function attributeNS(el, attr){
var colonIndex, ns, name, uri;
// The `xmlns` attribute
if (attr === 'xmlns'){
ns = name = 'xmlns';
}
if (!ns){
// HTML attribute, e.g. `src`
// And for browsers that incorrectly don't output prefixes with markup(),
// e.g. Safari 6.05
if (!hasSvgNamespace(el)){
return false;
}
// Find a colon separating the namespace prefix from the attribute name
colonIndex = attr.indexOf(':');
// A non-prefixed, namespaced attribute, e.g. `fill`
if (colonIndex === -1){
return true;
}
// A prefixed, namespaced attribute, e.g. `xlink:href`
// e.g. ns === 'xlink'
ns = attr.slice(0, colonIndex);
// The un-prefixed name of the attribute, e.g. `href`
name = attr.slice(colonIndex + 1);
}
// Lookup URI in Pablo's `ns` object
uri = Pablo.ns[ns] || null;
return {uri:uri, name:name};
}
function setAttribute(el, attr, value){
var attrNS = attributeNS(el, attr);
// Namespace attributes, e.g. `xmlns` and `xmlns:xlink`
// and namespace prefixed attributes, e.g. `xlink:href`
if (typeof attrNS === 'object'){
// attrNS = {uri, name}
// `uri` is the URI for the namespace of the prefix
// `name` is the un-prefixed attribute name, e.g. 'href'
return el.setAttributeNS(attrNS.uri, attr, value);
}
switch(attrNS){
// A pre-namespaced, prefixed attribute, e.g. `xmlns:xlink`
case false:
return el.setAttribute(attr, value);
// A non-prefixed, namespaced attribute, e.g. `fill`
case true:
return el.setAttributeNS(null, attr, value);
}
}
function getAttribute(el, attr){
var attrNS = attributeNS(el, attr);
switch(attrNS){
case false:
return el.getAttribute(attr);
case true:
return el.getAttributeNS(null, attr);
default:
return el.getAttributeNS(attrNS[0], attrNS[1]);
}
}
function removeAttribute(el, attr){
var attrNS = attributeNS(el, attr);
switch(attrNS){
case false:
return el.removeAttribute(attr);
case true:
return el.removeAttributeNS(null, attr);
default:
return el.removeAttributeNS(attrNS[0], attrNS[1]);
}
}
isNumeric = (function(){
var numberOrSpace = /^-?\d[\.\d\s]*$/;
return function(str){
if (typeof str === 'number'){
return true;
}
return typeof str === 'string' && numberOrSpace.test(str);
};
}());
function numericToNumber(values){
if (typeof values === 'number'){
return values;
}
if (typeof values === 'string'){
return isNumeric(values) ? Number(values) : values;
}
if (Array.isArray(values)){
return values.map(function(value){
return numericToNumber(value);
});
}
return values;
}
// e.g. 'fontColor' -> 'font-color'
// NOTE: does not check for blank spaces within multiple words, e.g. 'font Color'.
// To achieve that, use `capitalLetters = /\s*[A-Z]/g` and `letter.trim().toLowerCase()`
hyphenate = (function(){
var capitalLetters = /(^|.)([A-Z])/g;
function convertCapitalLetter(match, preceding, letter){
return (preceding ? preceding + '-' : '') +
letter.toLowerCase();
}
return function(str, leadingHyphen){
return (leadingHyphen ? '-' : '') +
str.replace(capitalLetters, convertCapitalLetter);
};
}());
resolveCssProperty = (function(){
var styleDictionary = {},
hyphenatedDictionary = {},
elements = [make('svg'), document.createElement('a')];
elements.forEach(function(el){
var style = el.style,
prop;
for (prop in style){
if (!(prop in styleDictionary) && typeof style[prop] !== 'function'){
styleDictionary[prop] = prop;
}
}
});
// e.g. convert 'transition' => 'webkitTransition'
// e.g. if `hyphenateResult === true` => '-webkit-transition'
return function(prop, hyphenateResult){
var resolvedProp = hyphenateResult ?
hyphenatedDictionary[prop] : styleDictionary[prop],
testProp, isPrefixed;
if (resolvedProp){
return resolvedProp;
}
if (hyphenateResult){
resolvedProp = styleDictionary[prop];
}
if (!resolvedProp){
testProp = camelCase(prop);
resolvedProp = styleDictionary[testProp];
}
if (!resolvedProp && userAgent.prefix){
testProp = userAgent.prefix + camelCase(testProp, true);
resolvedProp = styleDictionary[testProp];
if (!resolvedProp){
testProp = camelCase(testProp, true);
resolvedProp = styleDictionary[testProp];
}
}
if (resolvedProp){
styleDictionary[prop] = resolvedProp;
if (hyphenateResult){
isPrefixed = resolvedProp.toLowerCase().indexOf(userAgent.prefix) === 0;
resolvedProp = hyphenate(resolvedProp, isPrefixed);
hyphenatedDictionary[prop] = resolvedProp;
}
}
return resolvedProp;
};
}());
markupToSvgElement = (function(){
var parser, prefix, suffix;
return function markupToSvgElement(markup){
var svgdoc, target;
if (!parser){
parser = new DOMParser();
suffix = '</svg>';
// Add a <g> to a <svg> to ensure the <svg> is not self-closing
prefix = Pablo.svg().append(Pablo.g()).markup().replace(/<g.*/, '');
}
markup = prefix + markup + suffix;
// not supported in IE9: mime type 'image/svg+xml'
svgdoc = parser.parseFromString(markup, 'application/xml');
target = Pablo(svgdoc.documentElement.childNodes);
return target.detach();
};
}());
dataUrlToSvgMarkup = support.dataUrl ?
function(dataUrl){
var data = dataUrl.slice(svgDataUrlPrefix.length);
// See https://developer.mozilla.org/en-US/docs/Web/API/window.btoa#Unicode_Strings for use of decodeURIComponent and escape
return decodeURIComponent(escape(atob(data)));
} :
function(){
return '';
};
// Data cache
cache = {};
cacheNextId = 1;
/////
// PABLO COLLECTIONS
function PabloCollection(node, attr){
if (node){
// Create a named element, e.g. Pablo('circle', {})
// Check that this isn't Pablo('<circle/>', {})
if (typeof node === 'string' && attr && node.indexOf('<') === -1){
node = make(node);
}
// Add the results to the collection
this.add(node);
// Apply attributes
if (attr){
this.attr(attr);
}
}
}
pabloCollectionApi = PabloCollection.prototype = Object.create(arrayProto);
extend(pabloCollectionApi, {
pablo: pabloVersion,
collection: null,
/////
// ARRAY-LIKE BEHAVIOUR
toArray: function(){
return toArray(this);
},
size: function(){
return this.length;
},
get: function(index){
return this[index];
},
eq: function(index){
return index !== -1 ?
// Return zero-indexed node
Pablo(this[index]) :
// Return node, counting backwards from end of elements array
(index < -1 ? this.slice(index, index + 1) : this.slice(index));
},
first: function(){
return this.eq(0);
},
last: function(){
return this.eq(this.length-1);
},
add: (function(){
// Detect `<` as the first non-whitespace character
var openTag = /^\s*</;
return function (/*node, node,..., prepend*/){
var nodes = arguments,
numNodes = nodes.length,
prepend = false,
node, toAdd, nodeInArray, i;
// `prepend`
if (numNodes > 1 && typeof nodes[numNodes-1] === 'boolean'){
prepend = nodes[numNodes-1];
numNodes -= 1;
if (prepend){
nodes = arrayProto.slice.call(nodes, 0, numNodes).reverse();
}
}
for (i=0; i<numNodes; i++){
node = nodes[i];
// An SVG or HTML element, or document
if (isElement(node) || isDocument(node) || hasSvgNamespace(node)){
// Add element, if it is not already in the collection
if (arrayProto.indexOf.call(this, node) === -1){
arrayProto[prepend ? 'unshift' : 'push'].call(this, node);
}
}
// A Pablo collection
else if (isPablo(node)){
// See extensions/functional.js for example usage of node.collection
// TODO: remove support for functional.js?
node = toArray(node.collection || node);
toAdd = node.collection || node;
}
// A string outside of an array - either CSS selector,
// SVG markup or dataUrl
else if (typeof node === 'string'){
// SVG markup
// Detect `<` as the first non-whitespace character
// Check indexOf() first, for performance
if (node.indexOf('<') !== -1 && openTag.test(node)){
toAdd = markupToSvgElement(node);
}
// Data URL
else if (node.indexOf(svgDataUrlPrefix) === 0){
toAdd = markupToSvgElement(dataUrlToSvgMarkup(node));
}
// CSS selector
else {
toAdd = document.querySelectorAll(node);
}
}
// A nodeList (e.g. result of a selector query, or childNodes)
// or is an object like an array, e.g. a jQuery collection
else if (isNodeList(node) || isArrayLike(node)){
toAdd = node;
}
// `node` is an array or collection
if (toAdd || Array.isArray(node)){
// Convert to an array of nodes
if (toAdd){
node = toArray(toAdd);
}
while (node.length){
// Whether prepending or appending, always process arrays and
// array-like collections in forwards order
nodeInArray = prepend ? node.pop() : node.shift();
// A string inside an array is converted to an element
if (typeof nodeInArray === 'string'){
nodeInArray = make(nodeInArray);
}
// Add to collection
this.add(nodeInArray, prepend);
}
toAdd = null;
}
}
return this;
};
}()),
concat: function(){
return this.add.apply(Pablo(this), arguments);
},
// Add new node(s) to the collection; accepts arrays or nodeLists
unshift: function(){
var args = toArray(arguments);
args.push(true);
return this.add.apply(this, args);
},
// Remove node from end of the collection
pop: function(){
return Pablo(arrayProto.pop.call(this));
},
shift: function(){
return Pablo(arrayProto.shift.call(this));
},
slice: function(begin, end){
return Pablo(arrayProto.slice.call(this, begin, end));
},
splice: function(){
arrayProto.splice.apply(this, arguments);
return this;
},
join: function(separator){
return this.toArray().map(function(el){
return Pablo(el).toString();
}).join(separator);
},
reverse: function(){
arrayProto.reverse.call(this);
return this;
},
sort: function(fn){
arrayProto.sort.call(this, fn);
return this;
},
each: function(fn, context){
if (this.length){
if (this.length === 1){
fn.call(context || this, this[0], 0);
}
else {
arrayProto.forEach.call(this, fn, context || this);
}
}
return this;
},
map: function(fn, context){
return Pablo(arrayProto.map.call(this, fn, context || this));
},
/////
// TRAVERSAL
// See below for traversal shortcuts that use `traverse()` e.g. `parents()`
traverse: function(prop, doWhile, selectors){
var collection = Pablo(),
isFn = typeof doWhile === 'function';
this.each(function(el, i){
el = el[prop];
while (el && (isFn ? doWhile.call(this, el, i) : true)){
collection.add(el);
el = doWhile ? el[prop] : false;
}
});
return selectors ? collection.select(selectors) : collection;
},
/////
// MANIPULATION
detach: function(){
return this.each(function(el){
var parentNode = el.parentNode;
if (parentNode){
parentNode.removeChild(el);
}
});
},
remove: function(){
// If the cache has any contents
if (Object.keys(cache).length){
// Remove data for all elements and their descendents
this.off().removeData();
this.find('*').off().removeData();
}
// Remove from the DOM
return this.detach();
},
empty: function(){
// If the cache has any contents
if (Object.keys(cache).length){
// Remove data for each descendent of elements in the collection
this.find('*').off().removeData();
}
// Remove elements, text and other nodes
// This uses native DOM methods, rather than `detach()`, to ensure that
// non-element nodes are also removed.
return this.each(function(el){
while (el.firstChild){
el.removeChild(el.firstChild);
}
});
},
/* Arguments:
`deepDom`: clones descendent DOM elements and DOM event listeners (default true)
`withData` clones data associated with the element (default false)
`deepData` clones data associated with descendents of the element (defaults to same as `withData`)
*/
clone: function(deepDom, withData, deepData){
var isSingle = this.length === 1;
if (typeof deepDom !== 'boolean'){
deepDom = true;
}
if (typeof withData !== 'boolean'){
withData = false;
}
if (typeof deepData !== 'boolean'){
deepData = withData;
}
return this.map(function(el){
var cloned = el.cloneNode(deepDom),
data, node, clonedNode, dataset;
// Clone data associated with the element
if (withData){
// Avoid unnecessary Pablo collection creation
node = isSingle ? this : Pablo(el);
data = node.cloneData();
if (data){
// Set data on the cloned element
clonedNode = Pablo(cloned).data(data);
}
}
// Clone descendents' data
if (deepDom && deepData){
if (!clonedNode){
clonedNode = Pablo(cloned);
}
dataset = node.pluck('data');
clonedNode.find('*').data(dataset);
}
return cloned;
});
},
// `deep` is whether to duplicate child nodes
// `deepData` is whether to duplicate data on self and children
// TODO: should there be a way of duplicating without adding to the DOM
// i.e. to remove the call to `after()` or to return a new collection
duplicate: function(repeats, withData, deepData){
var duplicates;
if (repeats !== 0){
if (typeof repeats !== 'number' || repeats < 0){
repeats = 1;
}
// For performance, before cloning data, ensure that the elements
// or their descendents have data associated with them
if (withData){
withData = this.hasData();
}
if (deepData){
deepData = this.find('*').hasData();
}
duplicates = Pablo();
// Clone the collection
while (repeats --){
duplicates.add(this.clone(true, withData, deepData));
}
// Insert in the DOM after the collection
this.after(duplicates)
// Add new elements the collection
.add(duplicates);
}
return this;
},
getValue: function(value, i){
if (Array.isArray(value)){
// If array is shorter than collection, then cycle back to start
// of array
i = i % value.length;
value = value[i];
}
else if (typeof value === 'function'){
value = value.call(this, this[i], i);
}
return value;
},
attr: function(attr, value){
var el, attributes;
// Return an object of all attributes on the first element in
// the collection
if (typeof attr === 'undefined'){
return getAttributes(this[0]);
}
// Handle a named attribute
if (typeof attr === 'string'){
// Get the attribute from the first element in the collection
if (typeof value === 'undefined'){
el = this[0];
return el && getAttribute(el, attr);
}
// Set the attribute
// Return, if no elements
if (!this.length){
return this;
}
// Set the attribute, if the collection only has one element
if (this.length === 1){
if (value === null){
this.removeAttr(attr);
}
else {
setAttribute(this[0], attr, this.getValue(value, 0));
}
return this;
}
attributes = {};
attributes[attr] = value;
}
else {
attributes = attr;
}
return this.each(function(el, i){
var attr, value;
for (attr in attributes){
if (attributes.hasOwnProperty(attr)){
value = attributes[attr];