This repository has been archived by the owner on Jan 15, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
nwt.js
1717 lines (1348 loc) · 34.2 KB
/
nwt.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(z,y){
/**
* NWT primary entry point
* @constructor
*/
function NWT() {
};
NWT.prototype = {
/**
* Implements an interface on an object
*/
implement: function(implClass, modClass) {
var impls = {
DelayableQueue : [
/**
* Returns a queueable interface to the original object
* This allows us to insert delays between chainable method calls using the .wait() method
* Currently this is only implemented for the node class, but it should be possible to use this with any object.
*/
'wait', function () {
/**
* Queueable object which implements methods from another interface
* @param object Context for the callback
*/
function QueueableObject(context) {
this.queue = [];
this.context = context;
this.inWork = false;
}
QueueableObject.prototype = {
_add: function(func, args) {
var self = this;
self.queue.push({type: 'chain', func: func, args: args});
if (!self.inWork) {
return self._process();
}
},
/**
* Process the queue
* Shifts an item off the queue and waits for it to finish
*/
_process: function() {
var self = this, item;
self.inWork = true;
if (!self.queue.length) {
return;
}
item = self.queue.shift();
if (item.type == 'wait') {
setTimeout(function(){
self._process();
}, item.duration*1000);
} else {
self.context = item.func.apply(self.context, item.args);
self._process();
}
return self;
},
/**
* Updates the current delay timer
*/
wait: function(duration) {
this.queue.push({type: 'wait', duration: duration});
return this;
}
};
return function (duration) {
var self = this,
mockObj = new QueueableObject(self);
/**
* Returns an executable function
* uses setTimeout and the total queueTimer
*/
getQueuedFunction = function(func) {
return function() {
mockObj._add(func, arguments);
return mockObj;
}
};
/**
* Wrap all class functions
* We can unwrap at the end if the current wait is 0
*/
for( var i in self ) {
if (typeof self[i] != 'function' || i == 'wait' ) { continue; }
mockObj[i] = getQueuedFunction(self[i]);
}
mockObj.wait(duration);
return mockObj;
}
}
]
};
modClass[impls[implClass][0]] = impls[implClass][1]();
},
/**
* Declares a class on the n.* namespace
* This allows us to play with the prototype and do other things later
*/
declare: function(name, clazz) {
localnwt._lib = localnwt._lib || {}
localnwt._lib[name] = clazz
},
/**
* Augments a class namespaced on n._lib
*/
augment: function(name, fnName, fn) {
localnwt._lib[name].prototype[fnName] = fn;
},
/**
* Generates a unique id
*/
uuid: function() {
var counter = 0;
return function(){
counter++;
return counter.toString(16)
}
}()
};
// localnwt variable used for minification.
// We should reference localnwt wherever needed inside of our source scripts.
var localnwt = new NWT()
// Window namespaces
z.nwt = z.n = localnwt
/**
* Wraps an XHR response object
* This allows us to parse on demand with o.obj()
* The toString method will also spit out the flat response
* @param object XHR request
*/
function NWTIOResponse (request) {
this.request = request;
try {
this.obj = JSON.parse(request.responseText);
} catch(e) {}
}
NWTIOResponse.prototype = {
/**
* Returns the non-parse responseText
*/
toString: function () {
return this.request.responseText;
}
};
/**
* Provides ajax communication methods
* The folllowing methods are chainable
* success - success handler
* failure - failure handler
* serialize - serialize a form, selector, array, or object to send
* @constructor
*/
function NWTIO(args) {
this.req = new XMLHttpRequest();
this.config = {};
this.url = args[0];
// Data to send as
this.ioData = '';
var chainableSetters = ['success', 'failure', 'serialize'],
i,
setter,
mythis = this,
// Returns the setter function
getSetter = function (setter) {
return function (value) {
mythis.config[setter] = value;
return this;
}
};
for (i = 0, setter; setter = chainableSetters[i]; i++) {
this[setter] = getSetter(setter);
}
}
NWTIO.prototype = {
/**
* Runs the IO call
* @param string Type of call
*/
_run: function() {
var mythis = this;
this.req.onload = function() {
if (mythis.config.success) {
var response = new NWTIOResponse(mythis.req);
mythis.config.success(response);
}
};
this.req.onerror = function() {
if (mythis.config.failure) {
var response = new NWTIOResponse(mythis.req);
mythis.config.failure(response);
}
};
this.req.send(this.ioData ? this.ioData : null);
return this;
},
/**
* Runs IO POST
* We also use post for PUT or DELETE requests
*/
post: function(data, method) {
var urlencodedForm = true;
if (typeof data == 'string') {
this.ioData = data;
} else if (typeof data == 'object' && data._node) {
if (data.getAttribute('enctype')) {
urlencodedForm = false;
}
this.ioData = new FormData(data._node);
}
var req = this.req,
method = method || 'POST';
req.open(method, this.url);
//Send the proper header information along with the request
// Send as form encoded if we do not have a file field
if (urlencodedForm) {
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
return this._run();
},
/**
* Runs IO GET
* @param string We update the URL if we receive data to GET here
*/
get: function(data) {
// Strip out the old query string and append the new one
if (data) {
this.url = this.url.split('?', 1)[0] + '?' + data;
}
this.req.open('GET', this.url);
return this._run();
},
/**
* Runs IO PUT
*/
put: function(data) {
return this.post('?' + data, 'PUT');
},
/**
* Runs IO DELETE
*/
'delete': function(data) {
return this.post('?' + data, 'DELETE');
},
/**
* Aborts this request
*/
abort: function() {
this.req.abort();
return this;
}
};
localnwt.io = function() {
return new NWTIO(arguments);
};
var fxObj = {
// <id> : { ..obj mapping.. }
}
/**
* Individually wrapped NWTNode
* @constructor
*/
function NWTNodeInstance(node) {
localnwt.implement('DelayableQueue', this);
this._node = node;
}
n.declare('Node', NWTNodeInstance);
NWTNodeInstance.prototype = {
/**
* Gets the region of a node (top, left, bottom, right)
*/
region: function() {
var region = {
width: this.get('offsetWidth'),
height: this.get('offsetHeight')
},
box = this._node.getBoundingClientRect(),
doc = y,
docElem = doc.documentElement,
body = doc.body,
win = z,
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || docElem.scrollLeft || body.scrollLeft;
region.top = box.top + scrollTop - clientTop,
region.left = box.left + scrollLeft - clientLeft;
region.bottom = region.top + region.height;
region.right = region.left + region.width;
return region;
},
/**
* Checks if a given node intersects another
* @param object Node to check against
*/
intersects: function(other) {
var me = this.region(),
you = other.region();
return !(
me.left > you.right ||
me.right < you.left ||
me.top > you.bottom ||
me.bottom < you.top ||
you.left > me.right ||
you.right < me.left ||
you.top > me.bottom ||
you.bottom < me.top
);
},
/**
* Returns the ancestor that matches the css selector
* @param string CSS Selector
*/
ancestor: function(selector) {
var allMatches = localnwt.all(selector),
testNode = this._node,
ancestor = null,
maxDepth = 0;
if( allMatches.size() == 0 ) {
return null;
}
while( true ) {
// Iterate through all matches for each parent, and exit as soon as we have a match
// Pretty bad performance, but super small. TODO: Omtimize
allMatches.each(function (el) {
if (el._node == testNode) {
ancestor = el;
}
});
var parentNode = testNode.parentNode;
if( ancestor || !parentNode) { break; }
testNode = parentNode;
}
if( ancestor ) {
return ancestor;
} else {
return null;
}
},
parent: function() {
var parent = new NWTNodeInstance(this._node.parentNode);
return parent;
},
/**
* Returns true if the class exists on the node, false if not
*/
hasClass: function(className) {
return this._node.classList.contains(className);
},
/**
* Adds a class to the node
*/
addClass: function(className) {
this._node.classList.add(className);
return this;
},
/**
* Removes a class from the node.
*/
removeClass: function(className) {
return this.swapClass(className, '');
},
/**
* Replaces a class on a node
* @param string oldClass Old class name
* @param string newClass New class name
*/
swapClass: function(oldClass, newClass) {
this._node.className = this._node.className.replace(oldClass, newClass);
return this;
},
/**
* Gets a data attribute from the node
* Pass just whatever comes after data-
* If the attribute were data-user-id,
* you should pass 'user-id' to this function
* @param string Data attribute to get
*/
data: function(property) {
return this._node.getAttribute('data-' + property);
},
/**
* Sets a data attribute from the node
* @param string Data attribute to get
* @param mixed Value to set
*/
setData: function(property, val) {
return this._node.setAttribute('data-' + property, val);
},
/**
* Gets a property from the node object
* @param string Attribute to get
*/
get: function(property) {
if( property === 'parentNode' ) {
var node = this._node[property];
if( !node ) { return null; }
return new NWTNodeInstance(node);
}
return this._node[property];
},
/**
* Sets an attribute on the node
* @param string Attribute to set
* @param string Value to set
*/
set: function(property, value) {
this._node[property] = value;
return this;
},
/**
* Gets an attribute from the DOM node
* @param string Attribute to get
*/
getAttribute: function(property) {
return this._node.getAttribute(property);
},
/**
* Pass-thru to node.hasAttribute
* @param string Attribute to test for
*/
hasAttribute: function(property) {
return this._node.hasAttribute(property);
},
/**
* Sets an attribute on the DOM node
* @param string Attribute to set
*/
setAttribute: function(property, value) {
this._node.setAttribute(property, value);
return this;
},
/**
* Resolves JS Styles
*/
_jsStyle: function (name) {
var lookupMap = {float: 'cssFloat'};
if (lookupMap[name]) name = lookupMap[name];
return name;
},
/**
* Gets a style attribute set on the node
* @param string Style attribute to get
*/
getStyle: function(property) {
if( !this.getAttribute('style') ) {
return '';
}
property = this._jsStyle(property);
var matchedStyle = this._node.style[property];
if( matchedStyle ) {
return matchedStyle;
} else {
return null;
}
},
/**
* Removes a style attribute
* @param string Style attribute to remove
*/
removeStyle: function(property) {
return this.removeStyles(property);
},
/**
* Removes an array of styles from a node
* @param array Array of styles to remove
*/
removeStyles: function(props) {
// Default properties to an array
if (typeof props == 'string') {
props = [props];
}
var i,
propsLen = props.length;
for (i = 0; i < propsLen; i += 1) {
this._node.style[props[i]] = '';
}
return this;
},
/**
* Sets a style attribute
* @param string Style attribute to set
* @param string Value to set
*/
setStyle: function(property, value) {
var newStyle = {};
newStyle[property] = value;
return this.setStyles(newStyle);
},
/**
* Sets multiple styles
* @param object Object map of styles to set
*/
setStyles: function(newStyles) {
if( !this.getAttribute('style') ) {
this.setAttribute('style', '');
}
var newStyle = '',
// If the style matches one of the following, and we pass in an integer, default the unit
// E.g., 10 becomes 10px
defaultToUnit = {
top: 'px',
left: 'px',
width: 'px',
height: 'px'
},
i,
eachStyleValue,
// Keep track of an array of styles that we need to remove
newStyleKeys = [];
for( i in newStyles ) {
var styleKey = this._jsStyle(i),
eachStyleVal = newStyles[i];
// Default the unit if necessary
if (defaultToUnit[styleKey] && !isNaN(eachStyleVal)) {
eachStyleVal += defaultToUnit[styleKey];
}
this._node.style[styleKey] = eachStyleVal;
}
return this;
},
/**
* Serializes sub children of the current node into post data
*/
serialize: function() {
var retVal = '',
// Getting ALL elements inside of form element
els = this._node.getElementsByTagName('*');
// Looping through all elements inside of form and checking to see if they're "form elements"
for( var i = 0, el; el = els[i]; i++ ) {
if( !el.disabled && el.name && el.name.length > 0 ) {
switch(el.tagName.toLowerCase()) {
case 'input':
switch( el.type ) {
// Note we SKIP Buttons and Submits since there are no reasons as to why we
// should submit those anyway
case 'checkbox':
case 'radio':
if( el.checked ) {
if( retVal.length > 0 ) {
retVal += '&';
}
retVal += el.name + '=' + encodeURIComponent(el.value);
}
break;
case 'hidden':
case 'password':
case 'text':
if( retVal.length > 0 ) {
retVal += '&';
}
retVal += el.name + '=' + encodeURIComponent(el.value);
break;
}
break;
case 'select':
case 'textarea':
if( retVal.length > 0 ) {
retVal += '&';
}
retVal += el.name + '=' + encodeURIComponent(el.value);
break;
}
}
}
return retVal;
},
/**
* Gets the html of the node
*/
getHtml: function() {
return this._node.innerHTML;
},
/**
* Sets the html of the node
* @param string Html to set
*/
setHtml: function(html) {
var self = this,
processScripts,
scriptTags;
self._node.innerHTML = html;
// Re-append any script tags introduced
// We need to synchronously process them
scriptTags = self.all('script');
processScripts = function() {
var rawEl = scriptTags.nodes.shift();
if (!rawEl || !rawEl._node) {
return;
}
// If there is script html, eval it instead of appending it
var scriptSrc = rawEl.getAttribute('src');
if (scriptSrc) {
var newScript = y.createElement('script'),
done;
newScript.type = "text/javascript";
newScript.src = scriptSrc;
newScript.onload = newScript.onreadystatechange = function() {
if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
processScripts();
}
};
self._node.appendChild(newScript);
} else if (rawEl.get('text')){
var evalRef = eval
evalRef(rawEl.get('text'));
processScripts();
}
}
try {
processScripts();
}catch(e){}
return this;
},
/**
* Passthrough to node.get('val')
*/
val: function() {
return this.get('value');
},
/**
* Finds a node based on direction
* @param string Native method to iterate nodes {previous | next}
* @param string criteria CSS selector or Filtering function
*/
_find: function(method, criteria) {
// Iterate on the raw node
var node = this._node,
// Method to iterate on
siblingType = method + 'Sibling',
// Filter to test the node
filter,
validItems;
// CSS Selector case
if (typeof criteria == "string") {
validItems = n.all(criteria);
filter = function(rawNode) {
var found = false;
validItems.each(function(el){
if (rawNode == el._node) {
found = true;
}
});
return found;
};
// Default the filter to return true
} else if (!criteria) {
filter = function(){ return true }
} else {
filter = function(rawEl) {
return criteria(new NWTNodeInstance(rawEl));
}
}
while(node) {
node = node[siblingType];
if (node && node.nodeType == 1 && filter(node)) {
break;
}
}
return node ? new NWTNodeInstance(node) : null;
},
/**
* Returns the next node
*/
next: function(filter) {
return this._find('next', filter)
},
/**
* Returns the previous node
*/
previous: function(filter) {
return this._find('previous', filter)
},
/**
* Returns a child node instance based on a selector
* Implements querySelector
* @param string css selector
*/
one: function(selector) {
var node = this._node.querySelector(selector);
return new NWTNodeInstance(node);
},
/**
* Returns a child nodelist based on a selector
* Implements querySelector
* @param string CSS Selector
*/
all: function(selector) {
var nodelist = this._node.querySelectorAll(selector);
return new NWTNodeList(nodelist);
},
/**
* Appends a node instance to this node
*/
append: function(node) {
if( node instanceof NWTNodeInstance ) {
node = node._node;
}
this._node.appendChild(node);
return this;
},
/**
* Appends the current node to another node
* @param {string|object} Either a CSS selector, or node instance
* @return object The node that we appended the current node to
*/
appendTo: function(node) {
var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node);
newParent.append(this);
return this;
},
/**
* Prepends a node to the beginning of the children of this node
*/
prepend: function(node) {
if( node instanceof NWTNodeInstance ) {
node = node._node;
}
var child = this.one('*');
this._node.insertBefore(node, (child._node? child._node : null));
return this;
},
/**
* Inserts the current node into another node
* @param {string|object} Either a CSS selector, or node instance
* @param string Position to insert at. Defaults to 'before'
* @return object The node that we inserted the current node into
*/
insertTo: function(node, position) {
var newParent = ( node instanceof NWTNodeInstance ) ? node : localnwt.one(node);
newParent.insert(this, position);
return this;
},
/**
* Removes a node instance from the dom
*/
remove: function() {
this._node.parentNode.removeChild(this._node);
},
/**
* Inserts a given node into this node at the proper position
*/
insert: function(node, position) {
position = position || 'before';
if( position == 'before' ) {
this._node.parentNode.insertBefore(node._node, this._node);
} else if ( position == 'after' ) {
this._node.parentNode.insertBefore(node._node, this.next() ? this.next()._node : null);
}
},
/**
* Simulates a click event on a node
*/
click: function() {
var evt = y.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, z,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
return !this._node.dispatchEvent(evt);
},
// Begin NWT Event hooks
/**
* Stub out the Node addEventListener/removeEventListener interfaces
*/
addEventListener: function(ev, fn) {
return this._node.addEventListener(ev, fn, false);
},
removeEventListener: function(ev, fn) {
return this._node.removeEventListener(ev, fn, false);
},
/**
* Implement a node API to for event listeners
* @see NWTEvent::on
*/
on: function(event, fn, selector, context) {
return localnwt.event.on(this, event, fn, selector,context);
},
/**
* Implement a node API to for event listeners
* @see NWTEvent::once
*/
once: function(event, fn, selector, context) {
return localnwt.event.on(this, event, fn, selector, context, true);
},
/**
* Implement a node API to for event listeners
* @see NWTEvent::off
*/
off: function(event, fn) {