forked from hirokidaichi/brook
/
brook.js
1371 lines (1298 loc) · 39.2 KB
/
brook.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
/**
@fileOverview brook
@author daichi.hiroki<hirokidaichi@gmail.com>
*/
/**
@name brook
@namespace brookライブラリ群のルートとなる名前空間です。promiseの生成処理を持っています。
*/
Namespace('brook').define(function(ns){
var VERSION = "0.01";
/**
* @class brook.promiseで生成されるインスタンスのインナークラス
* @name _Promise
* @memberOf brook
* @description
* 実行する前の次の処理をもつオブジェクトです。
* Promiseインスタンスはbind関数で結合する事が出来ます。連続した非同期/同期の処理をデータの流れとして抽象化して結合する事が出来ます。
* subscribe/forEach/runなどの処理を実行するまでは、結合した処理は実行される事はありません。
* また、コンストラクタは公開されていません。brook.promiseがファクトリとなっています。
*/
var Promise = function(next){
this.next = next || function(next,val){ return next(val); };
};
(function(proto){
/**#@+
* @methodOf brook._Promise.prototype
*/
/**
* @name concat
* @param {Promise} promise
*/
proto.concat = function(promise){
var _before = this;
var after = promise;
var next = function(n,val){
return _before.subscribe( promise.ready(n),val);
};
return new Promise(next);
};
/**
* @name bind
* @param {Promise} promise
*/
proto.bind = function(){
var r = this;
for( var i = 0,l = arguments.length;i<l;i++){
var s = arguments[i];
s = ( s instanceof Promise) ? s : promise( s );
r = r.concat( s );
}
return r;
};
/**
* @name ready
* @param {Promise} promise
*/
proto.ready = function(n){
var proc = this.next;
return function(val){
return proc(n,val);
};
};
/**
* @name run
* @param {Promise} promise
*/
proto.run = function(val){
this.subscribe( undefined , val );
};
/**
* @name subscribe
* @param {Promise} promise
*/
proto.subscribe = function(next,val){
var next = next ? next : function(){};
if( !this.errorHandler )
return this.next(next,val);
try {
this.next(next,val);
}
catch(e){
this.onError(e);
}
};
/**
* @name forEach
* @param {Promise} promise
*/
proto.forEach = proto.subscribe;
/**
* @name setErrorHandler
* @param {Promise} promise
*/
proto.setErrorHandler = function(promise){
this.errorHandler = promise;
};
/**
* @name onError
*/
proto.onError = function(e){
(this.errorHandler||new Promise).subscribe(function(){},e);
};
/**#@-*/
})(Promise.prototype);
/**
* @name promise
* @function
* @memberOf brook
* @param {function} next
* @return {Promise}
* @description
* プロミスを生成するファクトリメソッドです。nextは、さらに次の処理を第一引数に受け取り、第二引数に前回の処理の結果を受け取ります。
* 引数が無い場合は、データをそのまま次の処理に送るpromiseを生成します。
* @example
* var p = ns.promise(function(next,value){ next(value+1)});
* @example
* var p = ns.promise();
*/
var promise = function(next){return new Promise(next)};
ns.provide({
promise : promise,
VERSION : VERSION
});
});
/**
@fileOverview brook.util
@author daichi.hiroki<hirokidaichi@gmail.com>
*/
/**
@name brook.util
@namespace details here
*/
Namespace('brook.util')
.use('brook promise')
.define(function(ns){
/**#@+
* @methodOf brook.util
*/
/**
* @name mapper
* @param {Promise} promise
*/
var mapper = function(f){
return ns.promise(function(next,val){
return next(f(val));
});
};
/**
* @name filter
* @param {Promise} promise
*/
var filter = function(f){
return ns.promise(function(next,val){
if( f(val) ) return next(val);
});
};
/**
* @name takeBy
*/
var takeBy = function(by){
var num = 1;
var queue = [];
return ns.promise(function(next,val){
queue.push( val );
if( num++ % (by) ==0){
next(queue);
queue = [];
}
});
};
/**
* @name scatter
*/
var scatter = function(){
return ns.promise(function(next,val){
for( var i = 0, l = val.length;i<l;i++){
next(val[i]);
}
});
};
/**
* @name wait
*/
var wait = function(msec){
var msecFunc = ( typeof msec == 'function' )
? msec : function(){return msec};
return ns.promise(function(next,val){
setTimeout(function(){
next(val);
},msecFunc());
});
};
var waitUntil = function(f){
var p = function(next,val){
if( f() ){
return next(val);
}
setTimeout(function(){ p(next,val)},100);
};
return ns.promise(p);
};
var debug = function(sig){
var sig = sig ? sig : "debug";
return ns.promise(function(next,val){
console.log(sig + ":",val);
return next( val );
});
};
var cond = function(f,promise){
return ns.promise(function(next,val){
if( !f(val) )
return next( val );
promise.subscribe(function(val){
return next( val );
},val);
});
};
var match = function(dispatchTable){
return ns.promise(function(next,val){
var promise = dispatchTable[val] || dispatchTable['__default__'] || ns.promise();
promise.subscribe(function(v){
next(v);
},val);
});
};
var LOCK_MAP = {};
var unlock = function(name){
return ns.promise(function(next,val){
LOCK_MAP[name] = false;
next(val);
});
};
var lock = function(name){
var tryLock = (function(next,val){
if( !LOCK_MAP[name] ){
LOCK_MAP[name] = true;
return next(val);
}
setTimeout(function(){
tryLock(next,val);
},100);
});
return ns.promise(tryLock);
};
var from = function(value){
if( value.observe ){
return ns.promise(function(next,val){
value.observe(ns.promise(function(n,v){
next(v);
}));
});
}
return ns.promise(function(next,val){
next(value);
});
};
var EMIT_INTERVAL_MAP = {};
var emitInterval = function(msec, name){
var msecFunc = ( typeof msec == 'function' )
? msec : function(){return msec};
return ns.promise(function(next,val){
var id = setInterval(function(){
next(val);
},msecFunc());
if (name) {
EMIT_INTERVAL_MAP[name] = id;
}
});
};
var stopEmitInterval = function(name) {
return ns.promise(function(next, value) {
clearInterval(EMIT_INTERVAL_MAP[name]);
next(value);
});
};
/**#@-*/
ns.provide({
mapper : mapper,
filter : filter,
scatter : scatter,
takeBy : takeBy,
wait : wait,
cond : cond,
match : match,
debug : debug,
lock : lock,
unlock : unlock,
from : from,
waitUntil : waitUntil,
emitInterval: emitInterval,
stopEmitInterval: stopEmitInterval
});
});
/**
@fileOverview brook.lambda
@author daichi.hiroki<hirokidaichi@gmail.com>
*/
/**
@name brook.lambda
@namespace 簡単に小さな関数を作る為のテンプレートを提供します。
*/
Namespace('brook.lambda')
.define(function(ns){
var cache = {};
var hasArg = function(expression){
return expression.indexOf('->') >= 0;
};
var parseExpression = function(expression){
var fixed = hasArg( expression ) ? expression : "$->"+expression;
var splitted = fixed.split("->");
var argsExp = splitted.shift();
var bodyExp = splitted.join('->');
return {
argumentNames : argsExp.split(','),
body : hasArg(bodyExp) ? lambda( bodyExp ).toString() : bodyExp
};
};
/**
* @name lambda
* @function
* @memberOf brook.lambda
* @param {string} expression
* @return {function}
* @description
* 文字列表現を受け取り、シンプルな関数を生成します。
* @example
* var f = lambda('$ * $'); // 第一引数を二乗する関数
* @example
* var f = lambda('x,y-> x + y'); // xとyを受け取って、x+yを返す
* @example
* var f = lamnda('x->y->z-> x+y+z'); // 部分適用できる関数を作る
*/
var lambda = function(expression){
if( cache[expression] )
return cache[expression];
var parsed = parseExpression(expression);
var func = new Function( parsed.argumentNames,"return ("+ parsed.body + ");");
cache[expression] = func;
return func;
};
ns.provide({
lambda : lambda
});
});
/**
@fileOverview brook.channel
@author daichi.hiroki<hirokidaichi@gmail.com>
*/
/**
@name brook.channel
@namespace promiseをベースとしたobserver patternのシンプルな実装を提供します。
*/
Namespace('brook.channel')
.use('brook promise')
.define(function(ns){
/**
* @class brook.channel.createChannelで生成されるインスタンスのインナークラス
* @name _Channel
* @memberOf brook.channel
* @description
* promiseを登録できるobserverクラス
*/
var Channel = function(){
this.queue = [];
this.promises = [];
};
(function(proto){
/**#@+
* @methodOf brook.channel._Channel.prototype
*/
var through = function(k){return k};
proto.sendMessage = function(msg){
this.queue.push(msg);
while( this.queue.length ){
var v = this.queue.shift();
for( var i = 0,l= this.promises.length;i<l;i++){
this.promises[i].run(v);
}
}
};
/**
* @name send
*/
proto.send = function(func){
var func = ( func ) ? func : through;
var _self = this;
return ns.promise(function(next,val){
_self.sendMessage(func(val));
next(val);
});
};
/**
* @name observe
*/
proto.observe = function(promise){
this.promises.push(promise);
};
/**#@-*/
})(Channel.prototype);
var channel = function(name){
if( name )
return getNamedChannel(name);
return new Channel;
};
var NAMED_CHANNEL = {};
var getNamedChannel = function(name){
if( NAMED_CHANNEL[name] )
return NAMED_CHANNEL[name];
NAMED_CHANNEL[name] = new Channel;
return NAMED_CHANNEL[name];
};
var observeChannel = function(name,promise){
getNamedChannel( name ).observe( promise );
};
var sendChannel = function(name,func){
var channel = getNamedChannel( name );
return channel.send(func);
};
ns.provide({
channel : channel,
sendChannel : sendChannel,
observeChannel : observeChannel,
createChannel : function(){ return new Channel;}
});
});
/**
@fileOverview brook/model.js
@author daichi.hiroki<hirokidaichi@gmail.com>
*/
/**
@name brook.model
@namespace mvcにおけるmodelインタフェースを提供します。
*/
Namespace('brook.model')
.use('brook promise')
.use('brook.util *')
.use('brook.channel *')
.use('brook.lambda *')
.define(function(ns){
/**
* @class brook.model.createModelで生成されるインスタンスのインナークラス
* @name _Model
* @memberOf brook.model
* @description
* mvcにおけるmodelインタフェースをもったクラス
*/
var Model = function(obj){
this.methods = {};
this.channels= {};
for( var prop in obj ){
if( !obj.hasOwnProperty(prop) )
continue;
this.addMethod( prop,obj[prop]);
}
};
Model.prototype.addMethod = function(method,promise){
if( this.methods[method] )
throw('already '+ method +' defined');
var channel = ns.createChannel();
this.methods[method] = promise.bind( channel.send() );
this.channels[method] = channel;
return this;
};
Model.prototype.notify = function(method){
return ns.promise().bind( this.methods[method] );
};
Model.prototype.method = function(method){
if( !this.channels[method] )
throw('do not observe undefined method');
return this.channels[method];
};
var createModel = function(){
return new Model;
};
ns.provide({
createModel : createModel
});
});
Namespace("brook.view.htmltemplate.core")
.define(function(ns){
var module = { exports : {}};
//
/* 2008 Daichi Hiroki <hirokidaichi@gmail.com>
* html-template-core.js is freely distributable under the terms of MIT-style license.
* ( latest infomation :https://github.com/hirokidaichi/html-template )
/*-----------------------------------------------------------------------*/
var util = {};
util.defineClass = function(obj,superClass){
var klass = function Klass(){
this.initialize.apply(this,arguments);
};
if(superClass) klass.prototype = new superClass;
for(var prop in obj ){
if( !obj.hasOwnProperty(prop) )
continue;
klass.prototype[prop] = obj[prop];
}
if( !klass.prototype.initialize )
klass.prototype.initalize = function(){};
return klass;
};
util.merge = function(origin,target){
for(var prop in target ){
if( !target.hasOwnProperty(prop) )
continue;
origin[prop] = target[prop];
}
};
util.k = function(k){return k};
util.emptyFunction = function(){};
util.listToArray = function(list){
return Array.prototype.slice.call(list);
};
util.curry = function() {
var args = util.listToArray(arguments);
var f = args.shift();
return function() {
return f.apply(this, args.concat(util.listToArray(arguments)));
}
};
util.merge(util,{
isArray: function(object) {
return object != null && typeof object == "object" &&
'splice' in object && 'join' in object;
},
isFunction: function(object) {
return typeof object == "function";
},
isString: function(object) {
return typeof object == "string";
},
isNumber: function(object) {
return typeof object == "number";
},
isUndefined: function(object) {
return typeof object == "undefined";
}
});
util.createRegexMatcher = function(escapeChar,expArray){
function _escape( regText){
return (regText + '').replace(new RegExp(escapeChar,'g'), "\\");
}
var count = 0;
var e;
var regValues = { mapping : { 'fullText' : [0]},text:[]};
for( var i =0,l= expArray.length;i<l;i++){
e = expArray[i];
if(util.isString(e)){
regValues.text.push(e);
continue;
}
if(!regValues.mapping[e.map]){
regValues.mapping[e.map] = [];
}
regValues.mapping[e.map].push(++count);
}
var reg = undefined;
regValues.text = _escape(regValues.text.join(''));
return function matcher(matchingText){
if(!reg){
reg = new RegExp(regValues.text);
}
var results = (matchingText || '').match(reg);
if(results){
var ret = {};
var prop = 0,i = 0,map = regValues.mapping;
for(prop in map){
var list = map[prop];
var length = list.length;
for(i = 0 ;i<length ;i++){
if(results[list[i]]){
ret[prop] = results[list[i]];
break;
}
}
}
return ret;
}else{
return undefined;
}
};
};
var CHUNK_REGEXP_ATTRIBUTE = util.createRegexMatcher('%',[
"<",
"(%/)?",{map:'close'},
"TMPL_",
"(VAR|LOOP|IF|ELSE|ELSIF|UNLESS|INCLUDE)",{map:'tag_name'},
"%s*",
"(?:",
"(?:DEFAULT)=",
"(?:",
"'([^'>]*)'|",{map:'default'},
'"([^">]*)"|',{map:'default'},
"([^%s=>]*)" ,{map:'default'},
")",
")?",
"%s*",
"(?:",
"(?:ESCAPE)=",
"(?:",
"(JS|URL|HTML|0|1|NONE)",{map:'escape'},
")",
")?",
"%s*",
"(?:",
"(?:DEFAULT)=",
"(?:",
"'([^'>]*)'|",{map:'default'},
'"([^">]*)"|',{map:'default'},
"([^%s=>]*)" ,{map:'default'},
")",
")?",
"%s*",
/*
NAME or EXPR
*/
"(?:",
"(NAME|EXPR)=",{map:'attribute_name'},
"(?:",
"'([^'>]*)'|",{map:'attribute_value'},
'"([^">]*)"|',{map:'attribute_value'},
"([^%s=>]*)" ,{map:'attribute_value'},
")",
")?",
/*
DEFAULT or ESCAPE
*/
'%s*',
"(?:",
"(?:DEFAULT)=",
"(?:",
"'([^'>]*)'|",{map:'default'},
'"([^">]*)"|',{map:'default'},
"([^%s=>]*)" ,{map:'default'},
")",
")?",
"%s*",
"(?:",
"(?:ESCAPE)=",
"(?:",
"(JS|URL|HTML|0|1|NONE)",{map:'escape'},
")",
")?",
"%s*",
"(?:",
"(?:DEFAULT)=",
"(?:",
"'([^'>]*)'|",{map:'default'},
'"([^">]*)"|',{map:'default'},
"([^%s=>]*)" ,{map:'default'},
")",
")?",
"%s*",
">"
]);
var element = {};
element.Base = util.defineClass({
initialize: function(option) {
this.mergeOption(option);
},
mergeOption : function(option){
util.merge(this,option);
this['isCloseTag'] =(this['isCloseTag'])? true: false;
},
isParent : util.emptyFunction,
execute : util.emptyFunction,
getCode: function(e) {
return "void(0);";
},
toString: function() {
return [
'<' ,
((this.isCloseTag) ? '/': '') ,
this.type ,
((this.hasName) ? ' NAME=': '') ,
((this.name) ? this.name: '') ,
'>'
].join('');
},
// HTML::Template::Pro shigeki morimoto's extension
_pathLike: function(attribute , matched){
var pos = (matched == '/')?'0':'$_C.length -'+(matched.split('..').length-1);
return [
"(($_C["+pos+"]['" ,
attribute ,
"']) ? $_C["+pos+"]['" ,
attribute ,
"'] : undefined )"
].join('');
},
getParam: function() {
var ret = "";
if (this.attributes['name']) {
var matched = this.attributes['name'].match(/^(\/|(?:\.\.\/)+)(\w+)/);
if(matched){
return this._pathLike(matched[2],matched[1]);
}
var _default = ( this.attributes['default'] )? "'"+this.attributes['default']+"'":"undefined";
ret = [
"(($_T['" ,
this.attributes['name'] ,
"']) ? $_T['" ,
this.attributes['name'] ,
"'] : ",
_default,
" )"
].join('');
}
if (this.attributes['expr']) {
var operators = {
'gt' :'>',
'lt' :'<',
'eq' :'==',
'ne' :'!=',
'ge' :'>=',
'le' :'<='
};
var replaced = this.attributes['expr'].replace(/{(\/|(?:\.\.\/)+)(\w+)}/g,function(full,matched,param){
return [
'$_C[',
(matched == '/')?'0':'$_C.length -'+(matched.split('..').length-1),
']["',param,'"]'
].join('');
}).replace(/\s+(gt|lt|eq|ne|ge|le|cmp)\s+/g,function(full,match){
return " "+operators[match]+" ";
});
ret = [
"(function(){",
" with($_F){",
" with($_T){",
" return (", replaced ,');',
"}}})()"
].join('');
}
if(this.attributes['escape']){
var _escape = {
NONE: 'NONE',
0 : 'NONE',
1 : 'HTML',
HTML: 'HTML',
JS : 'JS',
URL : 'URL'
}[this.attributes['escape']];
ret = [
'$_F.__escape'+_escape+'(',
ret,
')'
].join('');
}
return ret;
}
});
var cache = {
STRING_FRAGMENT : []
};
util.merge( element , {
ROOTElement: util.defineClass({
type: 'root',
getCode: function() {
if (this.isCloseTag) {
return 'return $_R.join("");';
} else {
return [
'var $_R = [];',
'var $_C = [param];',
'var $_F = funcs||{};',
'var $_T = param||{};',
'var $_S = cache.STRING_FRAGMENT;',
].join('');
}
}
},element.Base),
LOOPElement: util.defineClass({
type: 'loop',
initialize:function(option){
this.mergeOption(option);
},
getLoopId : function(){
if( this._ID ) {
return this._ID;
}
if( !element.LOOPElement.instanceId ){
element.LOOPElement.instanceId = 0;
}
var id = element.LOOPElement.instanceId++;
this._ID = '$'+id.toString(16);
return this._ID;
},
getCode: function() {
if (this.isCloseTag) {
return ['}','$_T = $_C.pop();'].join('');
} else {
var id = this.getLoopId();
return [
'var $_L_'+id+' =' + this.getParam() + '|| [];',
'var $_LL_'+id+' = $_L_'+id+'.length;',
'$_C.push($_T);',
'for(var i_'+id+'=0;i_'+id+'<$_LL_'+id+';i_'+id+'++){',
' $_T = (typeof $_L_'+id+'[i_'+id+'] == "object")?',
' $_L_'+id+'[i_'+id+'] : {};',
"$_T['__first__'] = (i_"+id+" == 0) ? true: false;",
"$_T['__counter__'] = i_"+id+"+1;",
"$_T['__odd__'] = ((i_"+id+"+1)% 2) ? true: false;",
"$_T['__last__'] = (i_"+id+" == ($_LL_"+id+" - 1)) ? true: false;",
"$_T['__inner__'] = ($_T['__first__']||$_T['__last__'])?false:true;"
].join('');
}
}
},element.Base),
VARElement: util.defineClass({
type: 'var',
getCode: function() {
if (this.isCloseTag) {
throw(new Error('HTML.Template ParseError TMPL_VAR'));
} else {
return '$_R.push(' + this.getParam() + ');';
}
}
},element.Base),
IFElement: util.defineClass({
type: 'if',
getCondition: function(param) {
return "!!" + this.getParam(param);
},
getCode: function() {
if (this.isCloseTag) {
return '}';
} else {
return 'if(' + this.getCondition() + '){';
}
}
},element.Base),
ELSEElement: util.defineClass( {
type: 'else',
getCode: function() {
if (this.isCloseTag) {
throw(new Error('HTML.Template ParseError No Close Tag for TMPL_ELSE'));
} else {
return '}else{';
}
}
},element.Base),
INCLUDEElement: util.defineClass({
type: 'include',
getCode: function() {
if (this.isCloseTag) {
throw(new Error('HTML.Template ParseError No Close Tag for TMPL_INCLUDE'));
} else {
var name = '"'+(this.attributes['name'])+'"';
return [
'$_R.push($_F.__include(',name,',$_T,$_F));'
].join('\n');
}
}
},element.Base),
TEXTElement: util.defineClass({
type: 'text',
isCloseTag: false,
initialize : function(option){this.value = option;},
getCode: function() {
if (this.isCloseTag) {
throw(new Error('HTML.Template ParseError No Close Tag for TEXT'));
} else {
cache.STRING_FRAGMENT.push(this.value);
return '$_R.push($_S['+(cache.STRING_FRAGMENT.length-1)+']);';
}
}
},element.Base)
});
element.ELSIFElement = util.defineClass({
type: 'elsif',
getCode: function() {
if (this.isCloseTag) {
throw(new Error('HTML.Template ParseError No Close Tag for TMPL_ELSIF'));
} else {
return '}else if(' + this.getCondition() + '){';
}
}
},element.IFElement);
element.UNLESSElement = util.defineClass({
type: 'unless',
getCondition: function(param) {
return "!" + this.getParam(param);
}
},element.IFElement);
element.createElement = function(type, option) {
return new element[type + 'Element'](option);
};
var parseHTMLTemplate = function(source) {
var chunks = [];
var createElement = element.createElement;
var root = createElement('ROOT', {
isCloseTag: false
});
var matcher = CHUNK_REGEXP_ATTRIBUTE;
chunks.push(root);
while (source.length > 0) {
var results = matcher(source);
if (!results) {
chunks.push(createElement('TEXT', source));
source = '';
break;
}
var index = 0;
var fullText = results.fullText;
if ((index = source.indexOf(fullText)) > 0) {
var text = source.slice(0, index);
chunks.push(createElement('TEXT', text));
source = source.slice(index);
};
var attr,name,value;
if ( results.attribute_name ) {
name = results.attribute_name.toLowerCase();
value = results.attribute_value;
attr = {};
attr[name] = value;
attr['default'] = results['default'];
attr['escape'] = results['escape'];
} else {
attr = undefined;
}
chunks.push(createElement(results.tag_name, {
'attributes': attr,
'isCloseTag' : results.close,
'parent' : this
}));
source = source.slice(fullText.length);
};
chunks.push(createElement('ROOT', {
isCloseTag: true
}));
return chunks;
};
module.exports.getFunctionText = function(chunksOrSource){
var chunks = util.isString(chunksOrSource) ? parseHTMLTemplate( chunksOrSource ) : chunksOrSource;
var codes = [];
for(var i=0,l=chunks.length;i<l;i++){codes.push(chunks[i].getCode());}
return codes.join('\n');
};
module.exports.compileFunctionText = function(functionText){
return util.curry(new Function('cache','param','funcs',functionText),cache);
};
ns.provide(module.exports);
});
/**
@fileOverview brook/view/htmltemplate.js
@author daichi.hiroki<hirokidaichi@gmail.com>