[ADD] translatable name to views
[odoo/odoo.git] / addons / web / static / src / js / formats.js
1
2 openerp.web.formats = function(openerp) {
3 var _t = openerp.web._t;
4
5 /**
6  * Intersperses ``separator`` in ``str`` at the positions indicated by
7  * ``indices``.
8  *
9  * ``indices`` is an array of relative offsets (from the previous insertion
10  * position, starting from the end of the string) at which to insert
11  * ``separator``.
12  *
13  * There are two special values:
14  *
15  * ``-1``
16  *   indicates the insertion should end now
17  * ``0``
18  *   indicates that the previous section pattern should be repeated (until all
19  *   of ``str`` is consumed)
20  *
21  * @param {String} str
22  * @param {Array<Number>} indices
23  * @param {String} separator
24  * @returns {String}
25  */
26 openerp.web.intersperse = function (str, indices, separator) {
27     separator = separator || '';
28     var result = [], last = str.length;
29
30     for(var i=0; i<indices.length; ++i) {
31         var section = indices[i];
32         if (section === -1 || last <= 0) {
33             // Done with string, or -1 (stops formatting string)
34             break;
35         } else if(section === 0 && i === 0) {
36             // repeats previous section, which there is none => stop
37             break;
38         } else if (section === 0) {
39             // repeat previous section forever
40             //noinspection AssignmentToForLoopParameterJS
41             section = indices[--i];
42         }
43         result.push(str.substring(last-section, last));
44         last -= section;
45     }
46
47     var s = str.substring(0, last);
48     if (s) { result.push(s); }
49     return result.reverse().join(separator);
50 };
51 /**
52  * Insert "thousands" separators in the provided number (which is actually
53  * a string)
54  *
55  * @param {String} num
56  * @returns {String}
57  */
58 openerp.web.insert_thousand_seps = function (num) {
59     var negative = num[0] === '-';
60     num = (negative ? num.slice(1) : num);
61     return (negative ? '-' : '') + openerp.web.intersperse(
62         num, _t.database.parameters.grouping, _t.database.parameters.thousands_sep);
63 };
64 /**
65  * Formats a single atomic value based on a field descriptor
66  *
67  * @param {Object} value read from OpenERP
68  * @param {Object} descriptor union of orm field and view field
69  * @param {Object} [descriptor.widget] widget to use to display the value
70  * @param {Object} descriptor.type fallback if no widget is provided, or if the provided widget is unknown
71  * @param {Object} [descriptor.digits] used for the formatting of floats
72  * @param {String} [value_if_empty=''] returned if the ``value`` argument is considered empty
73  */
74 openerp.web.format_value = function (value, descriptor, value_if_empty) {
75     // If NaN value, display as with a `false` (empty cell)
76     if (typeof value === 'number' && isNaN(value)) {
77         value = false;
78     }
79     //noinspection FallthroughInSwitchStatementJS
80     switch (value) {
81         case '':
82             if (descriptor.type === 'char') {
83                 return '';
84             }
85             console.warn('Field', descriptor, 'had an empty string as value, treating as false...');
86         case false:
87         case Infinity:
88         case -Infinity:
89             return value_if_empty === undefined ?  '' : value_if_empty;
90     }
91     var l10n = _t.database.parameters;
92     switch (descriptor.widget || descriptor.type) {
93         case 'integer':
94             return openerp.web.insert_thousand_seps(
95                 _.str.sprintf('%d', value));
96         case 'float':
97             var precision = descriptor.digits ? descriptor.digits[1] : 2;
98             var formatted = _.str.sprintf('%.' + precision + 'f', value).split('.');
99             formatted[0] = openerp.web.insert_thousand_seps(formatted[0]);
100             return formatted.join(l10n.decimal_point);
101         case 'float_time':
102             return _.str.sprintf("%02d:%02d",
103                     Math.floor(value),
104                     Math.round((value % 1) * 60));
105         case 'progressbar':
106             return _.str.sprintf(
107                 '<progress value="%.2f" max="100.0">%.2f%%</progress>',
108                     value, value);
109         case 'many2one':
110             // name_get value format
111             return value[1];
112         case 'datetime':
113             if (typeof(value) == "string")
114                 value = openerp.web.auto_str_to_date(value);
115
116             return value.format(l10n.date_format
117                         + ' ' + l10n.time_format);
118         case 'date':
119             if (typeof(value) == "string")
120                 value = openerp.web.auto_str_to_date(value);
121             return value.format(l10n.date_format);
122         case 'time':
123             if (typeof(value) == "string")
124                 value = openerp.web.auto_str_to_date(value);
125             return value.format(l10n.time_format);
126         case 'selection':
127             // Each choice is [value, label]
128             var result = _(descriptor.selection).detect(function (choice) {
129                 return choice[0] === value;
130             });
131             if (result) { return result[1]; }
132             return;
133         default:
134             return value;
135     }
136 };
137
138 openerp.web.parse_value = function (value, descriptor, value_if_empty) {
139     var date_pattern = Date.normalizeFormat(_t.database.parameters.date_format),
140         time_pattern = Date.normalizeFormat(_t.database.parameters.time_format);
141     switch (value) {
142         case false:
143         case "":
144             return value_if_empty === undefined ?  false : value_if_empty;
145     }
146     switch (descriptor.widget || descriptor.type) {
147         case 'integer':
148             var tmp;
149             do {
150                 tmp = value;
151                 value = value.replace(openerp.web._t.database.parameters.thousands_sep, "");
152             } while(tmp !== value);
153             tmp = Number(value);
154             if (isNaN(tmp))
155                 throw new Error(value + " is not a correct integer");
156             return tmp;
157         case 'float':
158             var tmp = Number(value);
159             if (!isNaN(tmp))
160                 return tmp;
161
162             var tmp2 = value;
163             do {
164                 tmp = tmp2;
165                 tmp2 = tmp.replace(openerp.web._t.database.parameters.thousands_sep, "");
166             } while(tmp !== tmp2);
167             var reformatted_value = tmp.replace(openerp.web._t.database.parameters.decimal_point, ".");
168             var parsed = Number(reformatted_value);
169             if (isNaN(parsed))
170                 throw new Error(value + " is not a correct float");
171             return parsed;
172         case 'float_time':
173             var float_time_pair = value.split(":");
174             if (float_time_pair.length != 2)
175                 return openerp.web.parse_value(value, {type: "float"});
176             var hours = openerp.web.parse_value(float_time_pair[0], {type: "integer"});
177             var minutes = openerp.web.parse_value(float_time_pair[1], {type: "integer"});
178             return hours + (minutes / 60);
179         case 'progressbar':
180             return openerp.web.parse_value(value, {type: "float"});
181         case 'datetime':
182             var datetime = Date.parseExact(
183                     value, (date_pattern + ' ' + time_pattern));
184             if (datetime !== null)
185                 return openerp.web.datetime_to_str(datetime);
186             datetime = Date.parse(value);
187             if (datetime !== null)
188                 return openerp.web.datetime_to_str(datetime);
189             throw new Error(value + " is not a valid datetime");
190         case 'date':
191             var date = Date.parseExact(value, date_pattern);
192             if (date !== null)
193                 return openerp.web.date_to_str(date);
194             date = Date.parse(value);
195             if (date !== null)
196                 return openerp.web.date_to_str(date);
197             throw new Error(value + " is not a valid date");
198         case 'time':
199             var time = Date.parseExact(value, time_pattern);
200             if (time !== null)
201                 return openerp.web.time_to_str(time);
202             time = Date.parse(value);
203             if (time !== null)
204                 return openerp.web.time_to_str(time);
205             throw new Error(value + " is not a valid time");
206     }
207     return value;
208 };
209
210 openerp.web.auto_str_to_date = function(value, type) {
211     try {
212         return openerp.web.str_to_datetime(value);
213     } catch(e) {}
214     try {
215         return openerp.web.str_to_date(value);
216     } catch(e) {}
217     try {
218         return openerp.web.str_to_time(value);
219     } catch(e) {}
220     throw new Error("'" + value + "' is not a valid date, datetime nor time");
221 };
222
223 openerp.web.auto_date_to_str = function(value, type) {
224     switch(type) {
225         case 'datetime':
226             return openerp.web.datetime_to_str(value);
227         case 'date':
228             return openerp.web.date_to_str(value);
229         case 'time':
230             return openerp.web.time_to_str(value);
231         default:
232             throw new Error(type + " is not convertible to date, datetime nor time");
233     }
234 };
235
236 /**
237  * Formats a provided cell based on its field type
238  *
239  * @param {Object} row_data record whose values should be displayed in the cell
240  * @param {Object} column column descriptor
241  * @param {"button"|"field"} column.tag base control type
242  * @param {String} column.type widget type for a field control
243  * @param {String} [column.string] button label
244  * @param {String} [column.icon] button icon
245  * @param {String} [value_if_empty=''] what to display if the field's value is ``false``
246  * @param {Boolean} [process_modifiers=true] should the modifiers be computed ?
247  */
248 openerp.web.format_cell = function (row_data, column, value_if_empty, process_modifiers) {
249     var attrs = {};
250     if (process_modifiers !== false) {
251         attrs = column.modifiers_for(row_data);
252     }
253     if (attrs.invisible) { return ''; }
254     if (column.tag === 'button') {
255         return [
256             '<button type="button" title="', column.string || '', '">',
257                 '<img src="', openerp.connection.prefix, '/web/static/src/img/icons/', column.icon, '.png"',
258                     ' alt="', column.string || '', '"/>',
259             '</button>'
260         ].join('')
261     }
262
263     if (!row_data[column.id]) {
264         return value_if_empty === undefined ? '' : value_if_empty;
265     }
266     return openerp.web.format_value(
267             row_data[column.id].value, column, value_if_empty);
268 }
269     
270 };