[FIX] correctly htmlescape data in format_cell
[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 'many2one':
106             // name_get value format
107             return value[1];
108         case 'datetime':
109             if (typeof(value) == "string")
110                 value = openerp.web.auto_str_to_date(value);
111
112             return value.format(l10n.date_format
113                         + ' ' + l10n.time_format);
114         case 'date':
115             if (typeof(value) == "string")
116                 value = openerp.web.auto_str_to_date(value);
117             return value.format(l10n.date_format);
118         case 'time':
119             if (typeof(value) == "string")
120                 value = openerp.web.auto_str_to_date(value);
121             return value.format(l10n.time_format);
122         case 'selection':
123             // Each choice is [value, label]
124             if(_.isArray(value)) {
125                  value = value[0]
126             }
127             var result = _(descriptor.selection).detect(function (choice) {
128                 return choice[0] === value;
129             });
130             if (result) { return result[1]; }
131             return;
132         default:
133             return value;
134     }
135 };
136
137 openerp.web.parse_value = function (value, descriptor, value_if_empty) {
138     var date_pattern = Date.normalizeFormat(_t.database.parameters.date_format),
139         time_pattern = Date.normalizeFormat(_t.database.parameters.time_format);
140     switch (value) {
141         case false:
142         case "":
143             return value_if_empty === undefined ?  false : value_if_empty;
144     }
145     switch (descriptor.widget || descriptor.type) {
146         case 'integer':
147             var tmp;
148             do {
149                 tmp = value;
150                 value = value.replace(openerp.web._t.database.parameters.thousands_sep, "");
151             } while(tmp !== value);
152             tmp = Number(value);
153             if (isNaN(tmp))
154                 throw new Error(value + " is not a correct integer");
155             return tmp;
156         case 'float':
157             var tmp = Number(value);
158             if (!isNaN(tmp))
159                 return tmp;
160
161             var tmp2 = value;
162             do {
163                 tmp = tmp2;
164                 tmp2 = tmp.replace(openerp.web._t.database.parameters.thousands_sep, "");
165             } while(tmp !== tmp2);
166             var reformatted_value = tmp.replace(openerp.web._t.database.parameters.decimal_point, ".");
167             var parsed = Number(reformatted_value);
168             if (isNaN(parsed))
169                 throw new Error(value + " is not a correct float");
170             return parsed;
171         case 'float_time':
172             var float_time_pair = value.split(":");
173             if (float_time_pair.length != 2)
174                 return openerp.web.parse_value(value, {type: "float"});
175             var hours = openerp.web.parse_value(float_time_pair[0], {type: "integer"});
176             var minutes = openerp.web.parse_value(float_time_pair[1], {type: "integer"});
177             return hours + (minutes / 60);
178         case 'progressbar':
179             return openerp.web.parse_value(value, {type: "float"});
180         case 'datetime':
181             var datetime = Date.parseExact(
182                     value, (date_pattern + ' ' + time_pattern));
183             if (datetime !== null)
184                 return openerp.web.datetime_to_str(datetime);
185             datetime = Date.parse(value);
186             if (datetime !== null)
187                 return openerp.web.datetime_to_str(datetime);
188             throw new Error(value + " is not a valid datetime");
189         case 'date':
190             var date = Date.parseExact(value, date_pattern);
191             if (date !== null)
192                 return openerp.web.date_to_str(date);
193             date = Date.parse(value);
194             if (date !== null)
195                 return openerp.web.date_to_str(date);
196             throw new Error(value + " is not a valid date");
197         case 'time':
198             var time = Date.parseExact(value, time_pattern);
199             if (time !== null)
200                 return openerp.web.time_to_str(time);
201             time = Date.parse(value);
202             if (time !== null)
203                 return openerp.web.time_to_str(time);
204             throw new Error(value + " is not a valid time");
205     }
206     return value;
207 };
208
209 openerp.web.auto_str_to_date = function(value, type) {
210     try {
211         return openerp.web.str_to_datetime(value);
212     } catch(e) {}
213     try {
214         return openerp.web.str_to_date(value);
215     } catch(e) {}
216     try {
217         return openerp.web.str_to_time(value);
218     } catch(e) {}
219     throw new Error("'" + value + "' is not a valid date, datetime nor time");
220 };
221
222 openerp.web.auto_date_to_str = function(value, type) {
223     switch(type) {
224         case 'datetime':
225             return openerp.web.datetime_to_str(value);
226         case 'date':
227             return openerp.web.date_to_str(value);
228         case 'time':
229             return openerp.web.time_to_str(value);
230         default:
231             throw new Error(type + " is not convertible to date, datetime nor time");
232     }
233 };
234
235 /**
236  * Formats a provided cell based on its field type. Most of the field types
237  * return a correctly formatted value, but some tags and fields are
238  * special-cased in their handling:
239  *
240  * * buttons will return an actual ``<button>`` tag with a bunch of error handling
241  *
242  * * boolean fields will return a checkbox input, potentially disabled
243  *
244  * * binary fields will return a link to download the binary data as a file
245  *
246  * @param {Object} row_data record whose values should be displayed in the cell
247  * @param {Object} column column descriptor
248  * @param {"button"|"field"} column.tag base control type
249  * @param {String} column.type widget type for a field control
250  * @param {String} [column.string] button label
251  * @param {String} [column.icon] button icon
252  * @param {Object} [options]
253  * @param {String} [options.value_if_empty=''] what to display if the field's value is ``false``
254  * @param {Boolean} [options.process_modifiers=true] should the modifiers be computed ?
255  * @param {String} [options.model] current record's model
256  * @param {Number} [options.id] current record's id
257  *
258  */
259 openerp.web.format_cell = function (row_data, column, options) {
260     options = options || {};
261     var attrs = {};
262     if (options.process_modifiers !== false) {
263         attrs = column.modifiers_for(row_data);
264     }
265     if (attrs.invisible) { return ''; }
266
267     if (column.tag === 'button') {
268         return _.template('<button type="button" title="<%-title%>" <%=additional_attributes%> >' +
269             '<img src="<%-prefix%>/web/static/src/img/icons/<%-icon%>.png" alt="<%-alt%>"/>' +
270             '</button>', {
271                 title: column.string || '',
272                 additional_attributes: isNaN(row_data["id"].value) && openerp.web.BufferedDataSet.virtual_id_regex.test(row_data["id"].value) ?
273                     'disabled="disabled" class="oe-listview-button-disabled"' : '',
274                 prefix: openerp.connection.prefix,
275                 icon: column.icon,
276                 alt: column.string || ''
277             });
278     }
279     if (!row_data[column.id]) {
280         return options.value_if_empty === undefined ? '' : options.value_if_empty;
281     }
282
283     switch (column.widget || column.type) {
284     case "boolean":
285         return _.str.sprintf('<input type="checkbox" %s disabled="disabled"/>',
286                  row_data[column.id].value ? 'checked="checked"' : '');
287     case "binary":
288         var text = _t("Download"),
289             download_url = _.str.sprintf('/web/binary/saveas?session_id=%s&model=%s&field=%s&id=%d', openerp.connection.session_id, options.model, column.id, options.id);
290         if (column.filename) {
291             download_url += '&filename_field=' + column.filename;
292             if (row_data[column.filename]) {
293                 text = _.str.sprintf(_t("Download \"%s\""), openerp.web.format_value(
294                         row_data[column.filename].value, {type: 'char'}));
295             }
296         }
297         return _.template('<a href="<%-href%>"><%-text%></a> (%<-size%>)', {
298             text: text,
299             href: download_url,
300             size: row_data[column.id].value
301         });
302     case 'progressbar':
303         return _.template(
304             '<progress value="<%-value%>" max="100"><%-value%>%</progress>', {
305                 value: row_data[column.id].value
306             });
307     }
308
309     return _.escape(openerp.web.format_value(
310             row_data[column.id].value, column, options.value_if_empty));
311 }
312
313 };