| 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067 | 1
1
134
134
134
134
134
134
134
134
134
7
4
4
2
1
2
2
2
2
2
2
7
7
7
7
7
7
6
6
3
3
3
3
7
2
5
1
2
2
2
2
2
4
4
1
1
1
1
4
4
1
4
1
1
4
4
4
1
1
1
2
32
32
29
29
29
3
3
10
10
7
9
7
3
25
24
24
1
16
15
2
13
3
10
15
1
20
20
17
17
17
3
3
9
9
7
10
9
7
2
8
7
7
1
8
7
7
1
11
10
10
1
8
7
7
1
1022
1018
1018
4
2
1
4
4
5
4
2
4
2
4
1
2
2
126
167
1
2
1
166
166
166
166
1
257
257
330
330
330
257
131
131
131
131
131
131
131
165
165
165
165
165
165
16
16
16
16
16
16
16
5
5
149
149
149
8
8
165
131
131
131
131
131
131
126
126
126
126
131
116
15
131
131
165
165
165
165
165
13
13
4
9
165
165
165
165
165
165
165
165
131
126
126
131
131
131
131
137
131
137
137
137
137
137
137
1
137
137
137
137
137
1296
1296
1296
1296
4
11
11
11
1292
1292
45
45
45
3
1247
1236
1236
1292
1281
1102
1102
1102
1
1101
1
1279
1279
1279
1279
1279
1279
2
2
2
2
2
2
1290
1288
1288
1131
7
7
12
12
34
5
5
12
5
7
24
24
22
1124
1294
135
181
181
181
11
170
3
3
8
8
8
3
167
2
165
6
165
165
20
23
23
20
165
8
165
165
15
22
22
165
8
8
8
8
165
9
165
165
165
1
164
164
30
7
24
24
24
23
164
165
131
131
1
1
1
181
181
1
181
4
181
1
159
159
1
159
2
159
1
180
180
180
140
54
51
180
15
22
20
180
1
1
1
| var BH = (function() {
/**
* BH: BEMJSON -> HTML процессор.
* @constructor
*/
function BH() {
/**
* Используется для идентификации матчеров.
* Каждому матчеру дается уникальный id для того, чтобы избежать повторного применения
* матчера к одному и тому же узлу BEMJSON-дерева.
* @type {Number}
* @private
*/
this._lastMatchId = 0;
/**
* Плоский массив для хранения матчеров.
* Каждый элемент — массив с двумя элементами: [{String} выражение, {Function} матчер}]
* @type {Array}
* @private
*/
this._matchers = [];
/**
* Флаг, включающий автоматическую систему поиска зацикливаний. Следует использовать в development-режиме,
* чтобы определять причины зацикливания.
* @type {Boolean}
* @private
*/
this._infiniteLoopDetection = false;
/**
* Неймспейс для библиотек. Сюда можно писать различный функционал для дальнейшего использования в матчерах.
* ```javascript
* bh.lib.objects = bh.lib.objects || {};
* bh.lib.objects.inverse = bh.lib.objects.inverse || function(obj) { ... };
* ```
* @type {Object}
*/
this.lib = {};
this._inited = false;
/**
* Опции BH. Задаются через setOptions.
* @type {Object}
*/
this._options = {};
this._optJsAttrName = 'onclick';
this._optJsAttrIsJs = true;
this.utils = {
_lastGenId: 0,
_expandoId: new Date().getTime(),
bh: this,
/**
* Проверяет, что объект является примитивом.
* ```javascript
* bh.match('link', function(ctx) {
* ctx.tag(ctx.isSimple(ctx.content()) ? 'span' : 'div');
* });
* ```
* @param {*} obj
* @returns {Boolean}
*/
isSimple: function (obj) {
if (!obj || obj === true) return true;
var t = typeof obj;
return t === 'string' || t === 'number';
},
/**
* Расширяет один объект свойствами другого (других).
* Аналог jQuery.extend.
* ```javascript
* obj = ctx.extend(obj, {a: 1});
* ```
* @param {Object} target
* @returns {Object}
*/
extend: function(target) {
if (!target || typeof target !== 'object') {
target = {};
}
for (var i = 1, len = arguments.length; i < len; i++) {
var obj = arguments[i],
key;
Eif (obj) {
for (key in obj) {
target[key] = obj[key];
}
}
}
return target;
},
/**
* Возвращает позицию элемента в рамках родителя.
* Отсчет производится с 1 (единицы).
* ```javascript
* bh.match('list__item', function(ctx) {
* ctx.mod('pos', ctx.position());
* });
* ```
* @returns {Number}
*/
position: function () {
var node = this.node;
return node.index === 'content' ? 1 : node.index + 1;
},
/**
* Возвращает true, если текущий BEMJSON-элемент первый в рамках родительского BEMJSON-элемента.
* ```javascript
* bh.match('list__item', function(ctx) {
* if (ctx.isFirst()) {
* ctx.mod('first', 'yes');
* }
* });
* ```
* @returns {Boolean}
*/
isFirst: function () {
var node = this.node;
return node.index === 'content' || node.index === 0;
},
/**
* Возвращает true, если текущий BEMJSON-элемент последний в рамках родительского BEMJSON-элемента.
* ```javascript
* bh.match('list__item', function(ctx) {
* if (ctx.isLast()) {
* ctx.mod('last', 'yes');
* }
* });
* ```
* @returns {Boolean}
*/
isLast: function () {
var node = this.node;
return node.index === 'content' || node.index === node.arr.length - 1;
},
/**
* Передает параметр вглубь BEMJSON-дерева. Например:
* ```javascript
* bh.match('input', function(ctx) {
* ctx.content({
* elem: 'control'
* }, true);
* ctx.tParam('value', ctx.param('value'));
* });
* bh.match('input__control', function(ctx) {
* ctx.attr('value', ctx.tParam('value'));
* });
* ```
* @param {String} key
* @param {*} value
* @returns {*|Ctx}
*/
tParam: function (key, value) {
var keyName = '__tp_' + key;
if (arguments.length === 2) {
this.node[keyName] = value;
return this;
} else {
var node = this.node;
while (node) {
if (node.hasOwnProperty(keyName)) {
return node[keyName];
}
node = node.parentNode;
}
return undefined;
}
},
/**
* Применяет матчинг для переданного фрагмента BEMJSON.
* Возвращает результат преобразований.
* @param {Object|Array} bemJson
* @returns {Object|Array}
*/
apply: function (bemJson) {
var prevCtx = this.ctx,
prevNode = this.node;
var res = this.bh.processBemJson(bemJson, prevCtx.block);
this.ctx = prevCtx;
this.node = prevNode;
return res;
},
/**
* Выполняет преобразования данного BEMJSON-элемента остальными матчерами. Может понадобиться, например, чтобы добавить элемент в самый конец содержимого, если в базовых шаблонах в конец содержимого добавляются другие элементы.
* Пример:
* ```javascript
* bh.match('header', function(ctx) {
* ctx.content([
* ctx.content(),
* { elem: 'under' }
* ], true);
* });
* bh.match('header_float_yes', function(ctx) {
* ctx.applyBase();
* ctx.content([
* ctx.content(),
* { elem: 'clear' }
* ], true);
* });
* ```
* @param {Object} [changes]
* @returns {Ctx}
*/
applyBase: function (changes) {
var prevCtx = this.ctx,
prevNode = this.node,
prevValues,
key;
if (changes) {
prevValues = {};
for (key in changes) {
prevValues[key] = prevCtx[key];
prevCtx[key] = changes[key];
}
}
var res = this.bh.processBemJson(this.ctx, this.ctx.block, true);
if (res !== prevCtx) {
this.newCtx = res;
}
if (changes) {
for (key in changes) {
prevCtx[key] = prevValues[key];
}
}
this.ctx = prevCtx;
this.node = prevNode;
return this;
},
/**
* Применяет матчеры, которые еще не были выполнены для данного фрагмента BEMJSON.
* Используется в случаях, когда следует выполнить шаблоны после выставления модификаторов.
* @returns {Ctx}
*/
applyTemplates: function () {
return this.applyBase();
},
/**
* Останавливает выполнение прочих матчеров для данного BEMJSON-элемента.
* Пример:
* ```javascript
* bh.match('button', function(ctx) {
* ctx.tag('button', true);
* });
* bh.match('button', function(ctx) {
* ctx.tag('span');
* ctx.stop();
* });
* ```
* @returns {Ctx}
*/
stop: function () {
this.ctx._stop = true;
return this;
},
/**
* Возвращает уникальный идентификатор. Может использоваться, например,
* чтобы задать соответствие между `label` и `input`.
* @returns {String}
*/
generateId: function (obj, onlyGet) {
return 'uniq' + this._expandoId + (++this._lastGenId);
},
/**
* Возвращает/устанавливает модификатор в зависимости от аргументов.
* **force** — задать модификатор даже если он был задан ранее.
* ```javascript
* bh.match('input', function(ctx) {
* ctx.mod('native', 'yes');
* ctx.mod('disabled', true);
* });
* bh.match('input_islands_yes', function(ctx) {
* ctx.mod('native', '', true);
* ctx.mod('disabled', false, true);
* });
* ```
* @param {String} key
* @param {String|Boolean} [value]
* @param {Boolean} [force]
* @returns {String|undefined|Ctx}
*/
mod: function(key, value, force) {
var mods;
if (value !== undefined) {
mods = this.ctx.mods || (this.ctx.mods = {});
mods[key] = mods[key] === undefined || force ? value : mods[key];
return this;
} else {
mods = this.ctx.mods;
return mods ? mods[key] : undefined;
}
},
/**
* Возвращает/устанавливает модификаторы в зависимости от аргументов.
* **force** — задать модификаторы даже если они были заданы ранее.
* ```javascript
* bh.match('paranja', function(ctx) {
* ctx.mods({
* theme: 'normal',
* disabled: true
* });
* });
* ```
* @param {Object} [values]
* @param {Boolean} [force]
* @returns {Object|Ctx}
*/
mods: function(values, force) {
var mods = this.ctx.mods || (this.ctx.mods = {});
if (values !== undefined) {
for (var key in values) {
mods[key] = mods[key] === undefined || force ? values[key] : mods[key];
}
return this;
} else {
return mods;
}
},
/**
* Возвращает/устанавливает тег в зависимости от аргументов.
* **force** — задать значение тега даже если оно было задано ранее.
* ```javascript
* bh.match('input', function(ctx) {
* ctx.tag('input');
* });
* ```
* @param {String} [tagName]
* @param {Boolean} [force]
* @returns {String|undefined|Ctx}
*/
tag: function(tagName, force) {
if (tagName !== undefined) {
this.ctx.tag = this.ctx.tag === undefined || force ? tagName : this.ctx.tag;
return this;
} else {
return this.ctx.tag;
}
},
/**
* Возвращает/устанавливает значение mix в зависимости от аргументов.
* При установке значения, если force равен true, то переданный микс заменяет прежнее значение,
* в противном случае миксы складываются.
* ```javascript
* bh.match('button_pseudo_yes', function(ctx) {
* ctx.mix({ block: 'link', mods: { pseudo: 'yes' } });
* ctx.mix([
* { elem: 'text' },
* { block: 'ajax' }
* ]);
* });
* ```
* @param {Array|BemJson} [mix]
* @param {Boolean} [force]
* @returns {Array|undefined|Ctx}
*/
mix: function(mix, force) {
if (mix !== undefined) {
if (force) {
this.ctx.mix = mix;
} else {
if (this.ctx.mix) {
this.ctx.mix = Array.isArray(this.ctx.mix) ?
this.ctx.mix.concat(mix) :
[this.ctx.mix].concat(mix);
} else {
this.ctx.mix = mix;
}
}
return this;
} else {
return this.ctx.mix;
}
},
/**
* Возвращает/устанавливает значение атрибута в зависимости от аргументов.
* **force** — задать значение атрибута даже если оно было задано ранее.
* @param {String} key
* @param {String} [value]
* @param {Boolean} [force]
* @returns {String|undefined|Ctx}
*/
attr: function(key, value, force) {
var attrs;
if (value !== undefined) {
attrs = this.ctx.attrs || (this.ctx.attrs = {});
attrs[key] = attrs[key] === undefined || force ? value : attrs[key];
return this;
} else {
attrs = this.ctx.attrs;
return attrs ? attrs[key] : undefined;
}
},
/**
* Возвращает/устанавливает атрибуты в зависимости от аргументов.
* **force** — задать атрибуты даже если они были заданы ранее.
* ```javascript
* bh.match('input', function(ctx) {
* ctx.attrs({
* name: ctx.param('name'),
* autocomplete: 'off'
* });
* });
* ```
* @param {Object} [values]
* @param {Boolean} [force]
* @returns {Object|Ctx}
*/
attrs: function(values, force) {
var attrs = this.ctx.attrs || (this.ctx.attrs = {});
if (values !== undefined) {
for (var key in values) {
if (values[key] === undefined) continue;
if (attrs[key] === undefined || force) attrs[key] = values[key];
}
return this;
} else {
return attrs;
}
},
/**
* Возвращает/устанавливает значение bem в зависимости от аргументов.
* **force** — задать значение bem даже если оно было задано ранее.
* Если `bem` имеет значение `false`, то для элемента не будут генерироваться BEM-классы.
* ```javascript
* bh.match('meta', function(ctx) {
* ctx.bem(false);
* });
* ```
* @param {Boolean} [bem]
* @param {Boolean} [force]
* @returns {Boolean|undefined|Ctx}
*/
bem: function(bem, force) {
if (bem !== undefined) {
this.ctx.bem = this.ctx.bem === undefined || force ? bem : this.ctx.bem;
return this;
} else {
return this.ctx.bem;
}
},
/**
* Возвращает/устанавливает значение `js` в зависимости от аргументов.
* **force** — задать значение `js` даже если оно было задано ранее.
* Значение `js` используется для инициализации блоков в браузере через `BEM.DOM.init()`.
* ```javascript
* bh.match('input', function(ctx) {
* ctx.js(true);
* });
* ```
* @param {Boolean|Object} [js]
* @param {Boolean} [force]
* @returns {Boolean|Object|Ctx}
*/
js: function(js, force) {
if (js !== undefined) {
this.ctx.js = this.ctx.js === undefined || force ? js : this.ctx.js;
return this;
} else {
return this.ctx.js;
}
},
/**
* Возвращает/устанавливает значение CSS-коасс в зависимости от аргументов.
* **force** — задать значение CSS-класса даже если оно было задано ранее.
* ```javascript
* bh.match('page', function(ctx) {
* ctx.cls('ua_js_no ua_css_standard');
* });
* ```
* @param cls
* @param force
* @returns {*}
*/
cls: function(cls, force) {
if (cls !== undefined) {
this.ctx.cls = this.ctx.cls === undefined || force ? cls : this.ctx.cls;
return this;
} else {
return this.ctx.cls;
}
},
/**
* Возвращает/устанавливает параметр текущего BEMJSON-элемента.
* **force** — задать значение параметра, даже если оно было задано ранее.
* Например:
* ```javascript
* // Пример входного BEMJSON: { block: 'search', action: '/act' }
* bh.match('search', function(ctx) {
* ctx.attr('action', ctx.param('action') || '/');
* });
* ```
* @param {String} key
* @param {*} [value]
* @param {Boolean} [force]
* @returns {*|Ctx}
*/
param: function(key, value, force) {
if (value !== undefined) {
this.ctx[key] = this.ctx[key] === undefined || force ? value : this.ctx[key];
return this;
} else {
return this.ctx[key];
}
},
/**
* Возвращает/устанавливает содержимое в зависимости от аргументов.
* **force** — задать содержимое даже если оно было задано ранее.
* ```javascript
* bh.match('input', function(ctx) {
* ctx.content({ elem: 'control' });
* });
* ```
* @param {String} [value]
* @param {Boolean} [force]
* @returns {*|Ctx}
*/
content: function(value, force) {
if (arguments.length > 0) {
this.ctx.content = this.ctx.content === undefined || force ? value : this.ctx.content;
return this;
} else {
return this.ctx.content;
}
},
/**
* Возвращает текущий фрагмент BEMJSON-дерева.
* Может использоваться в связке с `return` для враппинга и подобных целей.
* ```javascript
* bh.match('input', function(ctx) {
* return {
* elem: 'wrapper',
* content: ctx.json()
* };
* });
* ```
* @returns {Object|Array}
*/
json: function() {
return this.newCtx || this.ctx;
}
};
}
BH.prototype = {
/**
* Задает опции шаблонизации.
*
* @param {Object} options
* {String} options[jsAttrName] Атрибут, в который записывается значение поля `js`. По умолчанию, `onclick`.
* {String} options[jsAttrScheme] Схема данных для `js`-значения.
* Форматы:
* `js` — значение по умолчанию. Получаем `return { ... }`.
* `json` — JSON-формат. Получаем `{ ... }`.
* @returns {BH}
*/
setOptions: function(options) {
var i;
for (i in options) {
this._options[i] = options[i];
}
if (options.jsAttrName) {
this._optJsAttrName = options.jsAttrName;
}
if (options.jsAttrScheme) {
this._optJsAttrIsJs = options.jsAttrScheme === 'js';
}
return this;
},
/**
* Возвращает опции шаблонизации.
*
* @returns {Object}
*/
getOptions: function() {
return this._options;
},
/**
* Включает/выключает механизм определения зацикливаний.
*
* @param {Boolean} enable
* @returns {BH}
*/
enableInfiniteLoopDetection: function(enable) {
this._infiniteLoopDetection = enable;
return this;
},
/**
* Преобразует BEMJSON в HTML-код.
* @param {Object|Array|String} bemJson
*/
apply: function (bemJson) {
return this.toHtml(this.processBemJson(bemJson));
},
/**
* Объявляет матчер.
* ```javascript
* bh.match('page', function(ctx) {
* ctx.mix([{ block: 'ua' }]);
* ctx.cls('ua_js_no ua_css_standard');
* });
* bh.match('block_mod_modVal', function(ctx) {
* ctx.tag('span');
* });
* bh.match('block__elem', function(ctx) {
* ctx.attr('disabled', 'disabled');
* });
* bh.match('block__elem_elemMod', function(ctx) {
* ctx.mix([{ block: 'link' }]);
* });
* bh.match('block__elem_elemMod_elemModVal', function(ctx) {
* ctx.mod('active', 'yes');
* });
* bh.match('block_blockMod__elem', function(ctx) {
* ctx.param('checked', true);
* });
* bh.match('block_blockMod_blockModVal__elem', function(ctx) {
* ctx.content({
* elem: 'wrapper',
* content: ctx
* };
* });
* ```
* @param {String|Object} expr
* @param {Function} matcher
*/
match: function (expr, matcher) {
if (typeof expr === 'object') {
for (var i in expr) {
this.match(i, expr[i]);
}
return this;
}
matcher.__id = '__func' + (this._lastMatchId++);
this._matchers.push([expr, matcher]);
this._fastMatcher = null;
return this;
},
/**
* Вспомогательный метод для компиляции матчеров с целью их быстрого дальнейшего исполнения.
* @returns {String}
*/
buildMatcher: function () {
/**
* Группирует селекторы матчеров по указанному ключу.
* @param {Array} data
* @param {String} key
* @returns {Object}
*/
function groupBy(data, key) {
var res = {};
for (var i = 0, l = data.length; i < l; i++) {
var item = data[i];
var value = item[key] || '__no_value__';
(res[value] || (res[value] = [])).push(item);
}
return res;
}
var i, j, l;
var res = [''];
var vars = ['bh = this'];
var allMatchers = this._matchers;
var decl, expr, matcherInfo;
var declarations = [], exprBits, blockExprBits;
for (i = allMatchers.length - 1; i >= 0; i--) {
matcherInfo = allMatchers[i];
expr = matcherInfo[0];
Eif (expr) {
vars.push('_m' + i + ' = ms[' + i + '][1]');
decl = { fn: matcherInfo[1], index: i };
if (~expr.indexOf('__')) {
exprBits = expr.split('__');
blockExprBits = exprBits[0].split('_');
decl.block = blockExprBits[0];
Iif (blockExprBits.length > 1) {
decl.blockMod = blockExprBits[1];
decl.blockModVal = blockExprBits[2] || true;
}
exprBits = exprBits[1].split('_');
decl.elem = exprBits[0];
if (exprBits.length > 1) {
decl.mod = exprBits[1];
decl.modVal = exprBits[2] || true;
}
} else {
exprBits = expr.split('_');
decl.block = exprBits[0];
if (exprBits.length > 1) {
decl.mod = exprBits[1];
decl.modVal = exprBits[2] || true;
}
}
declarations.push(decl);
}
}
var declByBlock = groupBy(declarations, 'block');
res.push('var ' + vars.join(', ') + ';');
res.push('function applyMatchers(ctx, json) {');
res.push('var subRes, newCtx;');
res.push('switch (json.block) {');
for (var blockName in declByBlock) {
res.push('case "' + escapeStr(blockName) + '":');
var declsByElem = groupBy(declByBlock[blockName], 'elem');
res.push('switch (json.elem) {');
for (var elemName in declsByElem) {
if (elemName === '__no_value__') {
res.push('case undefined:');
} else {
res.push('case "' + escapeStr(elemName) + '":');
}
var decls = declsByElem[elemName];
for (j = 0, l = decls.length; j < l; j++) {
decl = decls[j];
var fn = decl.fn;
var conds = [];
conds.push('!json.' + fn.__id);
if (decl.mod) {
conds.push('json.mods');
if (decl.modVal === '*') {
conds.push('json.mods["' + escapeStr(decl.mod) + '"]');
} else {
conds.push(
'json.mods["' + escapeStr(decl.mod) + '"] === ' +
(decl.modVal === true || '"' + escapeStr(decl.modVal) + '"')
);
}
}
Iif (decl.blockMod) {
conds.push('json.blockMods');
if (decl.blockModVal === '*') {
conds.push('json.blockMods["' + escapeStr(decl.blockMod) + '"]');
} else {
conds.push(
'json.blockMods["' + escapeStr(decl.blockMod) + '"] === ' +
(decl.blockModVal === true || '"' + escapeStr(decl.blockModVal) + '"')
);
}
}
res.push('if (' + conds.join(' && ') + ') {');
res.push('json.' + fn.__id + ' = true;');
res.push('subRes = _m' + decl.index + '(ctx, json);');
res.push('if (subRes) { return subRes; }');
res.push('if (newCtx = ctx.newCtx) { ctx.newCtx = null; return newCtx; }');
res.push('if (json._stop) return;');
res.push('}');
}
res.push('return;');
}
res.push('}');
res.push('return;');
}
res.push('}');
res.push('};');
res.push('return applyMatchers;');
return res.join('\n');
},
/**
* Раскрывает BEMJSON, превращая его из краткого в полный.
* @param {Object|Array} bemJson
* @param {String} [blockName]
* @param {Boolean} [ignoreContent]
* @returns {Object|Array}
*/
processBemJson: function (bemJson, blockName, ignoreContent) {
if (!this._inited) {
this._init();
}
var resultArr = [bemJson];
var nodes = [{ json: bemJson, arr: resultArr, index: 0, blockName: blockName, blockMods: bemJson.mods || {} }];
var node, json, block, blockMods, i, l, p, child, subRes;
var compiledMatcher = (this._fastMatcher || (this._fastMatcher = Function('ms', this.buildMatcher())(this._matchers)));
var processContent = !ignoreContent;
var infiniteLoopDetection = this._infiniteLoopDetection;
/**
* Враппер для json-узла.
* @constructor
*/
function Ctx() {
this.ctx = null;
this.newCtx = null;
}
Ctx.prototype = this.utils;
var ctx = new Ctx();
while (node = nodes.shift()) {
json = node.json;
block = node.blockName;
blockMods = node.blockMods;
if (Array.isArray(json)) {
for (i = 0, l = json.length; i < l; i++) {
child = json[i];
Eif (child !== false && child != null && typeof child === 'object') {
nodes.push({ json: child, arr: json, index: i, blockName: block, blockMods: blockMods, parentNode: node });
}
}
} else {
var content, stopProcess = false;
if (json.elem) {
block = json.block = json.block || block;
blockMods = json.blockMods = json.blockMods || blockMods;
if (json.elemMods) {
json.mods = json.elemMods;
}
} else if (json.block) {
block = json.block;
blockMods = json.mods || (json.mods = {});
}
if (json.block) {
if (infiniteLoopDetection) {
json.__processCounter = (json.__processCounter || 0) + 1;
compiledMatcher.__processCounter = (compiledMatcher.__processCounter || 0) + 1;
if (json.__processCounter > 100) {
throw new Error('Infinite json loop detected at "' + json.block + (json.elem ? '__' + json.elem : '') + '".');
}
if (compiledMatcher.__processCounter > 1000) {
throw new Error('Infinite matcher loop detected at "' + json.block + (json.elem ? '__' + json.elem : '') + '".');
}
}
subRes = null;
Eif (!json._stop) {
ctx.node = node;
ctx.ctx = json;
subRes = compiledMatcher(ctx, json);
if (subRes) {
json = subRes;
node.json = json;
node.blockName = block;
node.blockMods = blockMods;
nodes.push(node);
stopProcess = true;
}
}
}
if (!stopProcess) {
Iif (Array.isArray(json)) {
node.json = json;
node.blockName = block;
node.blockMods = blockMods;
nodes.push(node);
} else {
if (processContent && (content = json.content)) {
if (Array.isArray(content)) {
var flatten;
do {
flatten = false;
for (i = 0, l = content.length; i < l; i++) {
if (Array.isArray(content[i])) {
flatten = true;
break;
}
}
if (flatten) {
json.content = content = content.concat.apply([], content);
}
} while (flatten);
for (i = 0, l = content.length, p = l - 1; i < l; i++) {
child = content[i];
if (child !== false && child != null && typeof child === 'object') {
nodes.push({ json: child, arr: content, index: i, blockName: block, blockMods: blockMods, parentNode: node });
}
}
} else {
nodes.push({ json: content, arr: json, index: 'content', blockName: block, blockMods: blockMods, parentNode: node });
}
}
}
}
}
node.arr[node.index] = json;
}
return resultArr[0];
},
/**
* Превращает раскрытый BEMJSON в HTML.
* @param {Object|Array|String} json
* @returns {String}
*/
toHtml: function (json) {
var res, i, l, item;
Iif (json === false || json == null) return '';
if (typeof json !== 'object') {
return json;
} else if (Array.isArray(json)) {
res = '';
for (i = 0, l = json.length; i < l; i++) {
item = json[i];
Eif (item !== false && item != null) {
res += this.toHtml(item);
}
}
return res;
} else {
if (typeof json.tag !== 'undefined' && !json.tag) {
return json.content ? this.toHtml(json.content) : '';
}
if (json.mix && !Array.isArray(json.mix)) {
json.mix = [json.mix];
}
var cls = json.bem !== false && json.block ? toBemCssClasses(json) : '',
jattr, jval, attrs = '', jsParams, hasMixJsParams = false;
if (jattr = json.attrs) {
for (i in jattr) {
jval = jattr[i];
if (jval !== null && jval !== undefined) {
attrs += ' ' + i + '="' + escapeAttr(jval) + '"';
}
}
}
if (json.js) {
(jsParams = {})[json.block + (json.elem ? '__' + json.elem : '')] = json.js === true ? {} : json.js;
}
var mixes = json.mix;
if (mixes && mixes.length) {
for (i = 0, l = mixes.length; i < l; i++) {
var mix = mixes[i];
Iif (mix && mix.js) {
(jsParams = jsParams || {})[(mix.block || json.block) + (mix.elem ? '__' + mix.elem : '')] = mix.js === true ? {} : mix.js;
hasMixJsParams = true;
}
}
}
if (jsParams) {
Eif (json.bem !== false) {
cls = cls + ' i-bem';
}
var jsData = (!hasMixJsParams && json.js === true ?
'{"' + json.block + (json.elem ? '__' + json.elem : '') + '":{}}' :
escapeAttr(JSON.stringify(jsParams)));
attrs += ' ' + (json.jsAttr || this._optJsAttrName) + '="' +
(this._optJsAttrIsJs ? 'return ' + jsData + ';' : jsData) + '"';
}
if (json.cls) {
cls = cls ? cls + ' ' + json.cls : json.cls;
}
var content, tag = (json.tag || 'div');
res = '<' + tag + (cls ? ' class="' + escapeAttr(cls) + '"' : '') + (attrs ? attrs : '');
if (selfCloseHtmlTags[tag]) {
res += '/>';
} else {
res += '>';
if ((content = json.content) != null) {
if (Array.isArray(content)) {
for (i = 0, l = content.length; i < l; i++) {
item = content[i];
Eif (item !== false && item != null) {
res += this.toHtml(item);
}
}
} else {
res += this.toHtml(content);
}
}
res += '</' + tag + '>';
}
return res;
}
},
/**
* Инициализация BH.
*/
_init: function() {
this._inited = true;
/*
Копируем ссылку на BEM.I18N в bh.lib.i18n, если это возможно.
*/
Iif (typeof BEM !== 'undefined' && typeof BEM.I18N !== 'undefined') {
this.lib.i18n = this.lib.i18n || BEM.I18N;
}
}
};
/**
* @deprecated
*/
BH.prototype.processBemjson = BH.prototype.processBemJson;
var selfCloseHtmlTags = {
area: 1,
base: 1,
br: 1,
col: 1,
command: 1,
embed: 1,
hr: 1,
img: 1,
input: 1,
keygen: 1,
link: 1,
meta: 1,
param: 1,
source: 1,
wbr: 1
};
var escapeAttr = function (attrVal) {
attrVal += '';
if (~attrVal.indexOf('&')) {
attrVal = attrVal.replace(/&/g, '&');
}
if (~attrVal.indexOf('"')) {
attrVal = attrVal.replace(/"/g, '"');
}
return attrVal;
};
var escapeStr = function (str) {
str += '';
if (~str.indexOf('\\')) {
str = str.replace(/\\/g, '\\\\');
}
if (~str.indexOf('"')) {
str = str.replace(/"/g, '\\"');
}
return str;
};
var toBemCssClasses = function (json, blockName) {
var mods, mod, res,
base = (json.block || blockName) + (json.elem ? '__' + json.elem : ''),
mix, i, l;
res = (base === blockName) ? '' : base;
if (mods = json.mods || json.elem && json.elemMods) {
for (i in mods) {
if (mod = mods[i]) {
res += (res ? ' ' : '') + base + '_' + i + (mod === true ? '' : '_' + mod);
}
}
}
if ((mix = json.mix) && (l = mix.length)) {
for (i = 0; i < l; i++) {
if (!mix[i]) continue;
res += ' ' + toBemCssClasses(mix[i], json.block || blockName);
}
}
return res;
};
return BH;
})();
Eif (typeof module !== 'undefined') {
module.exports = BH;
}
|