fc3a1e1ba70304e67db321e09bb897d1cea889e6
[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             style = extractStyle(node);
151             Roo.log(style);
152             var tags = new Array;
153
154             map(node.attrs['text'].split('\n'), function (text, iterable, line) {
155                 line = line || 0;
156                 tags.push(tag(
157                         'text',
158                         reduce(
159                                 node.attrs,
160                                 function (initial, value, name) {
161                                     if (name !== 'text' && name !== 'w' && name !== 'h') {
162                                         if (name === 'font-size')
163                                             value = value + 'px';
164
165                                         initial[name] = escapeXML(value.toString());
166                                     }
167
168                                     return initial;
169                                 },
170                                 {
171                                     style: 'text-anchor: ' + (style.font.anchor ? (style.font.anchor + ';') : 'middle;') +
172                                             styleToString(style) + ';'
173                                 }
174                         ),
175                         node.matrix,
176                         tag('tspan',
177                                 {
178                                     dy: computeTSpanDy(style.font.size, line + 1, node.attrs['text'].split('\n').length)
179                                 },
180                                 null,
181                                 escapeXML(text)
182                                 )
183                         ));
184             });
185
186             return tags;
187         },
188         'path': function (node) {
189             var initial = (node.matrix.a === 1 && node.matrix.d === 1) ? {} : {'transform': node.matrix.toString()};
190
191
192
193             return tag(
194                     'path',
195                     reduce(
196                             node.attrs,
197                             function (initial, value, name) {
198                                 if (name === 'path') {
199                                     name = 'd';
200                                 }
201
202                                 initial[name] = (typeof (value) == 'undefined') ? '' : value.toString();
203
204                                 return initial;
205                             },
206                             {
207                                 style: 'fill:' + Raphael.color(node.attrs.fill).hex + ';'
208                             }
209                     ),
210                     node.matrix
211                     );
212         }
213         // Other serializers should go here
214     };
215
216     R.fn.toSVG = function () {
217         var
218                 paper = this,
219                 restore = {svg: R.svg, vml: R.vml},
220                 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 + '">';
221
222         R.svg = true;
223         R.vml = false;
224
225         for (var node = paper.bottom; node != null; node = node.next) {
226             if (node.node.style.display === 'none')
227                 continue;
228
229             var attrs = '';
230
231             // Use serializer
232             if (typeof serializer[node.type] === 'function') {
233                 svg += serializer[node.type](node);
234
235                 continue;
236             }
237
238             switch (node.type) {
239                 case 'image':
240                     attrs += ' preserveAspectRatio="none"';
241                     break;
242             }
243
244             for (i in node.attrs) {
245                 var name = i;
246                 var val = node.attrs[i].toString();
247                 switch (i) {
248                     case 'src':
249                         name = 'xlink:href';
250
251                         break;
252                     case 'transform':
253                         name = '';
254                         break;
255
256                     case 'stroke':
257                     case 'fill':
258                         val = Raphael.getRGB(val).hex;
259                         break;
260                 }
261
262                 if (name) {
263                     attrs += ' ' + name + '="' + escapeXML(val) + '"';
264                 }
265             }
266
267             svg += '<' + node.type + ' transform="matrix(' + node.matrix.toString().replace(/^matrix\(|\)$/g, '') + ')"' + attrs + '></' + node.type + '>';
268         }
269
270         svg += '</svg>';
271
272         R.svg = restore.svg;
273         R.vml = restore.vml;
274
275         return svg;
276     };
277 })(window.Raphael);