29795cfb20d11334cd25e439e8ec5e732f8c4a60
[raphael] / plugins / raphael.export.js
1 /**
2  * Raphael.Export https://github.com/ElbertF/Raphael.Export
3  *
4  * Licensed under the MIT license:
5  * http://www.opensource.org/licenses/mit-license.php
6  *
7  */
8
9 (function (R) {
10     /**
11      * Escapes string for XML interpolation
12      * @param value string or number value to escape
13      * @returns string escaped
14      */
15     function escapeXML(s) {
16         if (typeof s === 'number')
17             return s.toString();
18
19         var replace = {
20             '&': 'amp',
21             '<': 'lt',
22             '>': 'gt',
23             '"': 'quot',
24             '\'': 'apos'
25         };
26
27         for (var entity in replace) {
28             s = s.replace(new RegExp(entity, 'g'), '&' + replace[entity] + ';');
29         }
30
31         return s;
32     }
33
34     /**
35      * Generic map function
36      * @param iterable the array or object to be mapped
37      * @param callback the callback function(element, key)
38      * @returns array
39      */
40     function map(iterable, callback) {
41         var mapped = new Array;
42
43         for (var i in iterable) {
44             if (iterable.hasOwnProperty(i)) {
45                 var value = callback.call(this, iterable[i], i);
46
47                 if (value !== null)
48                     mapped.push(value);
49             }
50         }
51
52         return mapped;
53     }
54
55     /**
56      * Generic reduce function
57      * @param iterable array or object to be reduced
58      * @param callback the callback function(initial, element, i)
59      * @param initial the initial value
60      * @return the reduced value
61      */
62     function reduce(iterable, callback, initial) {
63         for (var i in iterable) {
64             if (iterable.hasOwnProperty(i)) {
65                 initial = callback.call(this, initial, iterable[i], i);
66             }
67         }
68
69         return initial;
70     }
71
72     /**
73      * Utility method for creating a tag
74      * @param name the tag name, e.g., 'text'
75      * @param attrs the attribute string, e.g., name1="val1" name2="val2"
76      * or attribute map, e.g., { name1 : 'val1', name2 : 'val2' }
77      * @param content the content string inside the tag
78      * @returns string of the tag
79      */
80     function tag(name, attrs, matrix, content) {
81         if (typeof content === 'undefined' || content === null) {
82             content = '';
83         }
84
85         if (typeof attrs === 'object') {
86             attrs = map(attrs, function (element, name) {
87                 if (name === 'transform')
88                     return;
89
90                 return name + '="' + escapeXML(element) + '"';
91             }).join(' ');
92         }
93
94         return '<' + name + (matrix ? ' transform="matrix(' + matrix.toString().replace(/^matrix\(|\)$/g, '') + ')" ' : ' ') + attrs + '>' +
95                 content +
96                 '</' + name + '>' + "\n";
97     }
98
99     /**
100      * @return object the style object
101      */
102     function extractStyle(node) {
103         return {
104             font: {
105                 family: node.attrs.font.replace(/^.*?"(\w+)".*$/, '$1'),
106                 size: typeof node.attrs['font-size'] === 'undefined' ? null : node.attrs['font-size'],
107                 anchor: typeof node.attrs['text-anchor'] === 'undefined' ? null : node.attrs['text-anchor'],
108             }
109         };
110     }
111
112     /**
113      * @param style object from style()
114      * @return string
115      */
116     function styleToString(style) {
117         // TODO figure out what is 'normal'
118
119         var r = [
120             'font-family:' + style.font.family,
121             'font-weight:normal',
122             'font-style:normal',
123             'font-stretch:normal',
124             'font-variant:normal'
125         ];
126         if (style.font.size !== null) {
127             r.push('font-size: ' + style.font.size + 'px')
128         }
129
130         return r.join(';')
131
132     }
133
134     /**
135      * Computes tspan dy using font size. This formula was empircally determined
136      * using a best-fit line. Works well in both VML and SVG browsers.
137      * @param fontSize number
138      * @return number
139      */
140     function computeTSpanDy(fontSize, line, lines) {
141         if (fontSize === null)
142             fontSize = 10;
143
144         //return fontSize * 4.5 / 13
145         return fontSize * 4.5 / 13 * (line - .2 - lines / 2) * 3.5;
146     }
147
148     var serializer = {
149         'text': function (node) {
150             Roo.log(node);
151             style = extractStyle(node);
152             Roo.log(style);
153             var tags = new Array;
154             
155             var text = node.attrs['text'].split('\n');
156             
157             var test = tag('tspan',
158                     {
159                         dy: computeTSpanDy(style.font.size, 1, 2)
160                     },
161                     null,
162                     escapeXML("test11")
163             );
164             var test2 = tag('tspan',
165                     {
166                         dy: computeTSpanDy(style.font.size, 2, 2)
167                     },
168                     null,
169                     escapeXML("test22")
170             );
171             
172             tags.push(tag(
173                 'text',
174                 reduce(
175                     node.attrs,
176                     function (initial, value, name) {
177                         if (name !== 'text' && name !== 'w' && name !== 'h') {
178                             if (name === 'font-size')
179                                 value = value + 'px';
180
181                             initial[name] = escapeXML(value.toString());
182                         }
183
184                         return initial;
185                     },
186                     {
187                         style: 'text-anchor: ' + (style.font.anchor ? (style.font.anchor + ';') : 'middle;') +
188                                 styleToString(style) + ';'
189                     }
190                 ),
191                 node.matrix,
192                 test + test2
193             ));
194             
195 //            map(node.attrs['text'].split('\n'), function (text, iterable, line) {
196 //                line = line || 0;
197 //                tags.push(tag(
198 //                        'text',
199 //                        reduce(
200 //                                node.attrs,
201 //                                function (initial, value, name) {
202 //                                    if (name !== 'text' && name !== 'w' && name !== 'h') {
203 //                                        if (name === 'font-size')
204 //                                            value = value + 'px';
205 //
206 //                                        initial[name] = escapeXML(value.toString());
207 //                                    }
208 //
209 //                                    return initial;
210 //                                },
211 //                                {
212 //                                    style: 'text-anchor: ' + (style.font.anchor ? (style.font.anchor + ';') : 'middle;') +
213 //                                            styleToString(style) + ';'
214 //                                }
215 //                        ),
216 //                        node.matrix,
217 //                        tag('tspan',
218 //                                {
219 //                                    dy: computeTSpanDy(style.font.size, line + 1, node.attrs['text'].split('\n').length)
220 //                                },
221 //                                null,
222 //                                escapeXML(text)
223 //                                )
224 //                        ));
225 //            });
226
227             return tags;
228         },
229         'path': function (node) {
230             var initial = (node.matrix.a === 1 && node.matrix.d === 1) ? {} : {'transform': node.matrix.toString()};
231
232
233
234             return tag(
235                     'path',
236                     reduce(
237                             node.attrs,
238                             function (initial, value, name) {
239                                 if (name === 'path') {
240                                     name = 'd';
241                                 }
242
243                                 initial[name] = (typeof (value) == 'undefined') ? '' : value.toString();
244
245                                 return initial;
246                             },
247                             {
248                                 style: 'fill:' + Raphael.color(node.attrs.fill).hex + ';'
249                             }
250                     ),
251                     node.matrix
252                     );
253         }
254         // Other serializers should go here
255     };
256
257     R.fn.toSVG = function () {
258         var
259                 paper = this,
260                 restore = {svg: R.svg, vml: R.vml},
261                 svg = '<svg style="overflow: hidden; position: relative;" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="' + paper.width + '" version="1.1" height="' + paper.height + '">';
262
263         R.svg = true;
264         R.vml = false;
265
266         for (var node = paper.bottom; node != null; node = node.next) {
267             if (node.node.style.display === 'none')
268                 continue;
269
270             var attrs = '';
271
272             // Use serializer
273             if (typeof serializer[node.type] === 'function') {
274                 svg += serializer[node.type](node);
275
276                 continue;
277             }
278
279             switch (node.type) {
280                 case 'image':
281                     attrs += ' preserveAspectRatio="none"';
282                     break;
283             }
284
285             for (i in node.attrs) {
286                 var name = i;
287                 var val = node.attrs[i].toString();
288                 switch (i) {
289                     case 'src':
290                         name = 'xlink:href';
291
292                         break;
293                     case 'transform':
294                         name = '';
295                         break;
296
297                     case 'stroke':
298                     case 'fill':
299                         val = Raphael.getRGB(val).hex;
300                         break;
301                 }
302
303                 if (name) {
304                     attrs += ' ' + name + '="' + escapeXML(val) + '"';
305                 }
306             }
307
308             svg += '<' + node.type + ' transform="matrix(' + node.matrix.toString().replace(/^matrix\(|\)$/g, '') + ')"' + attrs + '></' + node.type + '>';
309         }
310
311         svg += '</svg>';
312
313         R.svg = restore.svg;
314         R.vml = restore.vml;
315
316         return svg;
317     };
318 })(window.Raphael);