UNPKG

2.17 kBJavaScriptView Raw
1var log = require("phnq_log").create(__filename);
2var phnq_core = require("phnq_core");
3var config = require("./config");
4var widgetManager = require("./widget_manager").instance();
5
6var nextIdIdx = 0;
7
8module.exports = phnq_core.clazz(
9{
10 init: function(theWidget, req)
11 {
12 this.theWidget = theWidget;
13 if(req)
14 {
15 this.query = req.query;
16 this.headers = req.headers;
17 }
18 else
19 {
20 this.query = {};
21 this.headers = {};
22 }
23 this.params = {};
24 this.embedded = [];
25 },
26
27 i18n: function(key, defaultValue)
28 {
29 var locale = "en";
30 var acceptLang = this.headers["accept-language"];
31 if(acceptLang)
32 {
33 locale = acceptLang.split(",")[0];
34 locale = locale.split(";")[0];
35 }
36 var currentWidget = this.embedded.length == 0 ? this.theWidget : widgetManager.getWidget(this.embedded[this.embedded.length-1]);
37 return currentWidget.getI18nString(key, locale) || defaultValue || "[MISSING_STRING("+locale+", "+currentWidget.type+") - "+key+"]";
38 },
39
40 nextId: function()
41 {
42 return config.idPrefix + (nextIdIdx++);
43 },
44
45 fixUrl: function(type, url)
46 {
47 // If url starts with http/https or /, then return as is...
48 if(url.match(/^(https?:\/\/|\/)/))
49 return url;
50 else
51 return config.uriPrefix + "/" + type + "/" + url;
52 },
53
54 widget: function(type /* , params, bodyFn */)
55 {
56 var params=null, bodyFn=null;
57
58 for(var i=1; i<arguments.length; i++)
59 {
60 if(!params && typeof(arguments[i]) == "object")
61 params = arguments[i];
62 else if(!bodyFn && typeof(arguments[i]) == "function")
63 bodyFn = arguments[i];
64 }
65
66 params = params || {};
67 var isLazy = !!params._lazy;
68
69 if(bodyFn)
70 {
71 if(isLazy)
72 throw "A widget with a body function may not be loaded lazily: "+type;
73
74 var buf = [];
75 bodyFn(buf);
76 this.body = buf.join("");
77 }
78
79 this.params = params;
80
81 var markup;
82 if(isLazy)
83 {
84 markup = "<span class=\"wph "+type+"\"><!--"+JSON.stringify(this.params)+"--><br/></span>";
85 }
86 else
87 {
88 this.embedded.push(type);
89 var widget = widgetManager.getWidget(type);
90 markup = widget.getMarkup(this);
91 if(!markup)
92 markup = "";
93
94 this.embedded.pop();
95 }
96
97 this.params = {};
98 this.body = null;
99
100 return markup;
101 }
102});