-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnux.js
More file actions
8416 lines (6972 loc) · 241 KB
/
nux.js
File metadata and controls
8416 lines (6972 loc) · 241 KB
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 e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
/** @module index */
/* Type Definititions */
/**
* A Redux store.
* @typedef {Object} Store
* @property {Function} dispatch Dispatch a provided action with type to invoke a matching reducer.
* @property {Function} getState Get the current global state.
* @property {Function} subscribe Provide callback to be invoked every time an action is fired.
* @property {Function} replaceReducer Replace an existing reducer with a new one.
*/
var h = _interopRequire(require("virtual-dom/h"));
var diff = _interopRequire(require("virtual-dom/diff"));
var patch = _interopRequire(require("virtual-dom/patch"));
var createElement = _interopRequire(require("virtual-dom/create-element"));
var delegator = _interopRequire(require("dom-delegator"));
var _redux = require("redux");
var createStore = _redux.createStore;
var compose = _redux.compose;
var utils = _interopRequire(require("./utils"));
var renderUI = require("./ui").renderUI;
var reducer = require("./reducer").reducer;
var _immutable = require("immutable");
var fromJS = _immutable.fromJS;
var Map = _immutable.Map;
var Rlite = _interopRequire(require("rlite-router"));
var nux = window.nux = module.exports = {
init: init,
options: {
localStorage: false,
logActions: false
},
utils: utils
};
/**
* Used to initialize a new Nux application. Any reducer that is provided will be combined with Nux's built
* in reducers. The initial UI is the base template for the application and is what will be rendered immediately
* upon initialization. A number of options can be provided as documented, and any element can be specified into
* which Nux will render the application, allowing for the running of multiple, disparate instances of Nux on
* a given page. A Redux store is returned, although direct interaction with the store should be unnecessary.
* Once initialized, any changes to the global state for a given Nux instance will be immediately reflected in
* via an efficient patching mechanism via virtual-dom.
*
* @author Mark Nutter <marknutter@gmail.com>
* @summary Initialize a Nux application.
*
* @param {Function} appReducer The provided reducer function.
* @param {Object} [initialUI] The initial UI vDOM object which will become the first state to be rendered.
* @param {Object} [options] Options to configure the nux application.
* @param {Boolean} [options.localStorage=false] Enable caching of global state to localStorage.
* @param {Boolean} [options.logActions=false] Enable advanced logging of all actions fired.
* @param {Element} [elem=HTMLBodyElement] The element into which the nux application will be rendered.
* @return {Store} Redux store where app state is maintained.
*/
function init(appReducer) {
var initialUI = arguments[1] === undefined ? fromJS({ div: {} }) : arguments[1];
var options = arguments[2] === undefined ? nux.options : arguments[2];
var elem = arguments[3] === undefined ? document.body : arguments[3];
var initialState = initialUI;
if (options.localStorage && localStorage.getItem("nux")) {
initialState = JSON.parse(localStorage.getItem("nux"));
};
delegator();
var router = Rlite();
var store = createStore(reducer(appReducer, initialState, options));
var currentUI = store.getState().get("ui").toVNode(store);
var rootNode = createElement(currentUI);
elem.appendChild(rootNode);
if (store.getState().get("routes")) {
var processHash = function () {
var hash = location.hash || "#";
router.run(hash.slice(1));
};
store.getState().get("routes").forEach(function (action, route) {
router.add(route, function (r) {
store.dispatch(action.merge(Map(r)).toJS());
});
});
window.addEventListener("hashchange", processHash);
processHash();
}
store.subscribe(function () {
var ui = store.getState().get("ui");
if (options.localStorage) {
localStorage.setItem("nux", JSON.stringify(ui ? ui.toJS() : {}));
}
var newUI = store.getState().get("ui").toVNode(store);
var patches = diff(currentUI, newUI);
rootNode = patch(rootNode, patches);
currentUI = newUI;
});
return store;
}
},{"./reducer":2,"./ui":3,"./utils":4,"dom-delegator":9,"immutable":21,"redux":23,"rlite-router":31,"virtual-dom/create-element":32,"virtual-dom/diff":33,"virtual-dom/h":34,"virtual-dom/patch":42}],2:[function(require,module,exports){
/**
* Create a reducer using a provided reducer combined with Nux's internal reducer. An initial vDOM UI object
* can be passed in to initialize the store with, as well as any options to further configure the reducer.
* The reducer returned is intended for use with a Redux store.
*
* @author Mark Nutter <marknutter@gmail.com>
* @summary Generate a Nux reducer function given a custom reducer function.
*
* @param {Function} appReducer The provided reducer function.
* @param {Object} [initialUI] The initial UI vDOM object which will become the first state to be rendered.
* @param {Object} [options] Options to configure the generated reducer.
* @param {Boolean} [options.logActions=false] Enable advanced logging of all actions fired.
* @return {Function} Reducer function to be used to initialize a Redux store
*/
"use strict";
exports.reducer = reducer;
Object.defineProperty(exports, "__esModule", {
value: true
});
/** @module reducer */
/**
* An Immutable Map.
* @typedef {Object} Map
*/
var _immutable = require("immutable");
var fromJS = _immutable.fromJS;
var Iterable = _immutable.Iterable;
var Map = _immutable.Map;
function reducer(appReducer) {
var initialUI = arguments[1] === undefined ? {} : arguments[1];
var options = arguments[2] === undefined ? {} : arguments[2];
var initialState = fromJS({ ui: initialUI }, function (key, value) {
var isIndexed = Iterable.isIndexed(value);
return isIndexed ? value.toList() : value.toOrderedMap();
}).merge(options.routes ? fromJS({ routes: options.routes }) : {});
return function (_x3, action) {
var state = arguments[0] === undefined ? initialState : arguments[0];
var nextState = undefined;
switch (action.type) {
case "_UPDATE_INPUT_VALUE":
nextState = state.setIn(action.pathArray.concat(["props", "value"]), action.val);
break;
default:
nextState = appReducer(state, action);
break;
}
if (options.logActions) {
storeAndLogState(action, nextState, state);
}
return nextState;
};
}
/**
* Log the previous state, an action, and the new state that resulted from that action
*
* @author Mark Nutter <marknutter@gmail.com>
* @summary Advance state change logging.
*
* @param {Object} action The redux action object.
* @param {Object} action.type The redux action type.
* @param {Map} nextState The state resulting from having performed the given action
* @param {Map} prevState The state as it was before the given action was performed
*/
function storeAndLogState(action, nextState, prevState) {
var nextStateJS = nextState.toJS();
console.log("\n----------------------------------------------------------------\nACTION TAKEN ", action, "\nNEW STATE ", nextStateJS, "\nPREVIOUS STATE ", prevState.toJS(), "\n----------------------------------------------------------------");
}
},{"immutable":21}],3:[function(require,module,exports){
"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
/**
* Accepts a Nux vDOM object and returns a VirtualNode. The vDOM object's 'children' are recursively converted
* to VirtualNodes. The 'props' for any given are modified such that any custom events are assigned callbacks
* which dispatch the associated actions. The Nux default event handlers are also added to the 'props' object
* for a given node. This is where all the magic happens, folks.
*
* @author Mark Nutter <marknutter@gmail.com>
*
* @param {Store} store A redux store
* @param {Object} ui The Nux vDOM object to be recursively converted into a VirtualNode
* @param {Array} [pathArray] The location of the provided vDOM object within another vDOM object (if applicable)
* @return {Store} Redux store where app state is maintained.
*/
exports.renderUI = renderUI;
Object.defineProperty(exports, "__esModule", {
value: true
});
/** @module ui */
var h = _interopRequire(require("virtual-dom/h"));
var _immutable = require("immutable");
var fromJS = _immutable.fromJS;
var Map = _immutable.Map;
var List = _immutable.List;
var Iterable = _immutable.Iterable;
function renderUI(store, ui) {
var pathArray = arguments[2] === undefined ? List() : arguments[2];
// ui objects come as a key/value pair so extract the key as the tag name and value as the node data
var tagName = ui.findKey(function () {
return true;
});
var node = ui.get(tagName);
// keep track of our current location in the ui vDOM object
var currentPathArray = pathArray.size === 0 ? pathArray.push(tagName) : pathArray;
var children = List(),
props = node.get("props") || Map();
// recurse through this node's children and render their UI as hyperscript
if (node.get("children")) {
children = node.get("children").map(function (childVal, childTagName) {
if (childTagName === "$text") {
return new List([childVal]);
} else {
return renderUI(store, new Map().set(childTagName, childVal), currentPathArray.concat(["children", childTagName]));
}
}).toList();
}
// add an event handler to inputs that updates their 'val' prop node when changes are detected
var registeredKeyEvents = {};
if (tagName.indexOf("input") > -1) {
props = props.set("ev-keyup", function (e) {
e.preventDefault();
store.dispatch({
type: "_UPDATE_INPUT_VALUE",
val: e.target.value,
pathArray: ["ui"].concat(currentPathArray.toJS())
});
registeredKeyEvents["ev-keyup"] ? registeredKeyEvents["ev-keyup"](e) : false;
registeredKeyEvents["ev-keyup-" + e.keyCode] ? registeredKeyEvents["ev-keyup-" + e.keyCode](e) : false;
});
}
// for any custom events detected, add callbacks that dispatch provided actions
if (props.get("events")) {
props = props.get("events").reduce(function (oldProps, val, key) {
if (key.indexOf("ev-keyup") > -1) {
registeredKeyEvents[key] = function (e) {
store.dispatch(val.get("dispatch").merge(Map({ event: e })).toJS());
};
return oldProps;
} else {
return oldProps.set(key, function (e) {
e.preventDefault();
store.dispatch(val.get("dispatch").merge(Map({ event: e })).toJS());
});
}
}, props)["delete"]("events");
}
// combine tag, props, and children into an array of plain javascript objects and return hyperscript VirtualNode
return h.apply(this, [tagName, props.toJS(), children.toJS()]);
}
;
},{"immutable":21,"virtual-dom/h":34}],4:[function(require,module,exports){
"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
/**
* Returns an array path that can be used to deeply select inside of Nux. 'children' strings
* will be interleaved between tag strings while all nodes from 'props' and onward will be
* added in sequence. All returned arrays will include a leading 'ui' node.
*
* @example
* selector('div#foo form#bar input#baz props value');
* // returns ['div#foo', 'children', 'form#bar', 'children', 'input#baz', 'props', 'value']
*
* @author Mark Nutter <marknutter@gmail.com>
* @summary Generate a Nux reducer function given a custom reducer function.
*
* @param {String} selectorString
* @return {Array} Path array used to deeply select inside of Immutable Nux vDOM objects
*/
exports.selector = selector;
Object.defineProperty(exports, "__esModule", {
value: true
});
/** @module utils */
var _immutable = require("immutable");
var Collection = _immutable.Collection;
var Map = _immutable.Map;
var fromJS = _immutable.fromJS;
var renderUI = require("./ui").renderUI;
var createElement = _interopRequire(require("virtual-dom/create-element"));
Collection.prototype.$ = function $(query, setVal) {
var pathArray = selector(query);
var tagName = pathArray.pop();
var nodeVal = undefined,
node = undefined;
if (setVal !== undefined) {
nodeVal = this.setIn(selector(query), setVal);
node = new Map().set(tagName, nodeVal);
return node;
} else {
nodeVal = this.getIn(selector(query));
node = new Map().set(tagName, nodeVal);
node.__queryNode = this;
node.__query = query;
return node;
}
};
Collection.prototype.children = function children() {
var tagName = this.findKey(function () {
return true;
});
var children = this.getIn([tagName, "children"]) || this.get("children") || new Map();
if (arguments.length === 0) {
return children;
}
if (arguments[0] && typeof arguments[0] === "object") {
children = arguments[0];
} else if (typeof arguments[0] === "string" && arguments[1] !== undefined) {
children = arguments[1] === null ? children["delete"](arguments[0]) : children.set(arguments[0], arguments[1]);
} else if (arguments.length === 1 && typeof arguments[0] === "string") {
return children.get(arguments[0]);
}
return this.__queryNode ? this.__queryNode.setIn(selector(this.__query).concat("children"), children) : this.setIn([tagName, "children"], children);
};
Collection.prototype.toNode = function toNode(tagName) {
return new Map().set(tagName, this);
};
Collection.prototype.toVNode = function toVNode(store) {
return renderUI(store, this);
};
Collection.prototype.toElement = function toElement(store) {
var vNode = this.toVNode(store);
if (vNode) {
return createElement(vNode);
}
};
Collection.prototype.toHTML = function toHTML(store) {
var element = this.toElement(store);
if (element) {
return element.outerHTML;
}
};
Collection.prototype.props = function props() {
var tagName = this.findKey(function () {
return true;
});
var props = this.getIn([tagName, "props"]) || new Map();
if (arguments.length === 0) {
return props;
}
if (typeof arguments[0] === "object") {
props = props.merge(arguments[0]);
} else if (typeof arguments[0] === "string" && arguments[1] !== undefined) {
props = arguments[1] === null ? props["delete"](arguments[0]) : props.set(arguments[0], fromJS(arguments[1]));
} else if (arguments.length === 1 && typeof arguments[0] === "string") {
return props.get(arguments[0]);
}
return this.__queryNode ? this.__queryNode.setIn(selector(this.__query).concat("props"), props) : this.setIn([tagName, "props"], props);
};
Collection.prototype.style = function style() {
var tagName = this.findKey(function () {
return true;
});
var style = this.getIn([tagName, "props", "style"]) || new Map();
if (!style) {
return new Map();
}
if (arguments.length === 0) {
return style;
}
if (typeof arguments[0] === "object") {
style = style.merge(arguments[0]);
} else if (typeof arguments[0] === "string" && typeof arguments[1] === "string") {
style = style.set(arguments[0], arguments[1]);
} else if (typeof arguments[0] === "string" && arguments[1] === null) {
style = style["delete"](arguments[0]);
} else if (arguments.length === 1 && typeof arguments[0] === "string") {
return style.get(arguments[0]);
}
return this.__queryNode ? this.__queryNode.setIn(selector(this.__query).concat(["props", "style"]), style) : this.setIn([tagName, "props", "style"], style);
};
Collection.prototype.events = function events() {
var tagName = this.findKey(function () {
return true;
});
var events = this.getIn([tagName, "props", "events"]) || new Map();
if (!events) {
return new Map();
}
if (arguments.length === 0) {
return events;
}
if (typeof arguments[0] === "object") {
events = events.merge(arguments[0]);
} else if (typeof arguments[0] === "string" && typeof arguments[1] === "object") {
events = events.set(arguments[0], fromJS(arguments[1]));
} else if (typeof arguments[0] === "string" && arguments[1] === null) {
events = events["delete"](arguments[0]);
} else if (arguments.length === 1 && typeof arguments[0] === "string") {
return events.get(arguments[0]);
}
return this.__queryNode ? this.__queryNode.setIn(selector(this.__query).concat(["props", "events"]), events) : this.setIn([tagName, "props", "events"], events);
};
function selector(selectorString) {
var domPathArray = selectorString.split(" props")[0].split(" ");
var fullDomPathArray = domPathArray.reduce(function (cur, val, index) {
if (val === "children") {
return cur;
}
if (val === "ui" || val === "props") {
return cur.concat([val]);
} else {
return domPathArray.length === index + 1 ? cur.concat([val]) : cur.concat([val, "children"]);
}
}, []);
var toConcat = [];
if (selectorString.indexOf("props") > 0) {
var propsPathArray = selectorString.split("props")[1].split(" ");
toConcat = ["props"].concat(propsPathArray.slice(1));
}
return fullDomPathArray.concat(toConcat);
}
;
},{"./ui":3,"immutable":21,"virtual-dom/create-element":32}],5:[function(require,module,exports){
},{}],6:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
process.nextTick = (function () {
var canSetImmediate = typeof window !== 'undefined'
&& window.setImmediate;
var canMutationObserver = typeof window !== 'undefined'
&& window.MutationObserver;
var canPost = typeof window !== 'undefined'
&& window.postMessage && window.addEventListener
;
if (canSetImmediate) {
return function (f) { return window.setImmediate(f) };
}
var queue = [];
if (canMutationObserver) {
var hiddenDiv = document.createElement("div");
var observer = new MutationObserver(function () {
var queueList = queue.slice();
queue.length = 0;
queueList.forEach(function (fn) {
fn();
});
});
observer.observe(hiddenDiv, { attributes: true });
return function nextTick(fn) {
if (!queue.length) {
hiddenDiv.setAttribute('yes', 'no');
}
queue.push(fn);
};
}
if (canPost) {
window.addEventListener('message', function (ev) {
var source = ev.source;
if ((source === window || source === null) && ev.data === 'process-tick') {
ev.stopPropagation();
if (queue.length > 0) {
var fn = queue.shift();
fn();
}
}
}, true);
return function nextTick(fn) {
queue.push(fn);
window.postMessage('process-tick', '*');
};
}
return function nextTick(fn) {
setTimeout(fn, 0);
};
})();
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
},{}],7:[function(require,module,exports){
var EvStore = require("ev-store")
module.exports = addEvent
function addEvent(target, type, handler) {
var events = EvStore(target)
var event = events[type]
if (!event) {
events[type] = handler
} else if (Array.isArray(event)) {
if (event.indexOf(handler) === -1) {
event.push(handler)
}
} else if (event !== handler) {
events[type] = [event, handler]
}
}
},{"ev-store":11}],8:[function(require,module,exports){
var globalDocument = require("global/document")
var EvStore = require("ev-store")
var createStore = require("weakmap-shim/create-store")
var addEvent = require("./add-event.js")
var removeEvent = require("./remove-event.js")
var ProxyEvent = require("./proxy-event.js")
var HANDLER_STORE = createStore()
module.exports = DOMDelegator
function DOMDelegator(document) {
if (!(this instanceof DOMDelegator)) {
return new DOMDelegator(document);
}
document = document || globalDocument
this.target = document.documentElement
this.events = {}
this.rawEventListeners = {}
this.globalListeners = {}
}
DOMDelegator.prototype.addEventListener = addEvent
DOMDelegator.prototype.removeEventListener = removeEvent
DOMDelegator.allocateHandle =
function allocateHandle(func) {
var handle = new Handle()
HANDLER_STORE(handle).func = func;
return handle
}
DOMDelegator.transformHandle =
function transformHandle(handle, broadcast) {
var func = HANDLER_STORE(handle).func
return this.allocateHandle(function (ev) {
broadcast(ev, func);
})
}
DOMDelegator.prototype.addGlobalEventListener =
function addGlobalEventListener(eventName, fn) {
var listeners = this.globalListeners[eventName] || [];
if (listeners.indexOf(fn) === -1) {
listeners.push(fn)
}
this.globalListeners[eventName] = listeners;
}
DOMDelegator.prototype.removeGlobalEventListener =
function removeGlobalEventListener(eventName, fn) {
var listeners = this.globalListeners[eventName] || [];
var index = listeners.indexOf(fn)
if (index !== -1) {
listeners.splice(index, 1)
}
}
DOMDelegator.prototype.listenTo = function listenTo(eventName) {
if (!(eventName in this.events)) {
this.events[eventName] = 0;
}
this.events[eventName]++;
if (this.events[eventName] !== 1) {
return
}
var listener = this.rawEventListeners[eventName]
if (!listener) {
listener = this.rawEventListeners[eventName] =
createHandler(eventName, this)
}
this.target.addEventListener(eventName, listener, true)
}
DOMDelegator.prototype.unlistenTo = function unlistenTo(eventName) {
if (!(eventName in this.events)) {
this.events[eventName] = 0;
}
if (this.events[eventName] === 0) {
throw new Error("already unlistened to event.");
}
this.events[eventName]--;
if (this.events[eventName] !== 0) {
return
}
var listener = this.rawEventListeners[eventName]
if (!listener) {
throw new Error("dom-delegator#unlistenTo: cannot " +
"unlisten to " + eventName)
}
this.target.removeEventListener(eventName, listener, true)
}
function createHandler(eventName, delegator) {
var globalListeners = delegator.globalListeners;
var delegatorTarget = delegator.target;
return handler
function handler(ev) {
var globalHandlers = globalListeners[eventName] || []
if (globalHandlers.length > 0) {
var globalEvent = new ProxyEvent(ev);
globalEvent.currentTarget = delegatorTarget;
callListeners(globalHandlers, globalEvent)
}
findAndInvokeListeners(ev.target, ev, eventName)
}
}
function findAndInvokeListeners(elem, ev, eventName) {
var listener = getListener(elem, eventName)
if (listener && listener.handlers.length > 0) {
var listenerEvent = new ProxyEvent(ev);
listenerEvent.currentTarget = listener.currentTarget
callListeners(listener.handlers, listenerEvent)
if (listenerEvent._bubbles) {
var nextTarget = listener.currentTarget.parentNode
findAndInvokeListeners(nextTarget, ev, eventName)
}
}
}
function getListener(target, type) {
// terminate recursion if parent is `null`
if (target === null || typeof target === "undefined") {
return null
}
var events = EvStore(target)
// fetch list of handler fns for this event
var handler = events[type]
var allHandler = events.event
if (!handler && !allHandler) {
return getListener(target.parentNode, type)
}
var handlers = [].concat(handler || [], allHandler || [])
return new Listener(target, handlers)
}
function callListeners(handlers, ev) {
handlers.forEach(function (handler) {
if (typeof handler === "function") {
handler(ev)
} else if (typeof handler.handleEvent === "function") {
handler.handleEvent(ev)
} else if (handler.type === "dom-delegator-handle") {
HANDLER_STORE(handler).func(ev)
} else {
throw new Error("dom-delegator: unknown handler " +
"found: " + JSON.stringify(handlers));
}
})
}
function Listener(target, handlers) {
this.currentTarget = target
this.handlers = handlers
}
function Handle() {
this.type = "dom-delegator-handle"
}
},{"./add-event.js":7,"./proxy-event.js":19,"./remove-event.js":20,"ev-store":11,"global/document":14,"weakmap-shim/create-store":17}],9:[function(require,module,exports){
var Individual = require("individual")
var cuid = require("cuid")
var globalDocument = require("global/document")
var DOMDelegator = require("./dom-delegator.js")
var versionKey = "13"
var cacheKey = "__DOM_DELEGATOR_CACHE@" + versionKey
var cacheTokenKey = "__DOM_DELEGATOR_CACHE_TOKEN@" + versionKey
var delegatorCache = Individual(cacheKey, {
delegators: {}
})
var commonEvents = [
"blur", "change", "click", "contextmenu", "dblclick",
"error","focus", "focusin", "focusout", "input", "keydown",
"keypress", "keyup", "load", "mousedown", "mouseup",
"resize", "select", "submit", "touchcancel",
"touchend", "touchstart", "unload"
]
/* Delegator is a thin wrapper around a singleton `DOMDelegator`
instance.
Only one DOMDelegator should exist because we do not want
duplicate event listeners bound to the DOM.
`Delegator` will also `listenTo()` all events unless
every caller opts out of it
*/
module.exports = Delegator
function Delegator(opts) {
opts = opts || {}
var document = opts.document || globalDocument
var cacheKey = document[cacheTokenKey]
if (!cacheKey) {
cacheKey =
document[cacheTokenKey] = cuid()
}
var delegator = delegatorCache.delegators[cacheKey]
if (!delegator) {
delegator = delegatorCache.delegators[cacheKey] =
new DOMDelegator(document)
}
if (opts.defaultEvents !== false) {
for (var i = 0; i < commonEvents.length; i++) {
delegator.listenTo(commonEvents[i])
}
}
return delegator
}
Delegator.allocateHandle = DOMDelegator.allocateHandle;
Delegator.transformHandle = DOMDelegator.transformHandle;
},{"./dom-delegator.js":8,"cuid":10,"global/document":14,"individual":15}],10:[function(require,module,exports){
/**
* cuid.js
* Collision-resistant UID generator for browsers and node.
* Sequential for fast db lookups and recency sorting.
* Safe for element IDs and server-side lookups.
*
* Extracted from CLCTR
*
* Copyright (c) Eric Elliott 2012
* MIT License
*/
/*global window, navigator, document, require, process, module */
(function (app) {
'use strict';
var namespace = 'cuid',
c = 0,
blockSize = 4,
base = 36,
discreteValues = Math.pow(base, blockSize),
pad = function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
},
randomBlock = function randomBlock() {
return pad((Math.random() *
discreteValues << 0)
.toString(base), blockSize);
},
safeCounter = function () {
c = (c < discreteValues) ? c : 0;
c++; // this is not subliminal
return c - 1;
},
api = function cuid() {
// Starting with a lowercase letter makes
// it HTML element ID friendly.
var letter = 'c', // hard-coded allows for sequential access
// timestamp
// warning: this exposes the exact date and time
// that the uid was created.
timestamp = (new Date().getTime()).toString(base),
// Prevent same-machine collisions.
counter,
// A few chars to generate distinct ids for different
// clients (so different computers are far less
// likely to generate the same id)
fingerprint = api.fingerprint(),
// Grab some more chars from Math.random()
random = randomBlock() + randomBlock();
counter = pad(safeCounter().toString(base), blockSize);
return (letter + timestamp + counter + fingerprint + random);
};
api.slug = function slug() {
var date = new Date().getTime().toString(36),
counter,
print = api.fingerprint().slice(0,1) +
api.fingerprint().slice(-1),
random = randomBlock().slice(-2);
counter = safeCounter().toString(36).slice(-4);
return date.slice(-2) +
counter + print + random;
};
api.globalCount = function globalCount() {
// We want to cache the results of this
var cache = (function calc() {
var i,
count = 0;
for (i in window) {
count++;
}
return count;
}());
api.globalCount = function () { return cache; };
return cache;
};
api.fingerprint = function browserPrint() {
return pad((navigator.mimeTypes.length +
navigator.userAgent.length).toString(36) +
api.globalCount().toString(36), 4);
};
// don't change anything from here down.
if (app.register) {
app.register(namespace, api);
} else if (typeof module !== 'undefined') {
module.exports = api;
} else {
app[namespace] = api;
}
}(this.applitude || this));
},{}],11:[function(require,module,exports){
'use strict';
var OneVersionConstraint = require('individual/one-version');
var MY_VERSION = '7';
OneVersionConstraint('ev-store', MY_VERSION);
var hashKey = '__EV_STORE_KEY@' + MY_VERSION;
module.exports = EvStore;
function EvStore(elem) {
var hash = elem[hashKey];
if (!hash) {
hash = elem[hashKey] = {};
}
return hash;
}
},{"individual/one-version":13}],12:[function(require,module,exports){
(function (global){
'use strict';
/*global window, global*/
var root = typeof window !== 'undefined' ?
window : typeof global !== 'undefined' ?
global : {};
module.exports = Individual;
function Individual(key, value) {
if (key in root) {
return root[key];
}
root[key] = value;
return value;