-
Notifications
You must be signed in to change notification settings - Fork 0
/
templater.js
2348 lines (1883 loc) · 56.4 KB
/
templater.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
var BEMHTML;
(function(global) {
function buildBemXjst(libs) {
var exports;
/* BEM-XJST Runtime Start */
var BEMHTML = function(module, exports) {
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.bemhtml = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
var inherits = require('inherits');
var Match = require('../bemxjst/match').Match;
var BemxjstEntity = require('../bemxjst/entity').Entity;
/**
* @class Entity
* @param {BEMXJST} bemxjst
* @param {String} block
* @param {String} elem
* @param {Array} templates
*/
function Entity(bemxjst) {
this.bemxjst = bemxjst;
this.jsClass = null;
// "Fast modes" about HTML
this.tag = new Match(this, 'tag');
this.attrs = new Match(this, 'attrs');
this.bem = new Match(this, 'bem');
this.cls = new Match(this, 'cls');
BemxjstEntity.apply(this, arguments);
}
inherits(Entity, BemxjstEntity);
exports.Entity = Entity;
Entity.prototype.init = function(block, elem) {
this.block = block;
this.elem = elem;
// Class for jsParams
this.jsClass = this.bemxjst.classBuilder.build(this.block, this.elem);
};
Entity.prototype._keys = {
tag: 1,
content: 1,
attrs: 1,
mix: 1,
js: 1,
mods: 1,
elemMods: 1,
cls: 1,
bem: 1
};
Entity.prototype.defaultBody = function(context) {
context.mods = this.mods.exec(context);
if (context.ctx.elem) context.elemMods = this.elemMods.exec(context);
return this.bemxjst.render(context,
this,
this.tag.exec(context),
this.js.exec(context),
this.bem.exec(context),
this.cls.exec(context),
this.mix.exec(context),
this.attrs.exec(context),
this.content.exec(context),
context.mods,
context.elemMods);
};
},{"../bemxjst/entity":5,"../bemxjst/match":8,"inherits":11}],2:[function(require,module,exports){
var inherits = require('inherits');
var utils = require('../bemxjst/utils');
var Entity = require('./entity').Entity;
var BEMXJST = require('../bemxjst');
function BEMHTML(options) {
BEMXJST.apply(this, arguments);
this._shortTagCloser = typeof options.xhtml !== 'undefined' &&
options.xhtml ? '/>' : '>';
this._elemJsInstances = options.elemJsInstances;
this._omitOptionalEndTags = options.omitOptionalEndTags;
this._singleQuotesForDataAttrs =
typeof options.singleQuotesForDataAttrs === 'undefined' ?
false :
options.singleQuotesForDataAttrs;
this._unquotedAttrs = typeof options.unquotedAttrs === 'undefined' ?
false :
options.unquotedAttrs;
}
inherits(BEMHTML, BEMXJST);
module.exports = BEMHTML;
BEMHTML.prototype.Entity = Entity;
BEMHTML.prototype.runMany = function(arr) {
var out = '';
var context = this.context;
var prevPos = context.position;
var prevNotNewList = context._notNewList;
if (prevNotNewList) {
context._listLength += arr.length - 1;
} else {
context.position = 0;
context._listLength = arr.length;
}
context._notNewList = true;
if (this.canFlush) {
for (var i = 0; i < arr.length; i++)
out += context._flush(this._run(arr[i]));
} else {
for (var i = 0; i < arr.length; i++)
out += this._run(arr[i]);
}
if (!prevNotNewList)
context.position = prevPos;
return out;
};
BEMHTML.prototype.render = function(context, entity, tag, js, bem, cls, mix,
attrs, content, mods, elemMods) {
if (tag === undefined)
tag = 'div';
else if (!tag)
return (content || content === 0) ? this._run(content) : '';
var ctx = context.ctx;
var out = '<' + tag;
var isBEM = !!(typeof bem !== 'undefined' ?
bem : entity.block || entity.elem);
if (!isBEM && !cls)
return this.renderClose(out, context, tag, attrs, isBEM, ctx, content);
if (js === true)
js = {};
var jsParams;
if (js) {
jsParams = {};
jsParams[entity.jsClass] = js;
}
var addJSInitClass = isBEM && jsParams && (
this._elemJsInstances ?
entity.block :
(entity.block && !entity.elem)
);
out += ' class=';
var classValue = '';
if (isBEM) {
classValue += entity.jsClass;
classValue += this.buildModsClasses(entity.block, entity.elem,
entity.elem ? elemMods : mods);
if (mix) {
var m = this.renderMix(entity, mix, jsParams, addJSInitClass);
classValue += m.out;
jsParams = m.jsParams;
addJSInitClass = m.addJSInitClass;
}
if (cls)
classValue += ' ' + (typeof cls === 'string' ?
utils.attrEscape(cls).trim() : cls);
} else {
classValue += typeof cls === 'string' ?
utils.attrEscape(cls).trim() : cls;
}
if (addJSInitClass)
classValue += ' i-bem';
out += this._unquotedAttrs && utils.isUnquotedAttr(classValue) ?
classValue :
('"' + classValue + '"');
if (isBEM && jsParams)
out += ' data-bem=\'' + utils.jsAttrEscape(JSON.stringify(jsParams)) + '\'';
return this.renderClose(out, context, tag, attrs, isBEM, ctx, content);
};
var OPTIONAL_END_TAGS = {
// https://www.w3.org/TR/html4/index/elements.html
html: 1, head: 1, body: 1, p: 1, li: 1, dt: 1, dd: 1,
colgroup: 1, thead: 1, tbody: 1, tfoot: 1, tr: 1, th: 1, td: 1, option: 1,
// html5 https://www.w3.org/TR/html5/syntax.html#optional-tags
/* dl — Neither tag is omissible */ rb: 1, rt: 1, rtc: 1, rp: 1, optgroup: 1
};
BEMHTML.prototype.renderClose = function(prefix, context, tag, attrs, isBEM,
ctx, content) {
var out = prefix;
out += this.renderAttrs(attrs);
if (utils.isShortTag(tag)) {
out += this._shortTagCloser;
if (this.canFlush)
out = context._flush(out);
} else {
out += '>';
if (this.canFlush)
out = context._flush(out);
// TODO(indutny): skip apply next flags
if (content || content === 0)
out += this.renderContent(content, isBEM);
if (!this._omitOptionalEndTags || !OPTIONAL_END_TAGS.hasOwnProperty(tag))
out += '</' + tag + '>';
}
if (this.canFlush)
out = context._flush(out);
return out;
};
BEMHTML.prototype.renderAttrs = function(attrs) {
var out = '';
// NOTE: maybe we need to make an array for quicker serialization
if (utils.isObj(attrs)) {
/* jshint forin : false */
for (var name in attrs) {
var attr = attrs[name];
if (attr === undefined || attr === false || attr === null)
continue;
if (attr === true) {
out += ' ' + name;
} else {
var attrVal = utils.isSimple(attr) ? attr : this.run(attr);
out += ' ' + name + '=';
out += (this._singleQuotesForDataAttrs && name.indexOf('data-') === 0) ?
'\'' + utils.jsAttrEscape(attrVal) + '\'' :
this.getAttrValue(attrVal);
}
}
}
return out;
};
BEMHTML.prototype.getAttrValue = function(attrVal) {
return this._unquotedAttrs && utils.isUnquotedAttr(attrVal) ?
attrVal :
('"' + utils.attrEscape(attrVal) + '"');
};
BEMHTML.prototype.renderMix = function(entity, mix, jsParams, addJSInitClass) {
var visited = {};
var context = this.context;
var js = jsParams;
var addInit = addJSInitClass;
visited[entity.jsClass] = true;
// Transform mix to the single-item array if it's not array
if (!Array.isArray(mix))
mix = [ mix ];
var classBuilder = this.classBuilder;
var out = '';
for (var i = 0; i < mix.length; i++) {
var item = mix[i];
if (!item)
continue;
if (typeof item === 'string')
item = { block: item, elem: undefined };
var hasItem = false;
if (item.elem) {
hasItem = item.elem !== entity.elem && item.elem !== context.elem ||
item.block && item.block !== entity.block;
} else if (item.block) {
hasItem = !(item.block === entity.block && item.mods) ||
item.mods && entity.elem;
}
var block = item.block || item._block || context.block;
var elem = item.elem || item._elem || context.elem;
var key = classBuilder.build(block, elem);
var classElem = item.elem ||
item._elem ||
(item.block ? undefined : context.elem);
if (hasItem)
out += ' ' + classBuilder.build(block, classElem);
out += this.buildModsClasses(block, classElem,
(item.elem || !item.block && (item._elem || context.elem)) ?
item.elemMods : item.mods);
if (item.js) {
if (!js)
js = {};
js[classBuilder.build(block, item.elem)] =
item.js === true ? {} : item.js;
if (!addInit)
addInit = this._elemJsInstances ?
(item.elem || block) :
(block && !item.elem);
}
// Process nested mixes from BEMJSON
if (item.mix) {
var nested = this.renderMix(entity, item.mix, js, addInit);
js = utils.extend(js, nested.jsParams);
addInit = nested.addJSInitClass;
out += nested.out;
}
// Process nested mixes from templates
if (!hasItem || visited[key])
continue;
visited[key] = true;
var nestedEntity = this.entities[key];
if (!nestedEntity)
continue;
var oldBlock = context.block;
var oldElem = context.elem;
var nestedMix = nestedEntity.mix.exec(context);
context.elem = oldElem;
context.block = oldBlock;
if (!nestedMix)
continue;
for (var j = 0; j < nestedMix.length; j++) {
var nestedItem = nestedMix[j];
if (!nestedItem) continue;
if (!nestedItem.block &&
!nestedItem.elem ||
!visited[classBuilder.build(nestedItem.block, nestedItem.elem)]) {
if (nestedItem.block) continue;
nestedItem._block = block;
nestedItem._elem = elem;
// make a copy, do not modify original array
mix = mix.slice(0, i + 1).concat(
nestedItem,
mix.slice(i + 1)
);
}
}
}
return {
out: out,
jsParams: js,
addJSInitClass: addInit
};
};
BEMHTML.prototype.buildModsClasses = function(block, elem, mods) {
if (!mods)
return '';
var res = '';
var modName;
/*jshint -W089 */
for (modName in mods) {
if (!mods.hasOwnProperty(modName) || modName === '')
continue;
var modVal = mods[modName];
if (!modVal && modVal !== 0) continue;
if (typeof modVal !== 'boolean')
modVal += '';
var builder = this.classBuilder;
res += ' ' + (elem ?
builder.buildElemClass(block, elem, modName, modVal) :
builder.buildBlockClass(block, modName, modVal));
}
return res;
};
},{"../bemxjst":7,"../bemxjst/utils":10,"./entity":1,"inherits":11}],3:[function(require,module,exports){
function ClassBuilder(options) {
this.elemDelim = options.elem || '__';
this.modDelim = typeof options.mod === 'string' ?
{
name: options.mod || '_',
val: options.mod || '_'
} :
{
name: options.mod && options.mod.name || '_',
val: options.mod && options.mod.val || '_'
};
}
exports.ClassBuilder = ClassBuilder;
ClassBuilder.prototype.build = function(block, elem) {
if (!elem)
return block;
else
return block + this.elemDelim + elem;
};
ClassBuilder.prototype.buildModPostfix = function(modName, modVal) {
var res = this.modDelim.name + modName;
if (modVal !== true) res += this.modDelim.val + modVal;
return res;
};
ClassBuilder.prototype.buildBlockClass = function(name, modName, modVal) {
var res = name;
if (modVal) res += this.buildModPostfix(modName, modVal);
return res;
};
ClassBuilder.prototype.buildElemClass = function(block, name, modName, modVal) {
return this.buildBlockClass(block) +
this.elemDelim +
name +
this.buildModPostfix(modName, modVal);
};
ClassBuilder.prototype.split = function(key) {
return key.split(this.elemDelim, 2);
};
},{}],4:[function(require,module,exports){
var utils = require('./utils');
function Context(bemxjst) {
this._bemxjst = bemxjst;
this.ctx = null;
this.block = '';
// Save current block until the next BEM entity
this._currBlock = '';
this.elem = null;
this.mods = {};
this.elemMods = {};
this.position = 0;
this._listLength = 0;
this._notNewList = false;
this.escapeContent = bemxjst.options.escapeContent !== false;
}
exports.Context = Context;
Context.prototype._flush = null;
Context.prototype.isSimple = utils.isSimple;
Context.prototype.isShortTag = utils.isShortTag;
Context.prototype.extend = utils.extend;
Context.prototype.identify = utils.identify;
Context.prototype.xmlEscape = utils.xmlEscape;
Context.prototype.attrEscape = utils.attrEscape;
Context.prototype.jsAttrEscape = utils.jsAttrEscape;
Context.prototype.onError = function(context, e) {
console.error('bem-xjst rendering error:', {
block: context.ctx.block,
elem: context.ctx.elem,
mods: context.ctx.mods,
elemMods: context.ctx.elemMods
}, e);
};
Context.prototype.isFirst = function() {
return this.position === 1;
};
Context.prototype.isLast = function() {
return this.position === this._listLength;
};
Context.prototype.generateId = function() {
return utils.identify(this.ctx);
};
Context.prototype.reapply = function(ctx) {
return this._bemxjst.run(ctx);
};
},{"./utils":10}],5:[function(require,module,exports){
var utils = require('./utils');
var Match = require('./match').Match;
var tree = require('./tree');
var Template = tree.Template;
var PropertyMatch = tree.PropertyMatch;
var CompilerOptions = tree.CompilerOptions;
function Entity(bemxjst, block, elem, templates) {
this.bemxjst = bemxjst;
this.block = null;
this.elem = null;
// Compiler options via `xjstOptions()`
this.options = {};
// `true` if entity has just a default renderer for `def()` mode
this.canFlush = true;
// "Fast modes"
this.def = new Match(this);
this.mix = new Match(this, 'mix');
this.js = new Match(this, 'js');
this.mods = new Match(this, 'mods');
this.elemMods = new Match(this, 'elemMods');
this.content = new Match(this, 'content');
// "Slow modes"
this.rest = {};
// Initialize
this.init(block, elem);
this.initModes(templates);
}
exports.Entity = Entity;
Entity.prototype.init = function(block, elem) {
this.block = block;
this.elem = elem;
};
Entity.prototype._keys = {
content: 1,
mix: 1,
js: 1,
mods: 1,
elemMods: 1
};
Entity.prototype._initRest = function(key) {
if (key === 'default') {
this.rest[key] = this.def;
} else if (this._keys[key]) {
this.rest[key] = this[key];
} else {
this.rest[key] = this.rest[key] || new Match(this, key);
}
};
Entity.prototype.initModes = function(templates) {
/* jshint maxdepth : false */
for (var i = 0; i < templates.length; i++) {
var template = templates[i];
for (var j = template.predicates.length - 1; j >= 0; j--) {
var pred = template.predicates[j];
if (!(pred instanceof PropertyMatch))
continue;
if (pred.key !== '_mode')
continue;
template.predicates.splice(j, 1);
this._initRest(pred.value);
// All templates should go there anyway
this.rest[pred.value].push(template);
break;
}
if (j === -1)
this.def.push(template);
// Merge compiler options
for (var j = template.predicates.length - 1; j >= 0; j--) {
var pred = template.predicates[j];
if (!(pred instanceof CompilerOptions))
continue;
this.options = utils.extend(this.options, pred.options);
}
}
};
Entity.prototype.prepend = function(other) {
// Prepend to the slow modes, fast modes are in this hashmap too anyway
var keys = Object.keys(this.rest);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (!other.rest[key])
continue;
this.rest[key].prepend(other.rest[key]);
}
// Add new slow modes
keys = Object.keys(other.rest);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (this.rest[key])
continue;
this._initRest(key);
this.rest[key].prepend(other.rest[key]);
}
};
// NOTE: This could be potentially compiled into inlined invokations
Entity.prototype.run = function(context) {
if (this.def.count !== 0)
return this.def.exec(context);
return this.defaultBody(context);
};
function contentMode() {
return this.ctx.content;
}
Entity.prototype.setDefaults = function() {
// Default .content() template for applyNext()
if (this.content.count !== 0)
this.content.push(new Template([], contentMode));
// .def() default
if (this.def.count !== 0) {
this.canFlush = this.options.flush || false;
var self = this;
this.def.push(new Template([], function defaultBodyProxy() {
return self.defaultBody(this);
}));
}
};
},{"./match":8,"./tree":9,"./utils":10}],6:[function(require,module,exports){
function BEMXJSTError(msg, func) {
this.name = 'BEMXJSTError';
this.message = msg;
if (Error.captureStackTrace)
Error.captureStackTrace(this, func || this.constructor);
else
this.stack = (new Error()).stack;
}
BEMXJSTError.prototype = Object.create(Error.prototype);
BEMXJSTError.prototype.constructor = BEMXJSTError;
exports.BEMXJSTError = BEMXJSTError;
},{}],7:[function(require,module,exports){
var inherits = require('inherits');
var Tree = require('./tree').Tree;
var PropertyMatch = require('./tree').PropertyMatch;
var AddMatch = require('./tree').AddMatch;
var Context = require('./context').Context;
var ClassBuilder = require('./class-builder').ClassBuilder;
var utils = require('./utils');
function BEMXJST(options) {
this.options = options;
this.entities = null;
this.defaultEnt = null;
// Current tree
this.tree = null;
// Current match
this.match = null;
// Create new Context constructor for overriding prototype
this.contextConstructor = function ContextChild(bemxjst) {
Context.call(this, bemxjst);
};
inherits(this.contextConstructor, Context);
this.context = null;
this.classBuilder = new ClassBuilder(this.options.naming || {});
// Execution depth, used to invalidate `applyNext` bitfields
this.depth = 0;
// Do not call `_flush` on overridden `def()` mode
this.canFlush = false;
// oninit templates
this.oninit = null;
// Initialize default entity (no block/elem match)
this.defaultEnt = new this.Entity(this, '', '', []);
this.defaultElemEnt = new this.Entity(this, '', '', []);
}
module.exports = BEMXJST;
BEMXJST.prototype.locals = Tree.methods
.concat('local', 'applyCtx', 'applyNext', 'apply');
BEMXJST.prototype.runOninit = function(oninits, ret) {
var self = ret || this;
self.BEMContext = this.contextConstructor;
for (var i = 0; i < oninits.length; i++) {
// NOTE: oninit has global context instead of BEMXJST
var oninit = oninits[i];
oninit(self, { BEMContext: self.BEMContext });
}
};
BEMXJST.prototype.compile = function(code) {
var self = this;
function applyCtx() {
return self.run(self.context.ctx);
}
function _applyCtx() {
return self._run(self.context.ctx);
}
function applyCtxWrap(ctx, changes) {
// Fast case
if (!changes)
return self.local({ ctx: ctx }, applyCtx);
return self.local(changes, function() {
return self.local({ ctx: ctx }, _applyCtx);
});
}
function _applyCtxWrap(ctx, changes) {
// Fast case
if (!changes)
return self.local({ ctx: ctx }, _applyCtx);
return self.local(changes, function() {
return self.local({ ctx: ctx }, applyCtx);
});
}
function apply(mode, changes) {
return self.applyMode(mode, changes);
}
function localWrap(changes) {
return function localBody(body) {
return self.local(changes, body);
};
}
var tree = new Tree({
refs: {
applyCtx: applyCtxWrap,
_applyCtx: _applyCtxWrap,
apply: apply
}
});
// Yeah, let people pass functions to us!
var templates = this.recompileInput(code);
var out = tree.build(templates, [
localWrap,
applyCtxWrap,
function applyNextWrap(changes) {
if (changes)
return self.local(changes, applyNextWrap);
return self.applyNext();
},
apply
]);
// Concatenate templates with existing ones
// TODO(indutny): it should be possible to incrementally add templates
if (this.tree) {
this.runOninit(out.oninit);
out = {
templates: out.templates.concat(this.tree.templates),
oninit: this.tree.oninit.concat(out.oninit)
};
}
this.tree = out;
// Group block+elem entities into a hashmap
var ent = this.groupEntities(out.templates);
// Transform entities from arrays to Entity instances
ent = this.transformEntities(ent);
this.entities = ent;
this.oninit = out.oninit;
};
BEMXJST.prototype.getTemplate = function(code, options) {
this.compile(code, options);
return this.exportApply();
};
BEMXJST.prototype.recompileInput = function(code) {
var args = BEMXJST.prototype.locals;
// Reuse function if it already has right arguments
if (typeof code === 'function' && code.length === args.length)
return code;
return new Function(args.join(', '), utils.fnToString(code));
};
BEMXJST.prototype.groupEntities = function(tree) {
var res = {};
for (var i = 0; i < tree.length; i++) {
// Make sure to change only the copy, the original is cached in `this.tree`
var template = tree[i].clone();
var block = null;
var elem;
elem = undefined;
for (var j = 0; j < template.predicates.length; j++) {
var pred = template.predicates[j];
if (!(pred instanceof PropertyMatch) &&
!(pred instanceof AddMatch))
continue;
if (pred.key === 'block')
block = pred.value;
else if (pred.key === 'elem')
elem = pred.value;
else
continue;
// Remove predicate, we won't much against it
template.predicates.splice(j, 1);
j--;
}
if (block === null) {
var msg = 'block(…) subpredicate is not found.\n' +
' See template with subpredicates:\n * ';
for (var j = 0; j < template.predicates.length; j++) {
var pred = template.predicates[j];
if (j !== 0)
msg += '\n * ';
if (pred.key === '_mode') {
msg += pred.value + '()';
} else {
if (Array.isArray(pred.key)) {
msg += pred.key[0].replace('mods', 'mod')
.replace('elemMods', 'elemMod') +
'(\'' + pred.key[1] + '\', \'' + pred.value + '\')';
} else {
msg += 'match(…)';
}
}
}
msg += '\n And template body: \n (' +
(typeof template.body === 'function' ?
template.body :
JSON.stringify(template.body)) + ')';
if (typeof BEMXJSTError === 'undefined') {
BEMXJSTError = require('./error').BEMXJSTError;
}
throw new BEMXJSTError(msg);
}
var key = this.classBuilder.build(block, elem);
if (!res[key])
res[key] = [];
res[key].push(template);
}
return res;
};
BEMXJST.prototype.transformEntities = function(entities) {
var wildcardElems = [];
var keys = Object.keys(entities);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
// TODO(indutny): pass this values over
var parts = this.classBuilder.split(key);
var block = parts[0];
var elem = parts[1];
if (elem === '*')
wildcardElems.push(block);
entities[key] = new this.Entity(
this, block, elem, entities[key]);
}
// Merge wildcard block templates
if (entities.hasOwnProperty('*')) {
var wildcard = entities['*'];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key === '*')
continue;
entities[key].prepend(wildcard);
}
this.defaultEnt.prepend(wildcard);
this.defaultElemEnt.prepend(wildcard);
}
// Merge wildcard elem templates
for (var i = 0; i < wildcardElems.length; i++) {
var block = wildcardElems[i];
var wildcardKey = this.classBuilder.build(block, '*');
var wildcard = entities[wildcardKey];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (key === wildcardKey)
continue;
var entity = entities[key];
if (entity.block !== block || entity.elem === undefined)
continue;
entities[key].prepend(wildcard);
}
this.defaultElemEnt.prepend(wildcard);
}
// Set default templates after merging with wildcard
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
entities[key].setDefaults();
this.defaultEnt.setDefaults();
this.defaultElemEnt.setDefaults();
}
return entities;
};
BEMXJST.prototype._run = function(context) {
if (context === undefined || context === '' || context === null)
return this.runEmpty();
else if (Array.isArray(context))
return this.runMany(context);
else if (
typeof context.html === 'string' &&
!context.tag &&
typeof context.block === 'undefined' &&
typeof context.elem === 'undefined' &&
typeof context.cls === 'undefined' &&
typeof context.attrs === 'undefined'
)
return this.runUnescaped(context);
else if (utils.isSimple(context))
return this.runSimple(context);
return this.runOne(context);
};
BEMXJST.prototype.run = function(json) {
var match = this.match;
var context = this.context;
var depth = this.depth;
this.match = null;
this.context = new this.contextConstructor(this);
this.canFlush = this.context._flush !== null;
this.depth = 0;
var res = this._run(json);
if (this.canFlush)
res = this.context._flush(res);