/
dom.js
1332 lines (1173 loc) · 37 KB
/
dom.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
/**
* @copyright (c) 2017 ActiveState Software Inc.
* @license Mozilla Public License v. 2.0
* @author ActiveState
*/
if (typeof module === 'undefined') module = {}; // debugging helper
/**
* @module ko/dom
* @description this module is meant to be "mostly" backwards compatible with jquery
*/
(function() {
const log = require("ko/logging").getLogger("ko-dom");
//log.setLevel(require("ko/logging").LOG_DEBUG);
if ( ! window)
{
var window = require("ko/windows").getMain();
var document = window.document;
}
/* === MAIN CONSTRUCTION LOGIC === */
/**
* @class Constructor
*
* @description These methods live on the exported function, you can access them like so:
*
* ```require("ko/dom").methodName(..)```
*/
/**
* @constructor module:ko/dom
*
* @param {string} query CSS query to use as the selector
* @param {element} parent The parent element (can be the window)
* @example
* var $ = require("ko/dom");
* $(".foo").text("bar");
*
* @returns {module:ko/dom~QueryObject}
*/
var $ = function(query, parent)
{
if (query instanceof window.ChromeWindow && parent) // Allow for the parent to be bound
{
var _query = parent;
parent = query;
query = _query;
}
parent = parent || window.document;
if (("document" in parent) && parent.constructor.toString().indexOf("Window()") !== -1)
{
parent = parent.document;
}
if ((typeof query) == "object" && ("koDom" in query))
{
return query;
}
else if (/^f/.test(typeof query))
{
if (/c/.test(parent.readyState))
return query();
else
return $(parent).on('DOMContentLoaded', query);
}
else if (/^</.test(query))
{
return new queryObject($.createElement(query));
}
else
return new queryObject(query, parent);
};
/**
* Get a ko/dom instance for the given window
*
* @name window
* @method
* @memberof module:ko/dom~Constructor
*
* @param {Window} w Window reference
*
* @example
* var $ = require("ko/dom").window(myWindow);
* $(".foo").text("bar");
*
* @returns {module:ko/dom} Returns a ko/dom instance for the given window
*/
$.window = (w) =>
{
// Return bound version of $
var bound = $.bind(null, w);
for (let prop in $)
{
if ( ! ($.hasOwnProperty(prop)))
continue;
bound[prop] = $[prop];
}
return bound;
};
/* === HELPER FUNCTIONS === */
/**
* Create element from complex string input
*
* @name createElement
* @method
* @memberof module:ko/dom~Constructor
*
* @param {String} html HTML string, must validate properly (no syntax errors), can also be just the nodename
* @param {Bool|Object} allowMultiple boolean or object, if object then this is taken as an object of attributes to assign to the element
*
* @returns {Node}
*/
$.createElement = function(html, allowMultiple = false)
{
try
{
if (typeof html == "string" && typeof allowMultiple == "object")
{
var attributes = allowMultiple;
var node = document.createElement(html);
for (let k in attributes)
{
if ( ! attributes.hasOwnProperty(k))
{
continue;
}
node.setAttribute(k, attributes[k]);
}
return node;
}
else if (typeof html == "string" && html.match(/^\w+$/))
{
return document.createElement(html);
}
var parsed = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/).exec(html);
if (parsed) {
return document.createElement(parsed[1]);
}
var tmp = document.createElement("div");
tmp.innerHTML = html;
if (allowMultiple)
{
var x = [].slice.call(tmp.childNodes);
return [].slice.call(tmp.childNodes);
}
else
return tmp.firstChild;
}
catch (e)
{
log.exception(e, "Failed injecting HTML: " + html);
return false;
}
}
/**
* Quickly create DOM structure
* Based on: {@link http://gist.github.com/278016}
*
* Example usage:
*
* ```
* $.create('A href=#' , {class: "foo"}, $.create('IMG src="http://bit.ly/WinAylott"')
* ('BR')
* ('' ,"View larger image") )
* ```
*
* @name create
* @method
* @memberof module:ko/dom~Constructor
*
* @param {string} selector The element definition
* @param {object|string|undefined} attributes Attributes to add to the element, if content is undefined and this is a string then the value of attributes will be used as the content param
* @param {string|undefined} content Content to append
*
* @returns {module:ko/dom~Constructor.create} Returns instance of this function, so you can chain calls
*
* @author Thomas Aylott (original author)
* @copyright 2010 Thomas Aylott
* @license MIT
**/
$.create = function (selector, attributes, content, output = '')
{
if (content === undefined && ((typeof attributes == "function") || typeof attributes == 'string'))
{
content = attributes;
attributes = undefined;
}
if (typeof content == "function")
{
content = content.toString();
}
if (attributes)
{
for (let key in attributes)
{
if ( ! attributes.hasOwnProperty(key)) continue;
let value = attributes[key];
if (typeof value == "string") value = $.escape(value)
selector += " " + key + "='"+value+"'";
}
}
output += '<' + selector + '>';
output += ''+ ( content||'' );
output += '</' + selector .split (' ')[0] + '>';
var BS = function(selector, attributes, content) {
return $.create(selector, attributes, content, output);
};
BS.toString = function () { return output; }
BS.finalize = function()
{
return new queryObject($.createElement(output, true /* Allow Multiple */));
}
return BS;
};
/**
* Escape given string (html entities encode)
*
* @name escape
* @method
* @memberof module:ko/dom~Constructor
*
* @param {String} str The input string
*
* @returns {String}
*/
$.escape = function(str)
{
str = str.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
str = str.replace(/'/g,''');
str = str.replace(/"/g,'"');
return str;
}
/**
* Manipulation helper for inserting DOM content
*
* @param {Object} elems Element
* @param {string|object} insert HTML string or object to be inserted
* @param {object} opts {where: prepend|after|before}
*
* @returns {void}
*/
var insertIntoElem = function(elems, insert, opts)
{
opts = opts || {};
if (typeof insert == "object" && insert.koDom)
insert.each(function() { insertIntoElem(elems, this, opts); });
var __insert = false
if (typeof insert == 'string')
__insert = $.createElement(insert);
if ( ! elems.koDom)
elems = $(elems);
return elems.each(function()
{
if (typeof insert == "object" && insert.koDom)
var _insert = insert.element()
else
var _insert = __insert ? __insert.cloneNode(true) : insert;
if (("where" in opts) && opts.where == "prepend" && this.firstChild)
this.insertBefore(_insert, this.firstChild);
else if (("where" in opts) && opts.where == "after")
{
if (this.nextSibling)
this.parentNode.insertBefore(_insert, this.nextSibling);
else
this.parentNode.appendChild(_insert);
}
else if (("where" in opts) && opts.where == "before")
this.parentNode.insertBefore(_insert, this);
else
this.appendChild(_insert);
});
}
/* === FUNCTION CHAIN === */
/**
* @class QueryObject
*/
function queryObject(query, customParent)
{
var parent = window.document;
this._elements = [];
if (query && typeof query == "object" && ! (query instanceof window.ChromeWindow) && query.length)
query = Array.prototype.slice.call(query);
// Use push.apply to force array type
if(Object.prototype.toString.call(query) === '[object Array]')
this._elements = query.slice(0);
else if (query && query.nodeType)
this._elements.push.apply(this._elements, [query]);
else if ('' + query === query)
{
try
{
this._elements.push.apply(this._elements, (customParent || parent).querySelectorAll(query));
}
catch (e)
{
log.exception(e, `Invalid selector: ${query}`);
}
}
else if ((query != null && query === query.window) ||
(query != null && query.window && query == query.window.document))
this._elements.push(query);
this.length = this._elements.length;
}
// set query object prototype
queryObject.prototype = {
// default length
length: 0,
// Identify as special DOM element
koDom: true,
/**
* Add event handler
*
* @memberof module:ko/dom~QueryObject
* @param {Event} event String event type i.e 'click'
* @param {Function} action Function
*
* @returns {this}
*/
on: function(event, action)
{
this.off(event, action); // Prevent duplicate event listeners
return this.each(function()
{
if ( ! ("__koListeners" in this))
this.__koListeners = {};
if ( ! (event in this.__koListeners))
this.__koListeners[event] = [];
this.__koListeners[event].push(action);
this.addEventListener(event, action);
});
},
/**
* Add an event listener which only receives a callback once
* @method
* @memberof module:ko/dom~QueryObject
* @param {Event} event String event type i.e 'click'
* @param {Function} action Callback function
*
* @returns {this}
*/
once: function(event, action)
{
var elems = this;
var listener = () =>
{
try
{
action.apply(this, arguments);
}
catch (e)
{
log.exception(e, "once callback failed");
}
this.off(event, listener);
};
this.on(event, listener);
},
/**
* Remove event listener
* @method
* @memberof module:ko/dom~QueryObject
* @param {Event} event String event type i.e 'click'
* @param {Function} action Callback function
*
* @returns this
*/
off: function(event, action)
{
return this.each(function()
{
if (("__koListeners" in this) && (event in this.__koListeners))
{
this.__koListeners[event].filter(function(value) {
return value != action;
});
}
this.removeEventListener(event, action);
});
},
/**
* Trigger an event
* @method
* @memberof module:ko/dom~QueryObject
* @returns this
*/
trigger: function(type, params)
{
var evt = new window.CustomEvent(type, {
bubbles: true,
cancelable: true,
detail: params
});
return this.each(function()
{
this.dispatchEvent(evt);
});
},
/**
* Iterate over matched elements
* @method
* @memberof module:ko/dom~QueryObject
* @param {Function} action The function to call on each iteration
*
* @returns this
*/
each: function(action)
{
for (var k in this._elements)
{
if ( ! this._elements.hasOwnProperty(k)) continue;
if (action.call(this._elements[k], k) === false) break;
}
return this;
},
/**
* Reverse the element array
* @method
* @memberof module:ko/dom~QueryObject
* @returns this
*/
reverse: function()
{
this._elements.reverse();
return this;
},
/**
* Set text content of elem
* @method
* @memberof module:ko/dom~QueryObject
* @param {string} value The value
*
* @returns this
*/
text: function(value)
{
if (value === undefined)
return this.element().textContent;
return this.each(function()
{
this.textContent = value;
});
},
/**
* Set html content of elem
* @method
* @memberof module:ko/dom~QueryObject
* @param {string|object} value String or queryObject
*
* @returns this
*/
html: function(value)
{
if (value === undefined)
return this.element().innerHTML;
this.each(function()
{
this.innerHTML = value ? value : "";
});
return this;
},
/**
* Get outer html of elem
* @method
* @memberof module:ko/dom~QueryObject
* @returns this
*/
outerHtml: function()
{
return this.element().outerHTML;
},
/**
* Empty the contents of an element
* @method
* @memberof module:ko/dom~QueryObject
* @returns this
*/
empty: function()
{
return this.text("");
},
/**
* Append content to elem
* @method
* @memberof module:ko/dom~QueryObject
* @param {element} elem
*
* @returns this
*/
append: function(elem)
{
insertIntoElem(this, elem);
return this;
},
/**
* Append elem to another element
* @method
* @memberof module:ko/dom~QueryObject
* @param {element} elem
*
* @returns this
*/
appendTo: function(elem)
{
insertIntoElem(elem, this);
return this;
},
/**
* Prepend content to elem
* @method
* @memberof module:ko/dom~QueryObject
* @param {string|object} value String or queryObject
*
* @returns this
*/
prepend: function(elem)
{
insertIntoElem(this, elem, {where: "prepend"});
return this;
},
/**
* Insert content after element
* @method
* @memberof module:ko/dom~QueryObject
* @param {string|object} value String or queryObject
*
* @returns this
*/
after: function(elem)
{
insertIntoElem(this, elem, {where: "after"});
return this;
},
/**
* Insert content before element
* @method
* @memberof module:ko/dom~QueryObject
* @param {string|object} value String or queryObject
*
* @returns this
*/
before: function(elem)
{
insertIntoElem(this, elem, {where: "before"});
return this;
},
/**
* Get the previous sibling for the first element in the selection
* @method
* @memberof module:ko/dom~QueryObject
* @returns {queryObject}
*/
prev: function()
{
var elem = this.element();
return new queryObject(elem ? elem.previousSibling : null);
},
/**
* Get the next sibling for the first element in the selection
* @method
* @memberof module:ko/dom~QueryObject
* @returns {queryObject}
*/
next: function()
{
var elem = this.element();
return new queryObject(elem ? this.element().nextSibling : null);
},
/**
* Replace matched element(s) with ..
* @method
* @memberof module:ko/dom~QueryObject
* @param {Element} elem The element
*
* @returns {Element} returns replaced element
*/
replaceWith: function(elem)
{
if ("koDom" in elem) elem = elem.element();
return this.element().parentNode.replaceChild(elem, this.element());
},
/**
* Clone matched element
* @method
* @memberof module:ko/dom~QueryObject
* @returns {Element} matched element
*/
clone: function(deep = true, events = true)
{
var cloned = [];
this.each(function() {
var el = this;
var result = $(el.cloneNode(deep));
if ("__koListeners" in el && events)
{
for (let event in el.__koListeners)
{
if ( ! el.__koListeners.hasOwnProperty(event)) continue;
el.__koListeners[event].forEach(function(action) {
result.on(event, action);
});
}
}
cloned.push(result.element());
});
return new queryObject(cloned);
},
/**
* Set / get value
* @method
* @memberof module:ko/dom~QueryObject
* @param {String|Void} value The value
*
* @returns this
*/
value: function(value)
{
// Todo: support different value types
var valueKey = 'value';
// Using property
if (valueKey in this.element())
{
if (value === undefined)
return this.element()[valueKey];
return this.each(function()
{
this[valueKey] = value;
});
}
// Using attribute
else
{
if (value === undefined)
return this.attr(valueKey);
return this.attr(valueKey, value);
}
},
/**
* Retrieve parent node
* @method
* @memberof module:ko/dom~QueryObject
* @returns {Element} Parent node
*/
parent: function()
{
return $(this.element().parentNode);
},
/**
* Delete matched elements
* @method
* @memberof module:ko/dom~QueryObject
* @returns this
*/
delete: function()
{
return this.each(function()
{
this.parentNode.removeChild(this);
});
},
/**
* Makes element visible by setting the visibility attribute
* @method
* @memberof module:ko/dom~QueryObject
* @returns this
*/
show: function()
{
return this.each(function()
{
this.style.visibility = "visible";
});
},
/**
* Makes element invisible by setting the visibility attribute
* @method
* @memberof module:ko/dom~QueryObject
* @returns this
*/
hide: function()
{
return this.each(function()
{
this.style.visibility = "collapse";
});
},
fadeIn: function(callback)
{
this.each(function()
{
this.style.opacity = 0;
this.style.visibility = "visible";
});
this.animate( { opacity: 1 },
{
start: {opacity: 0},
duration: 200
},
callback
);
},
fadeOut: function(callback)
{
this.each(function()
{
this.style.opacity = 1;
this.style.visibility = "visible";
});
this.animate( { opacity: 0 },
{
start: {opacity: 1},
duration: 200
},
function()
{
this.hide();
if (callback) callback();
}.bind(this)
);
},
/**
* Check if element is visible
* @method
* @memberof module:ko/dom~QueryObject
* @returns {Boolean}
*/
visible: function()
{
var el = this.element();
var w = el.ownerDocument.defaultView;
if ( ! w) return false;
if ( ! el) return false;
while (el && (el instanceof w.HTMLElement || el instanceof w.XULElement))
{
let v = w.getComputedStyle(el, null).getPropertyValue("visibility");
let d = w.getComputedStyle(el, null).getPropertyValue("display");
if (v == "hidden" || v == "collapse" || d == "none")
return false;
el = el.parentNode;
}
return true;
},
/**
* Checks if element exists
* @method
* @memberof module:ko/dom~QueryObject
* @returns {Boolean}
*/
exists: function()
{
return !! this.element().parentNode;
},
/**
* Checks for given class
* @method
* @memberof module:ko/dom~QueryObject
* @param {String} className The class name
*
* @returns this
*/
hasClass: function(className)
{
return this.element().classList.contains(className);
},
/**
* Adds given class
* @method
* @memberof module:ko/dom~QueryObject
* @param {String} className The class name
*
* @returns this
*/
addClass: function()
{
var args = arguments;
return this.each(function()
{
this.classList.add.apply(this.classList, args);
});
},
/**
* Remove given class
* @method
* @memberof module:ko/dom~QueryObject
* @param {String} className The class name
*
* @returns this
*/
removeClass: function()
{
var args = arguments;
return this.each(function()
{
this.classList.remove.apply(this.classList, args);
});
},
/**
* Set/get CSS value(s)
* @method
* @memberof module:ko/dom~QueryObject
* @param {String|Object} key The CSS property name, or an object with css properties/values
* @param {Mixed|Undefined} value The CSS property value, or undefined if first arg was an object
*
* @returns this
*/
css: function(key, value)
{
var pxRules = ["width", "height", "top", "left", "bottom", "right", "font-size"];
if ((typeof key) == 'string' && value === undefined)
{
value = this.element().style[key];
if (pxRules.indexOf(key) != -1 && value.indexOf("px") == (value.length-2))
value = value.substring(0, value.length-2);
return value;
}
if (pxRules.indexOf(key) != -1 && Number.isInteger(value))
value = value + "px";
var rules = {};
if (value !== undefined)
rules[key] = value;
else
rules = key;
return this.each(function()
{
for (let k in rules)
{
this.style[k] = rules[k];
}
});
},
/**
* Set/get attributes
* @method
* @memberof module:ko/dom~QueryObject
* @param {String|Object} key The attribute key
* @param {Mixed|Undefined} value The attribute value, or empty if you just want to retrieve it
*
* @returns this
*/
attr: function(key, value)
{
if ((typeof key) == 'string' && value === undefined)
{
return this.element().getAttribute(key);
}
var attrs = {};
if (value !== undefined)
attrs[key] = value;
else
attrs = key;
return this.each(function()
{
for (let k in attrs)
{
this.setAttribute(k, attrs[k]);
}
});
},
/**
* Remove Attribute
* @method
* @memberof module:ko/dom~QueryObject
* @param {String} key The attribute key
*
* @returns this
*/
removeAttr: function(key)
{
return this.each(function()
{
this.removeAttribute(key);
});
},
/**
* Get a unique ID for the matched element
* @method
* @memberof module:ko/dom~QueryObject
* @returns {String}
*/
uniqueId: function()
{
var self = this;
this.uniqueId.uuid = this.uniqueId.uuid || 0;
this.each(function()
{
if (this.id) return;
this.id = "_uuid-" + self.uniqueId.uuid++;
});
return this.element().id;