forked from marcusphillips/react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathseptember_overhaul.diff
More file actions
1659 lines (1550 loc) · 69.6 KB
/
Copy pathseptember_overhaul.diff
File metadata and controls
1659 lines (1550 loc) · 69.6 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
diff --git a/lib/js_dot_standin/js.js b/lib/js_dot_standin/js.js
index 8f89a2f..a68ff30 100644
--- a/lib/js_dot_standin/js.js
+++ b/lib/js_dot_standin/js.js
@@ -26,6 +26,19 @@ var js = js || {
}
},
+ hasKeys: function(object){
+ for(var key in object){ return true; }
+ return false;
+ },
+
+ keys: function(object){
+ var keys = [];
+ for(key in object){
+ keys.push(key);
+ }
+ return keys;
+ },
+
map: function(collection, block){
js.errorIf(typeof collection.length === 'undefined', 'js.map is currently written for arrays only');
var result = [];
@@ -35,6 +48,13 @@ var js = js || {
return result;
},
+ reduce: function(collection, memo, callback){
+ js.map(collection, function(which, item){
+ memo = callback(which, item, memo);
+ });
+ return memo;
+ },
+
matchers: {
leadingOrTrailingSpace: /(^\s)|(\s$)/
},
@@ -70,6 +90,17 @@ var js = js || {
}
},
+ debugIf: function(condition){
+ if(condition){
+ debugger;
+ }
+ },
+
+ errorAndDebugIf: function(condition, message){
+ js.debuggerIf(condition);
+ js.errorIf(condition, message);
+ },
+
among: function(haystack, needle){
if(haystack.indexOf){
return haystack.indexOf(needle) !== -1;
@@ -100,10 +131,14 @@ var js = js || {
},
copy: function(seed){
- var copy = Object.prototype.toString.call(seed) === '[object Array]' ? [] : typeof seed === 'object' || typeof seed === 'function' ? {} : seed;
+ var copy = js.isArray(seed) ? [] : typeof seed === 'object' || typeof seed === 'function' ? {} : seed;
return js.extend(copy, seed);
},
+ isArray: function(input){
+ return Object.prototype.toString.call(input) === '[object Array]';
+ },
+
makeArrayLike: function(target){
var arrayMethods = 'concat join pop push reverse shift slice sort splice unshift'.split(' ');
for(var i = 0; i < arrayMethods.length; i++){
diff --git a/react.js b/react.js
index 25a2a8a..247da96 100644
--- a/react.js
+++ b/react.js
@@ -8,18 +8,21 @@
(function () {
+ /*
+ * Library-wide helpers
+ */
+
var debugging = true;
+ var noop = function(){};
+ var undefined; // safeguard, undefined can be overwritten in the global scope
+
var debug = function(){
- if(debugging && typeof console !== 'undefined' && console.warn && console.warn.apply){
+ if(debugging && console !== undefined && console.warn && console.warn.apply){
console.warn.apply(console, arguments);
}
};
- var doNotRecurse = {};
-
- var undefined;
-
var matchers = {
directiveDelimiter: /\s*,\s*/,
space: /\s+/,
@@ -28,8 +31,8 @@
isNumber: /\d+/
};
+ // returns a unique, consistent key for every node
var getNodeKey = function(node){
- // todo: without using .data(), IE copies expando properties over, breaking loop behaviors and other cloning operations. disable .data() long enough to write a test for this.
var key = $(node).data("reactKey");
if(!key){
key = js.util.unique('reactNode');
@@ -42,16 +45,6 @@
return (object.reactKey = object.reactKey || js.util.unique('reactObject'));
};
- var Fallthrough = function(key){ this.key = key; };
-
- var updateNodes = function(nodes, updateContext){
- for(var i = 0; i < nodes.length; i++){
- makeRnode(nodes[i]).update(updateContext);
- }
- };
-
- // todo: calling Array.prototype.slice.call on the results of a call to .querySelectorAll blows up in IE. revert this code to use that and write a test for it.
- // also see if there's a more efficient way to build an array other than iterating over the array like object
var makeArrayFromArrayLikeObject = function(arrayLikeObject){
var array = [];
for(var i = 0, length = arrayLikeObject.length; i < length ; i++){
@@ -60,27 +53,37 @@
return array;
};
+
+ /*
+ * Scope chains
+ */
+
+ // Scope chains are used to model namespace lookup behavior in templates
+ // all scope chains are built by calling emptyScopeChain.extend()
var emptyScopeChain = (function(){
+ // helper for creating the result (emptyScopeChain) and future scope chains returned from .extend()
var makeScopeChain = function(type, previousLink, additionalScope, options){
options = options || {};
+
var scopeChain = {
parent: previousLink,
scope: additionalScope,
type: type,
key: options.key,
prefix: options.prefix || '',
+// asdf this shouldn't need a prefix
anchorKey: type === 'anchor' ? options.key : (previousLink||{}).anchorKey,
- extend: function(type, additionalScope, options){
- return makeScopeChain(type, scopeChain, additionalScope, options);
- },
-
contains: function(scope){
return scopeChain.scope === scope || scopeChain.parent && scopeChain.parent.contains(scope);
},
- extendMany: function(type, scopes, options){
+ extend: function(type, additionalScope, options){
+ return makeScopeChain(type, scopeChain, additionalScope, options);
+ },
+
+ extendWithMany: function(type, scopes, options){
scopes = scopes || [];
var lastLink = scopeChain;
for(var which = 0; which < scopes.length; which++){
@@ -89,91 +92,81 @@
return lastLink;
},
- extendForAnchorNames: function(names){
- names = names || [];
- var scopes = [];
- for(var whichToken = 0; whichToken < names.length; whichToken++){
- var scopeKey = names[whichToken];
- js.errorIf(!react.scopes[scopeKey], 'could not follow anchored directive, nothing found at react.scopes.'+scopeKey);
- scopes.push(react.scopes[scopeKey]);
- }
- return scopeChain.extendMany('anchor', scopes, {key: scopeKey});
- },
-
- observe: function(key, directive){
- var object = scopeChain.scope;
- // todo: scope observers per node-object anchoring, for easy cleanup of memory references
- react.nodes[directive.rnode.getKey()] = directive.rnode.node;
- var observations = directive.rnode.node['directive ' + directive.index + ' observes'] = directive.rnode.node['directive ' + directive.index + ' observes'] || [];
- observations.push({object: object, key: key});
- object.observers = object.observers || {};
- object.observers[key] = object.observers[key] || {};
- object.observers[key][directive.rnode.getKey() + ' ' + directive.index + ' ' + scopeChain.prefix] = true;
- },
-
- lookup: function(key, options){
- options = options || {};
+ // provides the value at a given key by looking through the scope chain from this leaf up
+ detailedLookup: function(key){
+ key = key.toString();
if(key[0] === '!'){
var negate = true;
key = key.slice(1);
}
- if (matchers.isString.test(key)) {
- return key.slice(1, key.length-1);
+ // the details object will contain all interesting aspects of this lookup
+ // potentialObservers will hold the scopeChain/key pairs that may need to be bound for future updates
+ var details = {potentialObservers: []};
+ // extend details must be called on any return values, since it handles the final step of negation
+ var extendDetails = function(moreDetails){
+ for(var key in moreDetails||{}){
+ details[key] = key === 'potentialObservers' ? details.potentialObservers.concat(moreDetails.potentialObservers || []) : moreDetails[key];
+ }
+ details.value = negate ? ! details.value : details.value;
+ return details;
+ };
+
+ // all lookups fail in the empty scope chain
+ if(scopeChain === emptyScopeChain){
+ return extendDetails({failed:true});
}
- // todo: clean up any pre-existing observers
+ if (matchers.isString.test(key)) {
+ js.errorIf(negate, 'You can\'t negate literals using the exlamation point');
+ return extendDetails({value: key.slice(1, key.length-1)});
+ }
var path = key.split('.');
+ // base key is the first segment of a path that uses dot access. It's is the only segment that will be taken from the current scope chain
var baseKey = path.shift();
- var details = {failed: true};
- // todo: write a test to verify that responses to change events don't result in new observers
- // todo: test that we don't observe binding objects
- if(scopeChain.scope[baseKey] instanceof Fallthrough){
- details = scopeChain.parent.lookup([scopeChain.scope[baseKey].key].concat(path).join('.'), js.extend({details:true}, options));
- }else if(baseKey in scopeChain.scope){
- if(scopeChain.anchorKey && options.listeningDirective && !options.suppressObservers){
- scopeChain.observe(baseKey, options.listeningDirective);
- }
- var prefix = baseKey + '.';
- var subObject = scopeChain.scope;
- var value = subObject[baseKey];
- while(path.length){ // one for each segment of the dot acess
- subObject = value;
- if(subObject === undefined || subObject === null){
- debug('Could not find a valid subscope at '+prefix+' for '+key+' on ', scopeChain.scope);
- return options.details ? details : subObject;
- }
- if(scopeChain.anchorKey && !options.suppressObservers && options.listeningDirective){
- emptyScopeChain.extend('dotAccess', subObject, {
- prefix: prefix,
- anchorKey: scopeChain.anchorKey
- }).observe(path[0], options.listeningDirective);
- }
- prefix = prefix + path[0] + '.';
- value = subObject[path.shift()];
+ var value = scopeChain.scope[baseKey];
+
+ // a Fallthrough object remaps the baseKey to a new baseKey in the previous scope
+ if(value instanceof Fallthrough){
+ return extendDetails(scopeChain.parent.detailedLookup( [value.key].concat(path).join('.') ));
+ }
+
+ details.potentialObservers.push({scopeChain: scopeChain, key: baseKey});
+
+ // recurse onto the parent scopeChain if the lookup fails at this level
+ if(! (baseKey in scopeChain.scope) ){
+ return extendDetails(scopeChain.parent.detailedLookup(key));
+ }
+
+ details.matchingBaseObject = scopeChain.scope;
+
+ // for dot access
+ if(path.length){
+ if(value === undefined || value === null){
+ debug('Could not find '+key+' on a null or undefined object at path '+prefix+baseKey+' from', scopeChain.scope);
+ return extendDetails();
}
- details = {
- matchingScopeChain: scopeChain,
- matchingBaseObject: subObject,
- baseKey: baseKey,
- negated: negate,
- value: typeof value === 'function' ? value.call(subObject||{}) : value
- };
- details.value = (negate ? ! details.value : details.value);
- }else if(!scopeChain.parent.isEmpty){
- details = scopeChain.parent.lookup(key, js.extend({details:true}, options));
+ return extendDetails(emptyScopeChain.extend('dotAccess', value, {
+ prefix: scopeChain.prefix + baseKey + '.',
+ anchorKey: scopeChain.anchorKey
+ }).detailedLookup(path.join('.')));
}
- return options.details ? details : details.value;
+
+ // functions are called before being returned
+ value = typeof value === 'function' ? value.call(scopeChain.scope) : value;
+
+ return extendDetails({value: value});
},
+ lookup: function(){
+ return scopeChain.detailedLookup.apply(scopeChain, arguments).value;
+ },
+
+ // provides a description of the scope chain in array format, optimized for viewing in the console
describe: function(){
- var link = scopeChain;
- var scopeChainDescription = [];
- while(link){
- scopeChainDescription.push(['scope: ', link.scope, ', type of scope shift: ' + link.type + (link.key ? ' (key: '+link.key+')': '') + (link.anchorKey ? ', anchored to: '+link.anchorKey+')': '')]);
- link = link.parent;
- }
- return scopeChainDescription;
+ return [
+ ['scope: ', scopeChain.scope, ', type of scope shift: ' + scopeChain.type + (scopeChain.key ? ' (key: '+scopeChain.key+')': '') + (scopeChain.anchorKey ? ', anchored to: '+scopeChain.anchorKey+')': '')]
+ ].concat(scopeChain.parent ? scopeChain.parent.describe() : []);
}
};
@@ -181,88 +174,54 @@
return scopeChain;
};
- var emptyScopeChain = makeScopeChain(undefined, undefined, {type:'empty'});
- emptyScopeChain.isEmpty = true;
- emptyScopeChain.lookup = function(){ js.error('cannot lookup in the empty scope chain'); };
+ var emptyScopeChain = makeScopeChain('empty');
return emptyScopeChain;
}());
- var globalScope = {};
- var globalScopeChain = emptyScopeChain.extend('global', globalScope);
+ // Fallthroughs provide a mechanism for binding one key in a scope to the value at another key
+ var Fallthrough = function(key){ this.key = key; };
- var react = {
- _enqueueNodes: function(newNodes){
- this.nodesToUpdate.push.apply(this.nodesToUpdate, newNodes);
- for(var whichNode = 0; whichNode < newNodes.length; whichNode++){
- var nodeKey = getNodeKey(newNodes[whichNode]);
- delete this.bequeathedScopeChains[nodeKey];
- delete this.loopItemTemplates[nodeKey];
- }
- },
+ /*
+ * Library interface
+ */
- _removeNodes: function(newNodes){
- var nodeKeysToRemove = {};
- for(var whichNode = 0; whichNode < newNodes.length; whichNode++){
- var nodeKey = getNodeKey(newNodes[whichNode]);
- nodeKeysToRemove[nodeKey] = true;
- delete this.bequeathedScopeChains[nodeKey];
- delete this.loopItemTemplates[nodeKey];
- }
- var newNodesToUpdate = js.filter(this.nodesToUpdate, function(which, each){
- return !nodeKeysToRemove[getNodeKey(each)];
- });
- this.nodesToUpdate.splice(0, this.nodesToUpdate.length);
- this.nodesToUpdate.push.apply(this.nodesToUpdate, newNodesToUpdate);
- },
+ var react = {
nodes: {},
scopes: {},
- debug: function(setting){
- if(typeof setting === 'undefined'){ setting = true; }
- debug = setting;
+ setDebugging: function(setting){
+ if(setting === undefined){ setting = true; }
+ debugging = setting;
},
+ // for giving scope objects meaningful names, which appear in the anchor directives on nodes. not yet ready for external consumption
name: function(name, object){
+ js.errorIf(object.reactKey, 'You tried to name a scope object that already had a name');
+ object.reactKey = name;
this.scopes[name] = object;
},
+ // convenience method for setting object values and automatically calling changed on them
set: function(object, key, value){
object[key] = value;
this.changed(object, key);
},
- changed: function(object, key){
- // if no key is supplied, check every key
- if(arguments.length < 2){
- for(key in object){
- this.changed(object, key);
- }
- // todo: this still won't work for arguments lists
- if(Object.prototype.toString.call(object) === '[object Array]'){
- this.changed(object, 'length');
- }
- return;
- }
-
- // if there are no observers for the supplied key, do nothing
- if(!object || !object.observers || !object.observers[key]){ return; }
-
- for(var listenerString in object.observers[key]){
- makeListener(object, key, listenerString).check();
- }
+ // allows user to notify react that an object's property has changed, so the relevant nodes may be updated
+ changed: function(){
+ makeOperation().changed.apply({}, arguments).run();
},
- update: function(/*[node, scope],*/ options){
+ update: function(/*[node, scope,]*/ options){
options = options || {};
if(options.nodeType || (options instanceof jQuery)){
// detect argument signature of (node, scope)
- options = {
+ options = js.extend({
node: arguments[0],
scope: arguments[1]
- };
- js.extend(options, arguments[2] || {});
+ }, arguments[2] || {});
}
if(options.node instanceof jQuery){
if(options.node.length !== 1){
@@ -270,7 +229,19 @@
}
options.node = options.node[0];
}
- return makeRnode(options.node).updateTree(options);
+
+ js.errorIf(options.scope && options.scopes, 'you must supply only one set of scopes');
+
+ var scopes = options.scope ? [options.scope] : options.scopes ? options.scopes : [];
+ if(options.anchor){
+ react.anchor({node: options.node, scopes:scopes});
+ scopes = [];
+ }
+
+ var operation = makeOperation();
+ operation.$(options.node).directives[options.fromDirective||'before'].injectScopes('updateInputs', scopes).dirtyBranch();
+ operation.run();
+ return options.node;
},
anchor: function(options){
@@ -286,7 +257,7 @@
this.nodes[getNodeKey(node)] = node;
// todo: clean up any links elsewhere (like listeners) that are left by potential existing anchors
- makeRnode(node).directives.set('anchored', ['anchored'].concat(js.map(scopes, function(i, scope){
+ makeOperation().$(node).directives.set('anchored', ['anchored'].concat(js.map(scopes, function(i, scope){
var scopeKey = getScopeKey(scopes[i]);
react.scopes[scopeKey] = scopes[i];
return scopeKey;
@@ -304,536 +275,655 @@
};
+ var commands = react.commands = {
+ scopes: react.scopes
+ };
- var commands = react.commands = js.create(react, {
/*
- * when a command runs, it will have a 'this' scope like the following (arrows indicate prototype relationships)
- *
- * react {
- * }
- *
- * ^
- * |
- * commands {
- * command handler definitions
- * lookup(key)
- * }
- *
- * ^
- * |
- * // a new processing scope is created for each node to be updated
- * nodeContext {
- * node
- * scopeChain
- * }
+ * Operation
*/
- lookup: function(key, options){
- options = options || {};
- options.listeningDirective = makeRnode(this.node).directives[this.directiveIndex];
- options.suppressObservers = 'suppressObservers' in options ? options.suppressObservers : this.suppressObservers;
+ // An operation provides a shared context where complex interactions may rely upon shared state
- return this.scopeChain.lookup(key, options);
- },
+ var makeOperation = function(){
+ // within an operation, all $node objects are cached to maintain object-identicality across calls to $()
+ var $nodes = {};
+ var proxies = [];
- anchored: function(token){
- if(!this.scopes[token]){
- debug('anchored directive failed to find a scope for the key "'+key+'"');
- return;
- }
- this.pushScope('anchor', this.scopes[token], {key:token});
- },
+ // to ensure root-first processing order, we earmark each directive we plan to follow, then follow them all during the run() step
+ var branchesToConsider = {};
+ var directivesToConsider = {};
+ var consideredDirectives = {};
- within: function(key){
- var scope = this.lookup(key);
- if(!scope){
- debug('within directive failed to find a scope for the key "'+key+'"');
- return;
- }
- this.pushScope('within', scope, {key:key});
- },
+ /*
+ * Proxy
+ */
- contain: function(key){
- // using innerHTML to clear the node because the jQuery convenience functions unbind event handlers. This would be an unexpected side effect for most React user consumption cases.
- this.node.innerHTML = '';
- var insertion = this.lookup(key);
- // if the insertion is a node, use the dom appending method, but insert other items as text
- if(insertion && insertion.nodeType){
- jQuery(this.node).append(insertion);
- this._removeNodes(makeRnode(insertion).getReactNodes());
- } else {
- jQuery(this.node).text(insertion);
- }
- },
-
- classIf: function(conditionKey, nameKey){
- this.node.classIfs = this.node.classIfs || {};
- var condition = this.lookup(conditionKey);
- var className;
- var persistence = conditionKey + ' ' + nameKey;
- if(condition){
- className = this.lookup(nameKey);
- if(className){
- $(this.node).addClass(className);
- this.node.classIfs[persistence] = className;
- }
- } else {
- className = this.node.classIfs[persistence] || this.lookup(nameKey);
- if(className){
- $(this.node).removeClass(className);
- delete this.node.classIfs[persistence];
- }
- }
- },
+ // A proxy provides an interface for the observer relationship between any JS object and the nodes/directives observing it's properties
- _createItemNodes: function(directiveMaker){
- var $loopChildren = jQuery(this.node).children();
- js.errorIf($loopChildren.length < 2, 'looping nodes must contain at least 2 children - one item template and one results container');
- var $itemTemplate = $loopChildren.first();
- //js.errorIf(makeRnode($itemTemplate[0]).directives[0].join(' ') !== 'itemTemplate', 'the item template must declare itself with an item directive');
- $itemTemplate.addClass('reactItemTemplate');
- this.loopItemTemplates[getNodeKey($itemTemplate[0])] = $itemTemplate[0];
- var $resultsContainer = $($loopChildren[1]);
- var $resultsContents = $resultsContainer.children();
+ var makeProxy = function(object){
- // todo: ignore binding scopes when looking for scope to iterate over
- var collection = this.scopeChain.scope;
- // todo: don't allow looping over static native objects (like strings - this is almost certainly an error)
- js.errorIf(collection === null || collection === undefined, 'The loop command expected a collection, but instead encountered '+collection);
- if(this.scopeChain.anchorKey && !this.suppressObservers){
- // todo: optimize. this is a shortcut - it simply puts a listener on the length property that results in a complete re-render of the looping directive if ever a change in length is noticed
- this.scopeChain.observe('length', makeRnode(this.node).directives[this.directiveIndex]);
- }
+ var proxy = {
+ // writes an association between a directive and a property on an object by annotating the object
+ observe: function(key, directive, prefix){
+ directive.$node.store();
+ makeObserver(key, directive.$node.key, directive.index, prefix).write();
+ },
- var itemNodes = [];
- for(var i = 0; i < collection.length; i++){
- var itemNode = $resultsContents[i];
- if(!itemNode){
- itemNode = $itemTemplate.clone().removeClass('reactItemTemplate')[0];
- // todo: implement bindings as key aliases
- js.errorIf(matchers.space.test(i), 'looping not currently supported over colletions with space-filled keys'); // todo: make this even more restrictive - just alphanumerics
- var itemDirective = directiveMaker(i);
- makeRnode(itemNode).directives.prepend(itemDirective);
- this._enqueueNodes(makeRnode(itemNode).getReactNodes());
+ changed: function(keys){
+ // if no key is supplied, check every key
+ if(!object || !object.observers){ return; }
+ keys = (
+ js.isArray(keys) ? keys :
+ keys !== undefined ? [keys] :
+ js.keys(object).concat('length' in object && !object.propertyIsEnumerable('length') ? ['length'] : [])
+ );
+
+ // we first need to collect all the observers of the changed keys
+ for(var whichKey = 0; whichKey < keys.length; whichKey++){
+ key = keys[whichKey];
+ if(!object.observers[key]){ continue; } // if there are no observers for the supplied key, do nothing
+ for(var keyObserverString in object.observers[key]){
+ makeObserver(key, keyObserverString).dirty();
+ }
+ }
}
- itemNodes.push(itemNode);
- }
- if(collection.length !== $resultsContents.length){
- // we set innerHTML here to prevent jQuery fron detaching all event handlers (automatic in an .html() call)
- $resultsContainer[0].innerHTML = '';
- $resultsContainer.html(itemNodes);
- }
- },
+ };
- withinEach: function(){
- // todo: return here (and everywhere else) if collection is undefined. test for this
- this._createItemNodes(function(index){
- return ['withinItem', index];
- });
- },
+ var cachedObservers = {};
+ var makeObserver = function(propertyKey, nodeKey, directiveIndex, prefix){
+ if(arguments.length === 2){
+ var tokens = observerString.split(matchers.space);
+ nodeKey = tokens[0];
+ directiveIndex = tokens[1];
+ prefix = tokens[2];
+ }
- withinItem: function(key){
- // todo: add a rule to only allow getting items from last scope (check if key < scope.length?)
- // todo: add a rule to make sure the last scope object is an array
- js.errorIf(this.scopeChain.scope.length-1 < +key, 'Tried to re-render a node for an index the no longer exists');
- // todo: want to raise an error including link to this.scopeChain.scope - write an error helper
- js.errorIf(!this.scopeChain.scope[key], 'Could not find anything at key '+key+' on the scope object');
- // todo: might be a problem that using the within() as a helper will give the scope a type of 'within'
- this.within(key);
- },
+ var observerKey = propertyKey+' '+nodeKey+' '+directiveIndex+' '+prefix;
+ if(cachedObservers[observerKey]){ return cachedObservers[observerKey]; }
- 'for': function(keyAlias, valueAlias){
- var aliases = arguments;
- // todo: return here (and everywhere else) if collection is undefined. test for this
- this._createItemNodes(function(index){
- return ['bindItem', index].concat(Array.prototype.slice.call(aliases));
- });
- },
+ var observer = {
+ object: object,
- bindItem: function(key, keyAlias, valueAlias){
- if(valueAlias === undefined){
- valueAlias = keyAlias;
- keyAlias = undefined;
- }
+ directive: $(react.nodes[nodeKey]).directives[directiveIndex],
- // set up an item scope to be applied for each item
- // a new scope will be created with bindings for valueAlias and optionally for keyAlias
- var itemBindings = {};
- if(keyAlias !== undefined){
- itemBindings[keyAlias] = key;
- }
- // todo: don't make this a fallthrough - create an explicit binding to the previous array scope object
- itemBindings[valueAlias] = new Fallthrough(key);
+ key: observerKey,
- this.pushScope('bindItem', itemBindings, {key:key});
- },
+ write: function(){
+ object.observers = object.observers || {};
+ object.observers[key] = object.observers[key] || {};
+ object.observers[key][observerKey] = true;
+ },
- _conditionalShow: function(conditional){
- jQuery(this.node)[conditional ? 'show' : 'hide']();
- },
+ dirty: function(){
+ if(observer.isDirty){ return; }
+ observer.isDirty = true;
+ observer.directive.dirtyObserver(observer);
+ },
- 'if': function(condition){
- var conditional = this.lookup(condition);
- // this is technical debt, but will go away in the refactor. the suppressObservers flag happens to be useful in this case to detect when we are only building a scope chain. when that happens, we also don't want to have these side effects on the classes either
- if(!this.suppressObservers){
- $(this.node)[conditional ? 'removeClass' : 'addClass']('reactConditionallyHidden');
- }
- if(!conditional){
- this.pushScope('doNotRecurse', doNotRecurse);
- }
- this._conditionalShow(conditional);
- },
+ isPertinant: function(){
+ var details = observer.directive.getScopeChain().detailedLookup(prefix + propertyKey);
+ // ignore the object if it's not in the same path that lead to registration of the observer
+ return details.matchingBaseObject === object || details.failed && observer.directive.getScopeChain().contains(object);
+ }
+ };
- showIf: function(condition){
- this._conditionalShow(this.lookup(condition));
- },
+ return cachedObservers[observerKey] = observer;
+ };
- visIf: function(condition){
- jQuery(this.node).css('visibility', this.lookup(condition) ? 'visible' : 'hidden');
- },
+ proxies.push(proxy);
+ return proxy;
+ };
- attr: function(name, value){
- js.errorIf(arguments.length !== 2, 'the attr directive requires 2 arguments');
+ // Overriding jQuery to provide supplemental functionality to DOM node wrappers
+ // Within the scope of makeOperation, all calls to $() return a customized jQuery object. For access to the original, use jQuery()
+ var $ = function(node){
+ js.errorIf(arguments.length !== 1 || node.nodeType !== 1 || js.isArray[arguments[0]] || arguments[0] instanceof jQuery, 'overridden $ can only accept one input of type DOM node');
+ if($nodes[getNodeKey(node)]){ return $nodes[getNodeKey(node)]; }
+
+ var $node = js.create(jQuery(node), {
+ key: getNodeKey(node),
+
+ wrappedParent: function(){
+ return (
+ ! $node.parent()[0] ? null :
+ $node.parent()[0] === document ? null :
+ $($node.parent()[0])
+ );
+ },
- name = this.lookup(name);
- value = this.lookup(value);
+ store: function(){
+ react.nodes[$node.key] = $node.node;
+ },
- if(!js.among(['string', 'number', 'undefined'], typeof name)){
- js.log('bad attr name: ', name);
- js.error('expected attr name token ' + name + ' to resolve to a string, a number, null, or undefined, not ' + typeof name);
- }else if(!js.among(['string', 'number', 'undefined'], typeof value)){
- js.log('bad attr value: ', value);
- js.error('expected attr value token ' + value + ' to resolve to a string, a number, null, or undefined, not ' + typeof value);
- }
+ // note: getReactNodes() only returns the operative node and nodes that have a 'react' attribute on them. any other nodes of interest to react (such as item templates that lack a 'react' attr) will not be included
+ getSelfAndReactDescendants: function(){
+ return js.map([node].concat(makeArrayFromArrayLikeObject(node.querySelectorAll('[react]'))), function(which, node){
+ return $(node);
+ });
+ }
- jQuery(this.node).attr(name, value);
- },
+ });
- attrIf: function(condition, name, value){
- if(this.lookup(condition)){
- $(this.node).attr(this.lookup(name), this.lookup(value));
- } else {
- $(this.node).removeAttr(this.lookup(name));
- }
- },
+ // provides an object representing the directive itself (for example, "contain user.name")
+ var makeDirective = function(index, tokens, parent){
+ var dirtyObservers = {};
+ var reportedAsClean = false;
+ var isDirty = false;
+ var isContageous = false;
+ var isDead = false;
+ var isFollowed = false;
+ var scopeChain;
+ var scopeInjectionArgLists = [];
+
+ var directive = js.create(commands, {
+ $: $,
+ $node: $node,
+ node: node,
+ key: $node.key+' '+index,
+ isDirective: true,
+ index: index,
+ command: tokens[0],
+ inputs: tokens.slice(1),
+
+ lookup: function(key){
+ var details = directive.getScopeChain().detailedLookup(key);
+ for(var i = 0; i < details.potentialObservers.length; i++){
+ var potentialObserver = details.potentialObservers[i];
+ if(directive.isDirty() && potentialObserver.scopeChain.anchorKey){
+ makeProxy(potentialObserver.scopeChain.scope).observe(potentialObserver.key, directive, scopeChain.prefix);
+ }
+ }
+ return details.value;
+ },
- checkedIf: function(condition){
- $(this.node).attr('checked', this.lookup(condition));
- }
+ resetScopeChain: function(){
+ scopeChain = emptyScopeChain;
+ },
- });
+ injectScopes: function(type, scopes){
+ scopeInjectionArgLists = scopeInjectionArgLists.concat(js.map(scopes, function(which, scope){
+ return [type, scope];
+ }));
+ return directive;
+ },
- // a reactnode (rnode) is a wrapper for dom nodes that provides supplemental functionality
- var makeRnode = function(node){
+ pushScope: function(type, scope, options){
+ scopeChain = directive.getScopeChain().extend(type, scope, options);
+ },
- var rnode = {
+ getScopeChain: function(){
+ return scopeChain = js.reduce(scopeInjectionArgLists, scopeChain || directive.getParent().getScopeChain(), function(which, scopeChainArguments, memo){
+ return memo.extend.apply(memo, scopeChainArguments);
+ });
+ },
+
+ getScope: function(){
+ return directive.getScopeChain().scope;
+ },
+
+ // a branch of the directive tree is 'dead' if no child directives (and itself) should be followed
+ dead: function(){
+ isDead = true;
+ return directive;
+ },
+
+ // a directive is 'dirty' if it the currently rendered output needs to be updated based on the new inputs
+ dirty: function(){
+ js.errorIf(reportedAsClean, 'internal error: tried to set \'dirty\' property after isDirty() returned false');
+ isDirty = true;
+ directive.consider();
+ return directive;
+ },
+
+ // a directive is contageous if its 'dirty' value propagates to children
+ contageous: function(){
+ isContageous = true;
+ return directive;
+ },
+
+ // todo: this might not be necessary - contagous should perhaps just do this
+ dirtyBranch: function(){
+ directive.dirty().contageous().considerBranch();
+ },
+
+ dirtyObserver: function(observer){
+ js.errorIf(reportedAsClean, 'internal error: tried to add a dirty observer after isDirty() returned false');
+ dirtyObservers[observer.key] = observer;
+ directive.consider();
+ },
+
+ isDirty: function(){
+ if(directive.getParent().doesInfect()){ isDirty = true; }
+ for(var which in dirtyObservers){
+ if(dirtyObservers[which].isPertinent()){ isDirty = true; break; }
+ }
+ reportedAsClean = reportedAsClean || isDirty === false;
+ return isDirty;
+ },
+
+ doesInfect: function(){
+ return directive.follow(), isDirty && isContageous;
+ },
+
+ consider: function(){
+ directivesToConsider[directive.key] = directive;
+ },
+
+ considerBranch: function(){
+ branchesToConsider[directive.key] = directive;
+ },
+
+ ifDirty: function(callback){
+ didCallIfDirty = true;
+ if(directive.isDirty() && callback){
+ callback.apply(this);
+ }
+ },
+
+ // the directive's command (for example, 'contain') will be executed with a 'this' context of that directive
+ follow: function(){
+ js.errorIf(!isRunning, 'An internal error occurred: someone tried to .follow() a directive outside of operation.run()');
+ describeErrors(function(){
+ if(isFollowed){ return; }
+ isFollowed = true;
+ directive.getParent().follow();
+ js.errorIf(!commands[directive.command], directive.command+' is not a valid react command');
+ commands[directive.command].apply(directive, directive.inputs);
+ js.errorIf(!didCallIfDirty, 'all directives must run a section of their code in a block passed to this.ifDirty(), even if the block is empty. Put any code that will mutate state there, and leave code that manipulates scope chains, etc outside of it.');
+ if(branchesToConsider[directive.key]){
+ var $nodes = $node.getSelfAndReactDescendants();
+ for(var which = 0; which < $nodes.length; which++){
+ $nodes[which].directives.after.consider();
+ }
+ }
+ });
+ },
+
+ getParent: function(){
+ if(parent){ return parent; }
+ var previousParent = 'unmatchable', repeatLimit = 10000;
+ while(parent !== previousParent){
+ previousParent = parent;
+ parent && parent.follow();
+ js.errorIf(!repeatLimit--, 'You\'ve done something really crazy in your directives. Probably mutated state in a way that changes the dom structure. Don\'t do that.');
+ parent = $node.wrappedParent() ? $node.wrappedParent().directives.after : nullDirective;
+ }
+ return parent;
+ },
- node: node,
+ setParent: function(directive){
+ parent = directive;
+ },
- getKey: function(){
- return getNodeKey(node);
- },
+ toString: function(){
+ return [directive.command].concat(directive.inputs).join(' ');
+ }
- // note: getReactNodes() only returns the operative node and nodes that have a 'react' attribute on them. any other nodes of interest to react (such as item templates that lack a 'react' attr) will not be included
- getReactNodes: function(){
- return [node].concat(makeArrayFromArrayLikeObject(node.querySelectorAll('[react]')));
- },
+ });
- getParent: function(updateContext){
- var ancestor = $(node).parent()[0];
- var repeatLimit = 1000;
- while(repeatLimit--){
- if(!ancestor || ancestor === document){
- return false;
- } else if (
- ancestor === updateContext.root ||
- ancestor.getAttribute('react') ||
- updateContext.bequeathedScopeChains[getNodeKey(ancestor)] || // todo: what's this cover?
- updateContext.loopItemTemplates[getNodeKey(ancestor)] // todo: I don't think we need this now that it gets a special class attached to it
- ){
- return ancestor;
+ var describeErrors = function(callback){
+ try{ callback(); } catch (error){
+ js.log('Failure during React update: ', {
+ 'original error': error,
+ 'original stack': error.stack && error.stack.split ? error.stack.split('\n') : error.stack,
+ 'while processing node': node,
+ 'index of failed directive': index,
+ 'directive call': directive.command+'('+directive.inputs.join(', ')+')',
+ 'scope chain description': directive.getScopeChain().describe(),
+ '(internal scope chain object) ': directive.getScopeChain()
+ });
+ throw error;
}
- ancestor = $(ancestor).parent()[0];
- }
- js.error('rnode.getParent() broke');
- },
+ };
- updateGivenScopeChain: function(scopeChain, updateContext, fromDirective){
- var nodeKey = rnode.getKey();
- var directives = rnode.directives;
+ return directive;
+ };
- if(directives.anchored){
- scopeChain = scopeChain.extendForAnchorNames(directives.anchored.inputs);
- }
+ var nullDirective = makeDirective(null, [], null);
+ nullDirective.follow = noop;