-
Notifications
You must be signed in to change notification settings - Fork 1
/
bbt.js
6566 lines (6563 loc) · 265 KB
/
bbt.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
// resources(16):
// [function] ../../src/basis/template.js -> 8.js
// [function] ../../src/basis/devpanel.js -> 0.js
// [function] ../../src/basis/template/html.js -> 2.js
// [function] ../../src/basis/l10n.js -> 3.js
// [function] ../../src/basis/event.js -> 4.js
// [function] ../../src/basis/template/htmlfgen.js -> 5.js
// [function] ../../src/basis/template/const.js -> 6.js
// [function] ../../src/basis/template/namespace.js -> 7.js
// [function] bbt.js -> 1.js
// [function] ../../src/basis/template/declaration.js -> 9.js
// [function] ../../src/basis/template/tokenize.js -> e.js
// [function] ../../src/basis/template/isolateCss.js -> f.js
// [function] ../../src/basis/template/store.js -> a.js
// [function] ../../src/basis/template/theme.js -> b.js
// [function] ../../src/basis/template/buildDom.js -> c.js
// [function] ../../src/basis/dom/event.js -> d.js
//
// filelist(1):
// /scripts/release-configs/bbt.js
//
(function(){
"use strict";
var __namespace_map__ = {"0.js":"basis.devpanel","1.js":"bbt","2.js":"basis.template.html","3.js":"basis.l10n","4.js":"basis.event","5.js":"basis.template.htmlfgen","6.js":"basis.template.const","7.js":"basis.template.namespace","8.js":"basis.template","9.js":"basis.template.declaration","a.js":"basis.template.store","b.js":"basis.template.theme","c.js":"basis.template.buildDom","d.js":"basis.dom.event"};
var bbt;
var __resources__ = {
"8.js": function(exports, module, basis, global, __filename, __dirname, require, resource, asset) {
var namespace = "basis.template";
var document = global.document;
var Class = basis.Class;
var cleaner = basis.cleaner;
var path = basis.path;
var consts = basis.require("./6.js");
var DECLARATION_VERSION = basis.require("./9.js").VERSION;
var getDeclFromSource = basis.require("./9.js").getDeclFromSource;
var makeDeclaration = basis.require("./9.js").makeDeclaration;
var setIsolatePrefixGenerator = basis.require("./9.js").setIsolatePrefixGenerator;
var store = basis.require("./a.js");
var theme = basis.require("./b.js");
var getSourceByPath = theme.get;
var templateList = [];
var sourceByDocumentId = {};
function resolveSourceByDocumentId(sourceId) {
var resource = sourceByDocumentId[sourceId];
if (!resource) {
var host = document.getElementById(sourceId);
var source = "";
if (host && host.tagName == "SCRIPT" && host.type == "text/basis-template") source = host.textContent || host.text; else if (!host) basis.dev.warn("Template script element with id `" + sourceId + "` not found"); else basis.dev.warn('Template should be declared in <script type="text/basis-template"> element (id `' + sourceId + "`)");
resource = sourceByDocumentId[sourceId] = basis.resource.virtual("tmpl", source || "");
resource.id = sourceId;
resource.url = '<script id="' + sourceId + '"/>';
}
return resource;
}
function resolveResource(ref, baseURI) {
if (/^#\d+$/.test(ref)) return templateList[ref.substr(1)];
if (/^id:/.test(ref)) return resolveSourceByDocumentId(ref.substr(3));
if (/^[a-z0-9\.]+$/i.test(ref) && !/\.tmpl$/.test(ref)) return getSourceByPath(ref);
return basis.resource(basis.resource.resolveURI(ref, baseURI, '<b:include src="{url}"/>'));
}
function templateSourceUpdate() {
if (this.destroyBuilder) buildTemplate.call(this);
var cursor = this;
while (cursor = cursor.attaches_) cursor.handler.call(cursor.context);
}
function buildTemplate() {
var declaration = getDeclFromSource(this.source, this.baseURI, false, {
isolate: this.getIsolatePrefix()
});
var destroyBuilder = this.destroyBuilder;
var instances = {};
var funcs = this.builder(declaration.tokens, instances);
this.createInstance = funcs.createInstance;
this.clearInstance = funcs.destroyInstance;
this.destroyBuilder = funcs.destroy;
store.add(this.templateId, this, instances);
this.instances_ = instances;
this.decl_ = declaration;
var newDeps = declaration.deps;
var oldDeps = this.deps_;
this.deps_ = newDeps;
if (oldDeps) for (var i = 0, dep; dep = oldDeps[i]; i++) dep.bindingBridge.detach(dep, templateSourceUpdate, this);
if (newDeps) for (var i = 0, dep; dep = newDeps[i]; i++) dep.bindingBridge.attach(dep, templateSourceUpdate, this);
var newResources = declaration.resources;
var oldResources = this.resources;
this.resources = newResources;
if (newResources) for (var i = 0, url; url = newResources[i]; i++) {
var resource = basis.resource(url).fetch();
if (typeof resource.startUse == "function") resource.startUse();
}
if (oldResources) for (var i = 0, url; url = oldResources[i]; i++) {
var resource = basis.resource(url).fetch();
if (typeof resource.stopUse == "function") resource.stopUse();
}
if (destroyBuilder) destroyBuilder(true);
}
var Template = Class(null, {
className: namespace + ".Template",
__extend__: function(value) {
if (value instanceof Template) return value;
if (value instanceof TemplateSwitchConfig) return new TemplateSwitcher(value);
return new Template(value);
},
source: "",
baseURI: "",
url: "",
attaches_: null,
init: function(source) {
if (templateList.length == 4096) throw "Too many templates (maximum 4096)";
this.setSource(source || "");
this.templateId = templateList.push(this) - 1;
},
bindingBridge: {
attach: function(template, handler, context) {
var cursor = template;
while (cursor = cursor.attaches_) if (cursor.handler === handler && cursor.context === context) basis.dev.warn("basis.template.Template#bindingBridge.attach: duplicate handler & context pair");
template.attaches_ = {
handler: handler,
context: context,
attaches_: template.attaches_
};
},
detach: function(template, handler, context) {
var cursor = template;
var prev;
while (prev = cursor, cursor = cursor.attaches_) if (cursor.handler === handler && cursor.context === context) {
prev.attaches_ = cursor.attaches_;
return;
}
basis.dev.warn("basis.template.Template#bindingBridge.detach: handler & context pair not found, nothing was removed");
},
get: function(template) {
var source = template.source;
return source && source.bindingBridge ? source.bindingBridge.get(source) : source;
}
},
createInstance: function(object, actionCallback, updateCallback, bindings, bindingInterface) {
buildTemplate.call(this);
return this.createInstance(object, actionCallback, updateCallback, bindings, bindingInterface);
},
clearInstance: function() {},
getIsolatePrefix: function() {
return "i" + this.templateId + "__";
},
setSource: function(source) {
var oldSource = this.source;
if (oldSource != source) {
if (typeof source == "string") {
var m = source.match(/^([a-z]+):/);
if (m) {
source = source.substr(m[0].length);
switch (m[1]) {
case "id":
source = resolveSourceByDocumentId(source);
break;
case "path":
source = getSourceByPath(source);
break;
default:
basis.dev.warn(namespace + ".Template.setSource: Unknown prefix " + m[1] + " for template source was ingnored.");
}
}
}
if (oldSource && oldSource.bindingBridge) {
this.url = "";
this.baseURI = "";
oldSource.bindingBridge.detach(oldSource, templateSourceUpdate, this);
}
if (source && source.bindingBridge) {
if (source.url) {
this.url = source.url;
this.baseURI = path.dirname(source.url) + "/";
}
source.bindingBridge.attach(source, templateSourceUpdate, this);
}
this.source = source;
templateSourceUpdate.call(this);
}
},
destroy: function() {
if (this.destroyBuilder) {
store.remove(this.templateId);
this.destroyBuilder();
}
this.attaches_ = null;
this.createInstance = null;
this.resources = null;
this.source = null;
this.instances_ = null;
this.decl_ = null;
}
});
var TemplateSwitchConfig = function(config) {
basis.object.extend(this, config);
};
var TemplateSwitcher = basis.Class(null, {
className: namespace + ".TemplateSwitcher",
ruleRet_: null,
templates_: null,
templateClass: Template,
ruleEvents: null,
rule: String,
init: function(config) {
this.ruleRet_ = [];
this.templates_ = [];
this.rule = config.rule;
var events = config.events;
if (events && events.length) {
this.ruleEvents = {};
for (var i = 0, eventName; eventName = events[i]; i++) this.ruleEvents[eventName] = true;
}
cleaner.add(this);
},
resolve: function(object) {
var ret = this.rule(object);
var idx = this.ruleRet_.indexOf(ret);
if (idx == -1) {
this.ruleRet_.push(ret);
idx = this.templates_.push(new this.templateClass(ret)) - 1;
}
return this.templates_[idx];
},
destroy: function() {
this.rule = null;
this.templates_ = null;
this.ruleRet_ = null;
}
});
function switcher(events, rule) {
if (!rule) {
rule = events;
events = null;
}
if (typeof events == "string") events = events.split(/\s+/);
return new TemplateSwitchConfig({
rule: rule,
events: events
});
}
cleaner.add({
destroy: function() {
for (var i = 0, template; template = templateList[i]; i++) template.destroy();
templateList = null;
}
});
module.exports = {
DECLARATION_VERSION: DECLARATION_VERSION,
TYPE_ELEMENT: consts.TYPE_ELEMENT,
TYPE_ATTRIBUTE: consts.TYPE_ATTRIBUTE,
TYPE_ATTRIBUTE_CLASS: consts.TYPE_ATTRIBUTE_CLASS,
TYPE_ATTRIBUTE_STYLE: consts.TYPE_ATTRIBUTE_STYLE,
TYPE_ATTRIBUTE_EVENT: consts.TYPE_ATTRIBUTE_EVENT,
TYPE_TEXT: consts.TYPE_TEXT,
TYPE_COMMENT: consts.TYPE_COMMENT,
TOKEN_TYPE: consts.TOKEN_TYPE,
TOKEN_BINDINGS: consts.TOKEN_BINDINGS,
TOKEN_REFS: consts.TOKEN_REFS,
ATTR_NAME: consts.ATTR_NAME,
ATTR_VALUE: consts.ATTR_VALUE,
ATTR_NAME_BY_TYPE: consts.ATTR_NAME_BY_TYPE,
CLASS_BINDING_ENUM: consts.CLASS_BINDING_ENUM,
CLASS_BINDING_BOOL: consts.CLASS_BINDING_BOOL,
ELEMENT_NAME: consts.ELEMENT_NAME,
ELEMENT_ATTRS: consts.ELEMENT_ATTRIBUTES_AND_CHILDREN,
ELEMENT_ATTRIBUTES_AND_CHILDREN: consts.ELEMENT_ATTRIBUTES_AND_CHILDREN,
TEXT_VALUE: consts.TEXT_VALUE,
COMMENT_VALUE: consts.COMMENT_VALUE,
TemplateSwitchConfig: TemplateSwitchConfig,
TemplateSwitcher: TemplateSwitcher,
Template: Template,
switcher: switcher,
getDeclFromSource: getDeclFromSource,
makeDeclaration: makeDeclaration,
resolveResource: resolveResource,
setIsolatePrefixGenerator: setIsolatePrefixGenerator,
getDebugInfoById: store.getDebugInfoById,
getTemplateCount: function() {
return templateList.length;
},
resolveTemplateById: store.resolveTemplateById,
resolveObjectById: store.resolveObjectById,
resolveTmplById: store.resolveTmplById,
SourceWrapper: theme.SourceWrapper,
Theme: theme.Theme,
theme: theme.theme,
getThemeList: theme.getThemeList,
currentTheme: theme.currentTheme,
setTheme: theme.setTheme,
onThemeChange: theme.onThemeChange,
define: theme.define,
get: theme.get,
getPathList: theme.getPathList
};
},
"0.js": function(exports, module, basis, global, __filename, __dirname, require, resource, asset) {
if (basis.filename_) {
basis.createSandbox({
inspect: basis,
devInfoResolver: basis.config.devInfoResolver,
modules: {
devpanel: {
autoload: true,
path: basis.path.dirname(basis.filename_) + "/devpanel/",
filename: "index.js"
}
}
});
}
},
"2.js": function(exports, module, basis, global, __filename, __dirname, require, resource, asset) {
var namespace = "basis.template.html";
var document = global.document;
var Node = global.Node;
var camelize = basis.string.camelize;
var isMarkupToken = basis.require("./3.js").isMarkupToken;
var getL10nToken = basis.require("./3.js").token;
var getFunctions = basis.require("./5.js").getFunctions;
var basisTemplate = basis.require("./8.js");
var TemplateSwitchConfig = basisTemplate.TemplateSwitchConfig;
var TemplateSwitcher = basisTemplate.TemplateSwitcher;
var Template = basisTemplate.Template;
var getSourceByPath = basisTemplate.get;
var buildDOM = basis.require("./c.js");
var CLONE_NORMALIZATION_TEXT_BUG = basis.require("./6.js").CLONE_NORMALIZATION_TEXT_BUG;
var IS_SET_STYLE_SAFE = !!function() {
try {
return document.documentElement.style.color = "x";
} catch (e) {}
}();
var l10nTemplate = {};
var l10nTemplateSource = {};
function getSourceFromL10nToken(token) {
var dict = token.dictionary;
var url = dict.resource ? dict.resource.url : "dictionary" + dict.basisObjectId;
var name = token.getName();
var id = name + "@" + url;
var result = l10nTemplateSource[id];
var sourceWrapper;
if (!result) {
var sourceToken = dict.token(name);
result = l10nTemplateSource[id] = sourceToken.as(function(value) {
if (sourceToken.getType() == "markup") {
var parentType = sourceToken.getParentType();
if (typeof value == "string" && (parentType == "plural" || parentType == "plural-markup")) value = value.replace(/\{#\}/g, "{__templateContext}");
if (value != this.value) if (sourceWrapper) {
sourceWrapper.detach(sourceToken, sourceToken.apply);
sourceWrapper = null;
}
if (value && String(value).substr(0, 5) == "path:") {
sourceWrapper = getSourceByPath(value.substr(5));
sourceWrapper.attach(sourceToken, sourceToken.apply);
}
return sourceWrapper ? sourceWrapper.bindingBridge.get(sourceWrapper) : value;
}
return this.value;
});
result.id = "{l10n:" + id + "}";
result.url = url + ":" + name;
}
return result;
}
function getL10nHtmlTemplate(token) {
if (typeof token == "string") token = getL10nToken(token);
if (!token) return null;
var templateSource = getSourceFromL10nToken(token);
var id = templateSource.id;
var htmlTemplate = l10nTemplate[id];
if (!htmlTemplate) htmlTemplate = l10nTemplate[id] = new HtmlTemplate(templateSource);
return htmlTemplate;
}
var builder = function() {
var WHITESPACE = /\s+/;
var CLASSLIST_SUPPORTED = global.DOMTokenList && document && document.documentElement.classList instanceof global.DOMTokenList;
var W3C_DOM_NODE_SUPPORTED = function() {
try {
return document instanceof Node;
} catch (e) {}
}() || false;
function collapseDomFragment(fragment) {
var startMarker = fragment.startMarker;
var endMarker = fragment.endMarker;
var cursor = startMarker.nextSibling;
while (cursor && cursor !== endMarker) {
var tmp = cursor;
cursor = cursor.nextSibling;
fragment.appendChild(tmp);
}
endMarker.parentNode.removeChild(endMarker);
fragment.startMarker = null;
fragment.endMarker = null;
return startMarker;
}
var bind_node = W3C_DOM_NODE_SUPPORTED ? function(domRef, oldNode, newValue, domNodeBindingProhibited) {
var newNode = !domNodeBindingProhibited && newValue && newValue instanceof Node ? newValue : domRef;
if (newNode !== oldNode) {
if (newNode.nodeType === 11 && !newNode.startMarker) {
newNode.startMarker = document.createTextNode("");
newNode.endMarker = document.createTextNode("");
newNode.insertBefore(newNode.startMarker, newNode.firstChild);
newNode.appendChild(newNode.endMarker);
}
if (oldNode.nodeType === 11 && oldNode.startMarker) oldNode = collapseDomFragment(oldNode);
oldNode.parentNode.replaceChild(newNode, oldNode);
}
return newNode;
} : function(domRef, oldNode, newValue, domNodeBindingProhibited) {
var newNode = !domNodeBindingProhibited && newValue && typeof newValue == "object" ? newValue : domRef;
if (newNode !== oldNode) {
try {
oldNode.parentNode.replaceChild(newNode, oldNode);
} catch (e) {
newNode = domRef;
if (oldNode !== newNode) oldNode.parentNode.replaceChild(newNode, oldNode);
}
}
return newNode;
};
var bind_element = function(domRef, oldNode, newValue, domNodeBindingProhibited) {
var newNode = bind_node(domRef, oldNode, newValue, domNodeBindingProhibited);
if (newNode === domRef && typeof newValue == "string") domRef.innerHTML = newValue;
return newNode;
};
var bind_comment = bind_node;
var bind_textNode = function(domRef, oldNode, newValue, domNodeBindingProhibited) {
var newNode = bind_node(domRef, oldNode, newValue, domNodeBindingProhibited);
if (newNode === domRef) domRef.nodeValue = String(newValue);
return newNode;
};
var bind_attrClass = CLASSLIST_SUPPORTED ? normalAttrClass : legacyAttrClass;
function normalAttrClass(domRef, oldClass, newValue, anim) {
var classList = domRef.classList;
if (!classList) return legacyAttrClass(domRef, oldClass, newValue, anim);
var newClass = newValue || "";
if (newClass != oldClass) {
if (oldClass) domRef.classList.remove(oldClass);
if (newClass) {
domRef.classList.add(newClass);
if (anim) {
domRef.classList.add(newClass + "-anim");
basis.nextTick(function() {
domRef.classList.remove(newClass + "-anim");
});
}
}
}
return newClass;
}
function legacyAttrClass(domRef, oldClass, newValue, anim) {
var newClass = newValue || "";
if (newClass != oldClass) {
var className = domRef.className;
var classNameIsObject = typeof className != "string";
var classList;
if (classNameIsObject) className = className.baseVal;
classList = className.split(WHITESPACE);
if (oldClass) basis.array.remove(classList, oldClass);
if (newClass) {
classList.push(newClass);
if (anim) {
basis.array.add(classList, newClass + "-anim");
basis.nextTick(function() {
var classList = (classNameIsObject ? domRef.className.baseVal : domRef.className).split(WHITESPACE);
basis.array.remove(classList, newClass + "-anim");
if (classNameIsObject) domRef.className.baseVal = classList.join(" "); else domRef.className = classList.join(" ");
});
}
}
if (classNameIsObject) domRef.className.baseVal = classList.join(" "); else domRef.className = classList.join(" ");
}
return newClass;
}
var bind_attrStyle = IS_SET_STYLE_SAFE ? function(domRef, propertyName, oldValue, newValue) {
if (oldValue !== newValue) domRef.style[camelize(propertyName)] = newValue;
return newValue;
} : function(domRef, propertyName, oldValue, newValue) {
if (oldValue !== newValue) {
try {
domRef.style[camelize(propertyName)] = newValue;
} catch (e) {}
}
return newValue;
};
var bind_attr = function(domRef, attrName, oldValue, newValue) {
if (oldValue !== newValue) {
if (newValue) domRef.setAttribute(attrName, newValue); else domRef.removeAttribute(attrName);
}
return newValue;
};
var bind_attrNS = function(domRef, namespace, attrName, oldValue, newValue) {
if (oldValue !== newValue) {
if (newValue) domRef.setAttributeNS(namespace, attrName, newValue); else domRef.removeAttributeNS(namespace, attrName);
}
return newValue;
};
function updateAttach() {
this.set(this.name, this.value);
}
function resolveValue(bindingName, value, Attaches) {
var bridge = value && value.bindingBridge;
var oldAttach = this.attaches && this.attaches[bindingName];
var tmpl = null;
if (bridge || oldAttach) {
if (bridge) {
var isMarkup = isMarkupToken(value);
var template;
if (isMarkup) template = getL10nHtmlTemplate(value);
if (!oldAttach || oldAttach.value !== value || oldAttach.template !== template) {
if (oldAttach) {
if (oldAttach.tmpl) oldAttach.template.clearInstance(oldAttach.tmpl);
oldAttach.value.bindingBridge.detach(oldAttach.value, updateAttach, oldAttach);
}
if (template) {
var context = this.context;
var bindings = this.bindings;
var onAction = this.action;
var bindingInterface = this.bindingInterface;
tmpl = template.createInstance(context, onAction, function onRebuild() {
tmpl = newAttach.tmpl = template.createInstance(context, onAction, onRebuild, bindings, bindingInterface);
tmpl.parent = tmpl.element.parentNode || tmpl.element;
updateAttach.call(newAttach);
}, bindings, bindingInterface);
tmpl.parent = tmpl.element.parentNode || tmpl.element;
}
if (!this.attaches) this.attaches = new Attaches;
var newAttach = this.attaches[bindingName] = {
name: bindingName,
value: value,
template: template,
tmpl: tmpl,
set: this.tmpl.set
};
bridge.attach(value, updateAttach, newAttach);
} else tmpl = value && isMarkupToken(value) ? oldAttach.tmpl : null;
if (tmpl) {
tmpl.set("__templateContext", value.value);
return tmpl.parent;
}
value = bridge.get(value);
} else {
if (oldAttach) {
if (oldAttach.tmpl) oldAttach.template.clearInstance(oldAttach.tmpl);
oldAttach.value.bindingBridge.detach(oldAttach.value, updateAttach, oldAttach);
this.attaches[bindingName] = null;
}
}
}
return value;
}
function createBindingUpdater(names, getters) {
var name1 = names[0];
var name2 = names[1];
var getter1 = getters[name1];
var getter2 = getters[name2];
switch (names.length) {
case 1:
return function bindingUpdater1(object) {
this(name1, getter1(object));
};
case 2:
return function bindingUpdater2(object) {
this(name1, getter1(object));
this(name2, getter2(object));
};
default:
var getters_ = names.map(function(name) {
return getters[name];
});
return function bindingUpdaterN(object) {
for (var i = 0; i < names.length; i++) this(names[i], getters_[i](object));
};
}
}
function makeHandler(events, getters) {
for (var name in events) events[name] = createBindingUpdater(events[name], getters);
return name ? events : null;
}
function createBindingFunction(keys) {
var bindingCache = {};
return function getBinding(instance, set) {
var bindings = instance.bindings;
if (!bindings) return {};
var cacheId = "bindingId" in bindings ? bindings.bindingId : null;
if (!cacheId) basis.dev.warn("basis.template.Template.getBinding: bindings has no bindingId property, cache is not used");
var result = bindingCache[cacheId];
if (!result) {
var names = [];
var getters = {};
var events = {};
for (var i = 0, bindingName; bindingName = keys[i]; i++) {
var binding = bindings[bindingName];
var getter = binding && binding.getter;
if (getter) {
getters[bindingName] = getter;
names.push(bindingName);
if (binding.events) {
var eventList = String(binding.events).trim().split(/\s+|\s*,\s*/);
for (var j = 0, eventName; eventName = eventList[j]; j++) {
if (events[eventName]) events[eventName].push(bindingName); else events[eventName] = [ bindingName ];
}
}
}
}
result = {
names: names,
sync: createBindingUpdater(names, getters),
handler: makeHandler(events, getters)
};
if (cacheId) bindingCache[cacheId] = result;
}
if (set) result.sync.call(set, instance.context);
if (!instance.bindingInterface) return;
if (result.handler) instance.bindingInterface.attach(instance.context, result.handler, set);
return result.handler;
};
}
var tools = {
bind_textNode: bind_textNode,
bind_node: bind_node,
bind_element: bind_element,
bind_comment: bind_comment,
bind_attr: bind_attr,
bind_attrNS: bind_attrNS,
bind_attrClass: bind_attrClass,
bind_attrStyle: bind_attrStyle,
resolve: resolveValue,
l10nToken: getL10nToken
};
return function(tokens, instances) {
var fn = getFunctions(tokens, true, this.source.url, tokens.source_, !CLONE_NORMALIZATION_TEXT_BUG);
var hasL10n = fn.createL10nSync;
var initInstance;
var l10nProtoSync;
var l10nMap = {};
var l10nLinks = [];
var l10nMarkupTokens = [];
var seed = 0;
var proto = {
cloneNode: function() {
if (seed == 1) return buildDOM(tokens);
proto = buildDOM(tokens);
if (hasL10n) {
l10nProtoSync = fn.createL10nSync(proto, l10nMap, bind_attr, CLONE_NORMALIZATION_TEXT_BUG);
for (var i = 0, l10nToken; l10nToken = l10nLinks[i]; i++) l10nProtoSync(l10nToken.path, l10nMap[l10nToken.path]);
}
return proto.cloneNode(true);
}
};
var createDOM = function() {
return proto.cloneNode(true);
};
if (hasL10n) {
var initL10n = function(set) {
for (var i = 0, token; token = l10nLinks[i]; i++) set(token.path, l10nMap[token.path]);
};
var linkHandler = function(value) {
var isMarkup = isMarkupToken(this.token);
if (isMarkup) basis.array.add(l10nMarkupTokens, this); else basis.array.remove(l10nMarkupTokens, this);
l10nMap[this.path] = isMarkup ? undefined : value == null ? "{" + this.path + "}" : value;
if (l10nProtoSync) l10nProtoSync(this.path, l10nMap[this.path]);
for (var key in instances) instances[key].tmpl.set(this.path, isMarkup ? this.token : value);
};
l10nLinks = fn.l10nKeys.map(function(key) {
var token = getL10nToken(key);
var link = {
path: key,
token: token,
handler: linkHandler
};
token.attach(linkHandler, link);
if (isMarkupToken(token)) l10nMarkupTokens.push(link); else l10nMap[key] = token.value == null ? "{" + key + "}" : token.value;
return link;
});
}
initInstance = fn.createInstanceFactory(this.templateId, createDOM, tools, l10nMap, l10nMarkupTokens, createBindingFunction(fn.keys), CLONE_NORMALIZATION_TEXT_BUG);
return {
createInstance: function(obj, onAction, onRebuild, bindings, bindingInterface) {
var instanceId = seed++;
var instance = {
context: obj,
action: onAction,
rebuild: onRebuild,
handler: null,
bindings: bindings,
bindingInterface: bindingInterface,
attaches: null,
compute: null,
tmpl: null
};
initInstance(instanceId, instance, !instanceId ? initL10n : null);
instances[instanceId] = instance;
return instance.tmpl;
},
destroyInstance: function(tmpl) {
var instanceId = tmpl.templateId_;
var instance = instances[instanceId];
if (instance) {
if (instance.handler) instance.bindingInterface.detach(instance.context, instance.handler, instance.tmpl.set);
if (instance.compute) {
for (var i = 0; i < instance.compute.length; i++) instance.compute[i].destroy();
instance.compute = null;
}
for (var key in instance.attaches) resolveValue.call(instance, key, null);
delete instances[instanceId];
}
},
destroy: function(rebuild) {
for (var i = 0, link; link = l10nLinks[i]; i++) link.token.detach(link.handler, link);
for (var key in instances) {
var instance = instances[key];
if (rebuild && instance.rebuild) instance.rebuild.call(instance.context);
if (!rebuild || key in instances) {
if (instance.handler) instance.bindingInterface.detach(instance.context, instance.handler, instance.tmpl.set);
for (var key in instance.attaches) resolveValue.call(key, null);
}
}
fn = null;
proto = null;
l10nMap = null;
l10nLinks = null;
l10nProtoSync = null;
instances = null;
}
};
};
}();
var HtmlTemplate = Template.subclass({
className: namespace + ".Template",
__extend__: function(value) {
if (value instanceof HtmlTemplate) return value;
if (value instanceof TemplateSwitchConfig) return new HtmlTemplateSwitcher(value);
return new HtmlTemplate(value);
},
builder: builder
});
var HtmlTemplateSwitcher = TemplateSwitcher.subclass({
className: namespace + ".TemplateSwitcher",
templateClass: HtmlTemplate
});
module.exports = {
Template: HtmlTemplate,
TemplateSwitcher: HtmlTemplateSwitcher
};
},
"3.js": function(exports, module, basis, global, __filename, __dirname, require, resource, asset) {
var namespace = "basis.l10n";
var Class = basis.Class;
var Emitter = basis.require("./4.js").Emitter;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var autoFetchDictionaryResource = true;
basis.resource.extensions[".l10n"] = function(content, url) {
var dictionary;
autoFetchDictionaryResource = false;
dictionary = resolveDictionary(url);
autoFetchDictionaryResource = true;
return dictionary.update(basis.resource.extensions[".json"](content, url));
};
var tokenIndex = [];
var tokenComputeFn = {};
var basisTokenPrototypeSet = basis.Token.prototype.set;
var tokenType = {
"default": true,
plural: true,
markup: true,
"plural-markup": true,
"enum-markup": true
};
var nestedType = {
"default": "default",
plural: "default",
markup: "default",
"plural-markup": "markup",
"enum-markup": "markup"
};
var isPluralType = {
plural: true,
"plural-markup": true
};
var ComputeToken = Class(basis.Token, {
className: namespace + ".ComputeToken",
dictionary: null,
token: null,
parent: "",
init: function(value) {
this.token.computeTokens[this.basisObjectId] = this;
basis.Token.prototype.init.call(this, value);
},
get: function() {
var value = this.dictionary.getValue(this.getName());
if (isPluralType[this.token.getType()]) value = String(value).replace(/\{#\}/g, this.value);
return value;
},
getName: function() {
var key = this.value;
if (isPluralType[this.token.getType()]) key = cultures[currentCulture].plural(key);
return this.parent + "." + key;
},
getType: function() {
var type = this.token.getType();
return this.dictionary.types[this.getName()] || nestedType[type] || "default";
},
getParentType: function() {
return this.token.getType();
},
toString: function() {
return this.get();
},
destroy: function() {
delete this.token.computeTokens[this.basisObjectId];
basis.Token.prototype.destroy.call(this);
}
});
var Token = Class(basis.Token, {
className: namespace + ".Token",
index: NaN,
dictionary: null,
name: "",
type: "default",
computeTokens: null,
computeTokenClass: null,
init: function(dictionary, tokenName, value) {
basis.Token.prototype.init.call(this, value);
this.index = tokenIndex.push(this) - 1;
this.name = tokenName;
this.parent = tokenName.replace(/(^|\.)[^.]+$/, "");
this.dictionary = dictionary;
this.computeTokens = {};
},
toString: function() {
return this.get();
},
apply: function() {
for (var key in this.computeTokens) this.computeTokens[key].apply();
basis.Token.prototype.apply.call(this);
},
set: function() {
basis.dev.warn("basis.l10n: Value for l10n token can't be set directly, but through dictionary update only");
},
getName: function() {
return this.name;
},
getType: function() {
return this.dictionary.types[this.name] || nestedType[this.dictionary.types[this.parent]] || "default";
},
getParentType: function() {
return this.parent ? this.dictionary.token(this.parent).getType() : "default";
},
setType: function() {
basis.dev.warn("basis.l10n: Token#setType() is deprecated");
},
compute: function(events, getter) {
if (arguments.length == 1) {
getter = events;
events = "";
}
getter = basis.getter(getter);
events = String(events).trim().split(/\s+|\s*,\s*/).sort();
var tokenId = this.basisObjectId;
var enumId = events.concat(tokenId, getter[basis.getter.ID]).join("_");
if (tokenComputeFn[enumId]) return tokenComputeFn[enumId];
var token = this;
var objectTokenMap = {};
var updateValue = function(object) {
basisTokenPrototypeSet.call(this, getter(object));
};
var handler = {
destroy: function(object) {
delete objectTokenMap[object.basisObjectId];
this.destroy();
}
};
for (var i = 0, eventName; eventName = events[i]; i++) if (eventName != "destroy") handler[eventName] = updateValue;
return tokenComputeFn[enumId] = function(object) {
if (object instanceof Emitter == false) throw "basis.l10n.Token#compute: object must be an instanceof Emitter";
var objectId = object.basisObjectId;
var computeToken = objectTokenMap[objectId];
if (!computeToken) {
computeToken = objectTokenMap[objectId] = token.computeToken(getter(object));
object.addHandler(handler, computeToken);
}
return computeToken;
};
},
computeToken: function(value) {
var ComputeTokenClass = this.computeTokenClass;
if (!ComputeTokenClass) ComputeTokenClass = this.computeTokenClass = ComputeToken.subclass({
dictionary: this.dictionary,
token: this,
parent: this.name
});
return new ComputeTokenClass(value);
},
token: function(name) {
if (isPluralType[this.getType()]) return this.computeToken(name, this);
if (this.dictionary) return this.dictionary.token(this.name + "." + name);
},
destroy: function() {
for (var key in this.computeTokens) this.computeTokens[key].destroy();
this.computeTokenClass = null;
this.computeTokens = null;
this.value = null;
this.dictionary = null;
tokenIndex[this.index] = null;
basis.Token.prototype.destroy.call(this);
}
});
function resolveToken(path) {
if (path.charAt(0) == "#") {
return tokenIndex[parseInt(path.substr(1), 36)];
} else {
var parts = path.match(/^(.+?)@(.+)$/);
if (parts) return resolveDictionary(basis.path.resolve(parts[2])).token(parts[1]);
basis.dev.warn("basis.l10n.token accepts token references in format `token.path@path/to/dict.l10n` only");
}
}
function isToken(value) {
return value ? value instanceof Token || value instanceof ComputeToken : false;
}
function isPluralToken(value) {
return isToken(value) && isPluralType[value.getType()];
}
function isMarkupToken(value) {
return isToken(value) && value.getType() == "markup";
}
var dictionaries = [];
var dictionaryByUrl = {};
var createDictionaryNotifier = new basis.Token;
function walkTokens(dictionary, culture, tokens, path) {
var cultureValues = dictionary.cultureValues[culture];
path = path ? path + "." : "";
for (var name in tokens) {
if (name.indexOf(".") != -1) {
basis.dev.warn((dictionary.resource ? dictionary.resource.url : "[anonymous dictionary]") + ": wrong token name `" + name + "`, token ignored.");
continue;
}
if (hasOwnProperty.call(tokens, name)) {
var tokenName = path + name;
var tokenValue = tokens[name];
cultureValues[tokenName] = tokenValue;
if (tokenValue && (typeof tokenValue == "object" || Array.isArray(tokenValue))) walkTokens(dictionary, culture, tokenValue, tokenName);
}
}
}
var Dictionary = Class(null, {
className: namespace + ".Dictionary",
tokens: null,
types: null,
cultureValues: null,
index: NaN,
resource: null,
init: function(content) {
this.tokens = {};
this.types = {};
this.cultureValues = {};
this.index = dictionaries.push(this) - 1;
if (basis.resource.isResource(content)) {
var resource = content;
this.resource = resource;
if (!dictionaryByUrl[resource.url]) {
dictionaryByUrl[resource.url] = this;
createDictionaryNotifier.set(resource.url);
}
if (autoFetchDictionaryResource) resource.fetch();
} else {
this.update(content || {});
}
},
update: function(data) {
if (!data) data = {};
this.cultureValues = {};
for (var culture in data) if (!/^_|_$/.test(culture)) {
this.cultureValues[culture] = {};
walkTokens(this, culture, data[culture]);
}
var newTypes = data._meta && data._meta.type || {};
var currentTypes = {};
for (var path in this.tokens) currentTypes[path] = this.tokens[path].getType();
this.types = {};
for (var path in newTypes) this.types[path] = tokenType[newTypes[path]] == true ? newTypes[path] : "default";
for (var path in this.tokens) {
var token = this.tokens[path];
if (token.getType() != currentTypes[path]) this.tokens[path].apply();
}
this.syncValues();
return this;
},
syncValues: function() {
for (var tokenName in this.tokens) basisTokenPrototypeSet.call(this.tokens[tokenName], this.getValue(tokenName));
},
getValue: function(tokenName) {
var fallback = cultureFallback[currentCulture] || [];
for (var i = 0, cultureName; cultureName = fallback[i]; i++) {
var cultureValues = this.cultureValues[cultureName];
if (cultureValues && tokenName in cultureValues) return cultureValues[tokenName];
}
},
getCultureValue: function(culture, tokenName) {
return this.cultureValues[culture] && this.cultureValues[culture][tokenName];
},