-
Notifications
You must be signed in to change notification settings - Fork 0
/
editor.js
2778 lines (2297 loc) · 79.4 KB
/
editor.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
// Umbrella JS http://umbrellajs.com/
// -----------
// Small, lightweight jQuery alternative
// @author Francisco Presencia Fandos http://francisco.io/
// @inspiration http://youmightnotneedjquery.com/
// Initialize the library
var u = function (parameter, context) {
// Make it an instance of u() to avoid needing 'new' as in 'new u()' and just
// use 'u().bla();'.
// @reference http://stackoverflow.com/q/24019863
// @reference http://stackoverflow.com/q/8875878
if (!(this instanceof u)) {
return new u(parameter, context);
}
// No need to further processing it if it's already an instance
if (parameter instanceof u) {
return parameter;
}
// Parse it as a CSS selector if it's a string
if (typeof parameter === 'string') {
parameter = this.select(parameter, context);
}
// If we're referring a specific node as in on('click', function(){ u(this) })
// or the select() function returned a single node such as in '#id'
if (parameter && parameter.nodeName) {
parameter = [parameter];
}
// Convert to an array, since there are many 'array-like' stuff in js-land
this.nodes = this.slice(parameter);
};
// Map u(...).length to u(...).nodes.length
u.prototype = {
get length () {
return this.nodes.length;
}
};
// This made the code faster, read "Initializing instance variables" in
// https://developers.google.com/speed/articles/optimizing-javascript
u.prototype.nodes = [];
// Add class(es) to the matched nodes
u.prototype.addClass = function () {
return this.eacharg(arguments, function (el, name) {
el.classList.add(name);
});
};
// [INTERNAL USE ONLY]
// Add text in the specified position. It is used by other functions
u.prototype.adjacent = function (html, data, callback) {
if (typeof data === 'number') {
if (data === 0) {
data = [];
} else {
data = new Array(data).join().split(',').map(Number.call, Number);
}
}
// Loop through all the nodes. It cannot reuse the eacharg() since the data
// we want to do it once even if there's no "data" and we accept a selector
return this.each(function (node, j) {
var fragment = document.createDocumentFragment();
// Allow for data to be falsy and still loop once
u(data || {}).map(function (el, i) {
// Allow for callbacks that accept some data
var part = (typeof html === 'function') ? html.call(this, el, i, node, j) : html;
if (typeof part === 'string') {
return this.generate(part);
}
return u(part);
}).each(function (n) {
this.isInPage(n)
? fragment.appendChild(u(n).clone().first())
: fragment.appendChild(n);
});
callback.call(this, node, fragment);
});
};
// Add some html as a sibling after each of the matched elements.
u.prototype.after = function (html, data) {
return this.adjacent(html, data, function (node, fragment) {
node.parentNode.insertBefore(fragment, node.nextSibling);
});
};
// Create a HTTP request for whenever the matched form submits
u.prototype.ajax = function (done, before) {
return this.handle('submit', function (e) {
ajax(
u(this).attr('action'),
{ body: u(this).serialize(), method: u(this).attr('method') },
done && done.bind(this),
before && before.bind(this)
);
});
};
// Add some html as a child at the end of each of the matched elements.
u.prototype.append = function (html, data) {
return this.adjacent(html, data, function (node, fragment) {
node.appendChild(fragment);
});
};
// [INTERNAL USE ONLY]
// Normalize the arguments to an array of strings
// Allow for several class names like "a b, c" and several parameters
u.prototype.args = function (args, node, i) {
if (typeof args === 'function') {
args = args(node, i);
}
// First flatten it all to a string http://stackoverflow.com/q/22920305
// If we try to slice a string bad things happen: ['n', 'a', 'm', 'e']
if (typeof args !== 'string') {
args = this.slice(args).map(this.str(node, i));
}
// Then convert that string to an array of not-null strings
return args.toString().split(/[\s,]+/).filter(function (e) {
return e.length;
});
};
// Merge all of the nodes that the callback return into a simple array
u.prototype.array = function (callback) {
callback = callback;
var self = this;
return this.nodes.reduce(function (list, node, i) {
var val;
if (callback) {
val = callback.call(self, node, i);
if (!val) val = false;
if (typeof val === 'string') val = u(val);
if (val instanceof u) val = val.nodes;
} else {
val = node.innerHTML;
}
return list.concat(val !== false ? val : []);
}, []);
};
// Handle attributes for the matched elements
u.prototype.attr = function (name, value, data) {
data = data ? 'data-' : '';
if (value !== undefined) {
var nm = name;
name = {};
name[nm] = value;
}
if (typeof name === 'object') {
return this.each(function (node) {
for (var key in name) {
node.setAttribute(data + key, name[key]);
}
});
}
return this.length ? this.first().getAttribute(data + name) : '';
};
// Add some html before each of the matched elements.
u.prototype.before = function (html, data) {
return this.adjacent(html, data, function (node, fragment) {
node.parentNode.insertBefore(fragment, node);
});
};
// Get the direct children of all of the nodes with an optional filter
u.prototype.children = function (selector) {
return this.map(function (node) {
return this.slice(node.children);
}).filter(selector);
};
/**
* Deep clone a DOM node and its descendants.
* @return {[Object]} Returns an Umbrella.js instance.
*/
u.prototype.clone = function () {
return this.map(function (node, i) {
var clone = node.cloneNode(true);
var dest = this.getAll(clone);
this.getAll(node).each(function (src, i) {
for (var key in this.mirror) {
this.mirror[key](src, dest.nodes[i]);
}
});
return clone;
});
};
/**
* Return an array of DOM nodes of a source node and its children.
* @param {[Object]} context DOM node.
* @param {[String]} tag DOM node tagName.
* @return {[Array]} Array containing queried DOM nodes.
*/
u.prototype.getAll = function getAll (context) {
return u([context].concat(u('*', context).nodes));
};
// Store all of the operations to perform when cloning elements
u.prototype.mirror = {};
/**
* Copy all JavaScript events of source node to destination node.
* @param {[Object]} source DOM node
* @param {[Object]} destination DOM node
* @return {[undefined]]}
*/
u.prototype.mirror.events = function (src, dest) {
if (!src._e) return;
for (var type in src._e) {
src._e[type].forEach(function (event) {
u(dest).on(type, event);
});
}
};
/**
* Copy select input value to its clone.
* @param {[Object]} src DOM node
* @param {[Object]} dest DOM node
* @return {[undefined]}
*/
u.prototype.mirror.select = function (src, dest) {
if (u(src).is('select')) {
dest.value = src.value;
}
};
/**
* Copy textarea input value to its clone
* @param {[Object]} src DOM node
* @param {[Object]} dest DOM node
* @return {[undefined]}
*/
u.prototype.mirror.textarea = function (src, dest) {
if (u(src).is('textarea')) {
dest.value = src.value;
}
};
// Find the first ancestor that matches the selector for each node
u.prototype.closest = function (selector) {
return this.map(function (node) {
// Keep going up and up on the tree. First element is also checked
do {
if (u(node).is(selector)) {
return node;
}
} while ((node = node.parentNode) && node !== document);
});
};
// Handle data-* attributes for the matched elements
u.prototype.data = function (name, value) {
return this.attr(name, value, true);
};
// Loops through every node from the current call
u.prototype.each = function (callback) {
// By doing callback.call we allow "this" to be the context for
// the callback (see http://stackoverflow.com/q/4065353 precisely)
this.nodes.forEach(callback.bind(this));
return this;
};
// [INTERNAL USE ONLY]
// Loop through the combination of every node and every argument passed
u.prototype.eacharg = function (args, callback) {
return this.each(function (node, i) {
this.args(args, node, i).forEach(function (arg) {
// Perform the callback for this node
// By doing callback.call we allow "this" to be the context for
// the callback (see http://stackoverflow.com/q/4065353 precisely)
callback.call(this, node, arg);
}, this);
});
};
// .filter(selector)
// Delete all of the nodes that don't pass the selector
u.prototype.filter = function (selector) {
// The default function if it's a css selector
// Cannot change name to 'selector' since it'd mess with it inside this fn
var callback = function (node) {
// Make it compatible with some other browsers
node.matches = node.matches || node.msMatchesSelector || node.webkitMatchesSelector;
// Check if it's the same element (or any element if no selector was passed)
return node.matches(selector || '*');
};
// filter() receives a function as in .filter(e => u(e).children().length)
if (typeof selector === 'function') callback = selector;
// filter() receives an instance of Umbrella as in .filter(u('a'))
if (selector instanceof u) {
callback = function (node) {
return (selector.nodes).indexOf(node) !== -1;
};
}
// Just a native filtering function for ultra-speed
return u(this.nodes.filter(callback));
};
// Find all the nodes children of the current ones matched by a selector
u.prototype.find = function (selector) {
return this.map(function (node) {
return u(selector || '*', node);
});
};
// Get the first of the nodes
u.prototype.first = function () {
return this.nodes[0] || false;
};
// Perform ajax calls
/* eslint-disable no-unused-vars*/
function ajax (action, opt, done, before) {
done = done || function () {};
// A bunch of options and defaults
opt = opt || {};
opt.body = opt.body || {};
opt.method = (opt.method || 'GET').toUpperCase();
opt.headers = opt.headers || {};
// Tell the back-end it's an AJAX request
opt.headers['X-Requested-With'] = opt.headers['X-Requested-With'] || 'XMLHttpRequest';
if (typeof window.FormData === 'undefined' || !(opt.body instanceof window.FormData)) {
opt.headers['Content-Type'] = opt.headers['Content-Type'] || 'application/x-www-form-urlencoded';
}
// If it's of type JSON, encode it as such
if (/json/.test(opt.headers['Content-Type'])) {
opt.body = JSON.stringify(opt.body);
}
if ((typeof opt.body === 'object') && !(opt.body instanceof window.FormData)) {
opt.body = u().param(opt.body);
}
// Create and send the actual request
var request = new window.XMLHttpRequest();
// An error is just an error
// This uses a little hack of passing an array to u() so it handles it as
// an array of nodes, hence we can use 'on'. However a single element wouldn't
// work since it a) doesn't have nodeName and b) it will be sliced, failing
u(request).on('error timeout abort', function () {
done(new Error(), null, request);
}).on('load', function () {
// Also an error if it doesn't start by 2 or 3...
// This is valid as there's no code 2x nor 2, nor 3x nor 3, only 2xx and 3xx
// We don't want to return yet though as there might be some content
var err = /^(4|5)/.test(request.status) ? new Error(request.status) : null;
// Attempt to parse the body into JSON
var body = parseJson(request.response) || request.response;
return done(err, body, request);
});
// Create a request of the specified type to the URL and ASYNC
request.open(opt.method, action);
// Set the corresponding headers
for (var name in opt.headers) {
request.setRequestHeader(name, opt.headers[name]);
}
// Load the before callback before sending the data
if (before) before(request);
request.send(opt.body);
return request;
}
/* eslint-enable no-unused-vars*/
// [INTERNAL USE ONLY]
// Parse JSON without throwing an error
/* eslint-disable no-unused-vars*/
function parseJson (jsonString) {
try {
var o = JSON.parse(jsonString);
// Handle non-exception-throwing cases:
// Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking
// so we must check for that, too.
if (o && typeof o === 'object') {
return o;
}
} catch (e) {}
return false;
}
/* eslint-enable no-unused-vars*/
// [INTERNAL USE ONLY]
// Generate a fragment of HTML. This irons out the inconsistences
u.prototype.generate = function (html) {
// Table elements need to be child of <table> for some f***ed up reason
if (/^\s*<t(h|r|d)/.test(html)) {
return u(document.createElement('table')).html(html).children().nodes;
} else if (/^\s*</.test(html)) {
return u(document.createElement('div')).html(html).children().nodes;
} else {
return document.createTextNode(html);
}
};
// Change the default event for the callback. Simple decorator to preventDefault
u.prototype.handle = function () {
var args = this.slice(arguments).map(function (arg) {
if (typeof arg === 'function') {
return function (e) {
e.preventDefault();
arg.apply(this, arguments);
};
}
return arg;
}, this);
return this.on.apply(this, args);
};
// Find out whether the matched elements have a class or not
u.prototype.hasClass = function () {
// Check if any of them has all of the classes
return this.is('.' + this.args(arguments).join('.'));
};
// Set or retrieve the html from the matched node(s)
u.prototype.html = function (text) {
// Needs to check undefined as it might be ""
if (text === undefined) {
return this.first().innerHTML || '';
}
// If we're attempting to set some text
// Loop through all the nodes
return this.each(function (node) {
// Set the inner html to the node
node.innerHTML = text;
});
};
// Check whether any of the nodes matches the selector
u.prototype.is = function (selector) {
return this.filter(selector).length > 0;
};
/**
* Internal use only. This function checks to see if an element is in the page's body. As contains is inclusive and determining if the body contains itself isn't the intention of isInPage this case explicitly returns false.
https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
* @param {[Object]} node DOM node
* @return {Boolean} The Node.contains() method returns a Boolean value indicating whether a node is a descendant of a given node or not.
*/
u.prototype.isInPage = function isInPage (node) {
return (node === document.body) ? false : document.body.contains(node);
};
// Get the last of the nodes
u.prototype.last = function () {
return this.nodes[this.length - 1] || false;
};
// Merge all of the nodes that the callback returns
u.prototype.map = function (callback) {
return callback ? u(this.array(callback)).unique() : this;
};
// Delete all of the nodes that equals the filter
u.prototype.not = function (filter) {
return this.filter(function (node) {
return !u(node).is(filter || true);
});
};
// Removes the callback to the event listener for each node
u.prototype.off = function (events) {
return this.eacharg(events, function (node, event) {
u(node._e ? node._e[event] : []).each(function (cb) {
node.removeEventListener(event, cb);
});
});
};
// Attach a callback to the specified events
u.prototype.on = function (events, cb, cb2) {
if (typeof cb === 'string') {
var sel = cb;
cb = function (e) {
var args = arguments;
u(e.currentTarget).find(sel).each(function (target) {
if (target === e.target || target.contains(e.target)) {
try {
Object.defineProperty(e, 'currentTarget', {
get: function () {
return target;
}
});
} catch (err) {}
cb2.apply(target, args);
}
});
};
}
// Add the custom data as arguments to the callback
var callback = function (e) {
return cb.apply(this, [e].concat(e.detail || []));
};
return this.eacharg(events, function (node, event) {
node.addEventListener(event, callback);
// Store it so we can dereference it with `.off()` later on
node._e = node._e || {};
node._e[event] = node._e[event] || [];
node._e[event].push(callback);
});
};
// [INTERNAL USE ONLY]
// Parametize an object: { a: 'b', c: 'd' } => 'a=b&c=d'
u.prototype.param = function (obj) {
return Object.keys(obj).map(function (key) {
return this.uri(key) + '=' + this.uri(obj[key]);
}.bind(this)).join('&');
};
// Travel the matched elements one node up
u.prototype.parent = function (selector) {
return this.map(function (node) {
return node.parentNode;
}).filter(selector);
};
// Add nodes at the beginning of each node
u.prototype.prepend = function (html, data) {
return this.adjacent(html, data, function (node, fragment) {
node.insertBefore(fragment, node.firstChild);
});
};
// Delete the matched nodes from the DOM
u.prototype.remove = function () {
// Loop through all the nodes
return this.each(function (node) {
// Perform the removal
node.parentNode.removeChild(node);
});
};
// Removes a class from all of the matched nodes
u.prototype.removeClass = function () {
// Loop the combination of each node with each argument
return this.eacharg(arguments, function (el, name) {
// Remove the class using the native method
el.classList.remove(name);
});
};
// Replace the matched elements with the passed argument.
u.prototype.replace = function (html, data) {
var nodes = [];
this.adjacent(html, data, function (node, fragment) {
nodes = nodes.concat(this.slice(fragment.children));
node.parentNode.replaceChild(fragment, node);
});
return u(nodes);
};
// Scroll to the first matched element
u.prototype.scroll = function () {
this.first().scrollIntoView({ behavior: 'smooth' });
return this;
};
// [INTERNAL USE ONLY]
// Select the adecuate part from the context
u.prototype.select = function (parameter, context) {
// Allow for spaces before or after
parameter = parameter.replace(/^\s*/, '').replace(/\s*$/, '');
if (context) {
return this.select.byCss(parameter, context);
}
for (var key in this.selectors) {
// Reusing it to save space
context = key.split('/');
if ((new RegExp(context[1], context[2])).test(parameter)) {
return this.selectors[key](parameter);
}
}
return this.select.byCss(parameter);
};
// Select some elements using a css Selector
u.prototype.select.byCss = function (parameter, context) {
return (context || document).querySelectorAll(parameter);
};
// Allow for adding/removing regexes and parsing functions
// It stores a regex: function pair to process the parameter and context
u.prototype.selectors = {};
// Find some html nodes using an Id
u.prototype.selectors[/^\.[\w\-]+$/] = function (param) {
return document.getElementsByClassName(param.substring(1));
};
// The tag nodes
u.prototype.selectors[/^\w+$/] = function (param) {
return document.getElementsByTagName(param);
};
// Find some html nodes using an Id
u.prototype.selectors[/^\#[\w\-]+$/] = function (param) {
return document.getElementById(param.substring(1));
};
// Create a new element for the DOM
u.prototype.selectors[/^</] = function (param) {
return u().generate(param);
};
// Convert forms into a string able to be submitted
// Original source: http://stackoverflow.com/q/11661187
u.prototype.serialize = function () {
var self = this;
// Store the class in a variable for manipulation
return this.slice(this.first().elements).reduce(function (query, el) {
// We only want to match enabled elements with names, but not files
if (!el.name || el.disabled || el.type === 'file') return query;
// Ignore the checkboxes that are not checked
if (/(checkbox|radio)/.test(el.type) && !el.checked) return query;
// Handle multiple selects
if (el.type === 'select-multiple') {
u(el.options).each(function (opt) {
if (opt.selected) {
query += '&' + self.uri(el.name) + '=' + self.uri(opt.value);
}
});
return query;
}
// Add the element to the object
return query + '&' + self.uri(el.name) + '=' + self.uri(el.value);
}, '').slice(1);
};
// Travel the matched elements at the same level
u.prototype.siblings = function (selector) {
return this.parent().children(selector).not(this);
};
// Find the size of the first matched element
u.prototype.size = function () {
return this.first().getBoundingClientRect();
};
// [INTERNAL USE ONLY]
// Force it to be an array AND also it clones them
// http://toddmotto.com/a-comprehensive-dive-into-nodelists-arrays-converting-nodelists-and-understanding-the-dom/
u.prototype.slice = function (pseudo) {
// Check that it's not a valid object
if (!pseudo ||
pseudo.length === 0 ||
typeof pseudo === 'string' ||
pseudo.toString() === '[object Function]') return [];
// Accept also a u() object (that has .nodes)
return pseudo.length ? [].slice.call(pseudo.nodes || pseudo) : [pseudo];
};
// [INTERNAL USE ONLY]
// Create a string from different things
u.prototype.str = function (node, i) {
return function (arg) {
// Call the function with the corresponding nodes
if (typeof arg === 'function') {
return arg.call(this, node, i);
}
// From an array or other 'weird' things
return arg.toString();
};
};
// Set or retrieve the text content from the matched node(s)
u.prototype.text = function (text) {
// Needs to check undefined as it might be ""
if (text === undefined) {
return this.first().textContent || '';
}
// If we're attempting to set some text
// Loop through all the nodes
return this.each(function (node) {
// Set the text content to the node
node.textContent = text;
});
};
// Activate/deactivate classes in the elements
u.prototype.toggleClass = function (classes, addOrRemove) {
/* jshint -W018 */
// Check if addOrRemove was passed as a boolean
if (!!addOrRemove === addOrRemove) {
return this[addOrRemove ? 'addClass' : 'removeClass'](classes);
}
/* jshint +W018 */
// Loop through all the nodes and classes combinations
return this.eacharg(classes, function (el, name) {
el.classList.toggle(name);
});
};
// Call an event manually on all the nodes
u.prototype.trigger = function (events) {
var data = this.slice(arguments).slice(1);
return this.eacharg(events, function (node, event) {
var ev;
// Allow the event to bubble up and to be cancelable (as default)
var opts = { bubbles: true, cancelable: true, detail: data };
try {
// Accept different types of event names or an event itself
ev = new window.CustomEvent(event, opts);
} catch (e) {
ev = document.createEvent('CustomEvent');
ev.initCustomEvent(event, true, true, data);
}
node.dispatchEvent(ev);
});
};
// [INTERNAL USE ONLY]
// Removed duplicated nodes, used for some specific methods
u.prototype.unique = function () {
return u(this.nodes.reduce(function (clean, node) {
var istruthy = node !== null && node !== undefined && node !== false;
return (istruthy && clean.indexOf(node) === -1) ? clean.concat(node) : clean;
}, []));
};
// [INTERNAL USE ONLY]
// Encode the different strings https://gist.github.com/brettz9/7147458
u.prototype.uri = function (str) {
return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
};
u.prototype.wrap = function (selector) {
function findDeepestNode (node) {
while (node.firstElementChild) {
node = node.firstElementChild;
}
return u(node);
}
// 1) Construct dom node e.g. u('<a>'),
// 2) clone the currently matched node
// 3) append cloned dom node to constructed node based on selector
return this.map(function (node) {
return u(selector).each(function (n) {
findDeepestNode(n)
.append(node.cloneNode(true));
node
.parentNode
.replaceChild(n, node);
});
});
};
// Export it for webpack
if (typeof module === 'object' && module.exports) {
module.exports = {
u: u,
ajax: ajax
};
}
/*global define:false */
/**
* Copyright 2015 Craig Campbell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Mousetrap is a simple keyboard shortcut library for Javascript with
* no external dependencies
*
* @version 1.5.2
* @url craig.is/killing/mice
*/
(function(window, document, undefined) {
/**
* mapping of special keycodes to their corresponding keys
*
* everything in this dictionary cannot use keypress events
* so it has to be here to map to the correct keycodes for
* keyup/keydown events
*
* @type {Object}
*/
var _MAP = {
8: 'backspace',
9: 'tab',
13: 'enter',
16: 'shift',
17: 'ctrl',
18: 'alt',
20: 'capslock',
27: 'esc',
32: 'space',
33: 'pageup',
34: 'pagedown',
35: 'end',
36: 'home',
37: 'left',
38: 'up',
39: 'right',
40: 'down',
45: 'ins',
46: 'del',
91: 'meta',
93: 'meta',
224: 'meta'
};
/**
* mapping for special characters so they can support
*
* this dictionary is only used incase you want to bind a
* keyup or keydown event to one of these keys
*
* @type {Object}
*/
var _KEYCODE_MAP = {
106: '*',
107: '+',
109: '-',
110: '.',
111 : '/',
186: ';',
187: '=',
188: ',',
189: '-',
190: '.',
191: '/',
192: '`',
219: '[',
220: '\\',
221: ']',
222: '\''
};
/**
* this is a mapping of keys that require shift on a US keypad
* back to the non shift equivelents
*
* this is so you can use keyup events with these keys
*
* note that this will only work reliably on US keyboards
*
* @type {Object}
*/
var _SHIFT_MAP = {
'~': '`',
'!': '1',
'@': '2',
'#': '3',
'$': '4',
'%': '5',
'^': '6',
'&': '7',
'*': '8',
'(': '9',
')': '0',
'_': '-',
'+': '=',
':': ';',
'\"': '\'',
'<': ',',
'>': '.',
'?': '/',
'|': '\\'
};
/**
* this is a list of special strings you can use to map
* to modifier keys when you specify your keyboard shortcuts
*
* @type {Object}
*/
var _SPECIAL_ALIASES = {
'option': 'alt',
'command': 'meta',
'return': 'enter',
'escape': 'esc',
'plus': '+',
'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
};
/**