plugins/raphael.export.js
[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' ) return s.toString();
17
18                 var replace = {
19             '&': 'amp',
20             '<': 'lt',
21             '>': 'gt',
22             '"': 'quot',
23             '\'': 'apos'
24         };
25
26                 for ( var entity in replace ) {
27                         s = s.replace(new RegExp(entity, 'g'), '&' + replace[entity] + ';');
28                 }
29
30                 return s;
31         }
32
33         /**
34         * Generic map function
35         * @param iterable the array or object to be mapped
36         * @param callback the callback function(element, key)
37         * @returns array
38         */
39         function map(iterable, callback) {
40                 var mapped = new Array;
41
42                 for ( var i in iterable ) {
43                         if ( iterable.hasOwnProperty(i) ) {
44                                 var value = callback.call(this, iterable[i], i);
45
46                                 if ( value !== null ) mapped.push(value);
47                         }
48                 }
49
50                 return mapped;
51         }
52
53         /**
54         * Generic reduce function
55         * @param iterable array or object to be reduced
56         * @param callback the callback function(initial, element, i)
57         * @param initial the initial value
58         * @return the reduced value
59         */
60         function reduce(iterable, callback, initial) {
61                 for ( var i in iterable ) {
62                         if ( iterable.hasOwnProperty(i) ) {
63                                 initial = callback.call(this, initial, iterable[i], i);
64                         }
65                 }
66
67                 return initial;
68         }
69
70         /**
71         * Utility method for creating a tag
72         * @param name the tag name, e.g., 'text'
73         * @param attrs the attribute string, e.g., name1="val1" name2="val2"
74         * or attribute map, e.g., { name1 : 'val1', name2 : 'val2' }
75         * @param content the content string inside the tag
76         * @returns string of the tag
77         */
78         function tag(name, attrs, matrix, content) {
79                 if ( typeof content === 'undefined' || content === null ) {
80                         content = '';
81                 }
82
83                 if ( typeof attrs === 'object' ) {
84                         attrs = map(attrs, function(element, name) {
85                                 if ( name === 'transform') return;
86
87                                 return name + '="' + escapeXML(element) + '"';
88                         }).join(' ');
89                 }
90
91                 return '<' + name + ( matrix ? ' transform="matrix(' + matrix.toString().replace(/^matrix\(|\)$/g, '') + ')" ' : ' ' ) + attrs + '>' +
92              content +
93             '</' + name + '>';
94         }
95
96         /**
97         * @return object the style object
98         */
99         function extractStyle(node) {
100                 return {
101                         font: {
102                                 family: node.attrs.font.replace(/^.*?"(\w+)".*$/, '$1'),
103                                 size:   typeof node.attrs['font-size'] === 'undefined' ? null : node.attrs['font-size']
104                                 }
105                         };
106         }
107
108         /**
109         * @param style object from style()
110         * @return string
111         */
112         function styleToString(style) {
113                 // TODO figure out what is 'normal'
114                 return 'font: normal normal normal 10px/normal ' + style.font.family + ( style.font.size === null ? '' : '; font-size: ' + style.font.size + 'px' );
115         }
116
117         /**
118         * Computes tspan dy using font size. This formula was empircally determined
119         * using a best-fit line. Works well in both VML and SVG browsers.
120         * @param fontSize number
121         * @return number
122         */
123         function computeTSpanDy(fontSize, line, lines) {
124                 if ( fontSize === null ) fontSize = 10;
125
126                 //return fontSize * 4.5 / 13
127                 return fontSize * 4.5 / 13 * ( line - .2 - lines / 2 ) * 3.5;
128         }
129
130         var serializer = {
131                 'text': function(node) {
132                         style = extractStyle(node);
133
134                         var tags = new Array;
135
136                         map(node.attrs['text'].split('\n'), function(text, iterable, line) {
137                                 line = line || 0;
138                                 tags.push(tag(
139                                         'text',
140                                         reduce(
141                                                 node.attrs,
142                                                 function(initial, value, name) {
143                                                         if ( name !== 'text' && name !== 'w' && name !== 'h' ) {
144                                                                 if ( name === 'font-size') value = value + 'px';
145
146                                                                 initial[name] = escapeXML(value.toString());
147                                                         }
148
149                                                         return initial;
150                                                 },
151                                                 { style: 'text-anchor: middle; ' + styleToString(style) + ';' }
152                                                 ),
153                                         node.matrix,
154                                         tag('tspan',
155                             {
156                                 dy: computeTSpanDy(style.font.size, line + 1, node.attrs['text'].split('\n').length)
157                             },
158                             null,
159                             text
160                     )
161                                 ));
162                         });
163
164                         return tags;
165                 },
166                 'path' : function(node) {
167                         var initial = ( node.matrix.a === 1 && node.matrix.d === 1 ) ? {} : { 'transform' : node.matrix.toString() };
168
169                         return tag(
170                                 'path',
171                                 reduce(
172                                         node.attrs,
173                                         function(initial, value, name) {
174                                                 if ( name === 'path' ) name = 'd';
175
176                                                 initial[name] = value.toString();
177
178                                                 return initial;
179                                         },
180                                         {}
181                                 ),
182                                 node.matrix
183                                 );
184                 }
185                 // Other serializers should go here
186         };
187
188         R.fn.toSVG = function() {
189                 var
190                         paper   = this,
191                         restore = { svg: R.svg, vml: R.vml },
192                         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 + '">'
193                         ;
194
195                 R.svg = true;
196                 R.vml = false;
197
198                 for ( var node = paper.bottom; node != null; node = node.next ) {
199                         if ( node.node.style.display === 'none' ) continue;
200
201                         var attrs = '';
202
203                         // Use serializer
204                         if ( typeof serializer[node.type] === 'function' ) {
205                                 svg += serializer[node.type](node);
206
207                                 continue;
208                         }
209
210                         switch ( node.type ) {
211                                 case 'image':
212                                         attrs += ' preserveAspectRatio="none"';
213                                         break;
214                         }
215
216                         for ( i in node.attrs ) {
217                                 var name = i;
218
219                                 switch ( i ) {
220                                         case 'src':
221                                                 name = 'xlink:href';
222
223                                                 break;
224                                         case 'transform':
225                                                 name = '';
226
227                                                 break;
228                                 }
229
230                                 if ( name ) {
231                                         attrs += ' ' + name + '="' + escapeXML(node.attrs[i].toString()) + '"';
232                                 }
233                         }
234
235                         svg += '<' + node.type + ' transform="matrix(' + node.matrix.toString().replace(/^matrix\(|\)$/g, '') + ')"' + attrs + '></' + node.type + '>';
236                 }
237
238                 svg += '</svg>';
239
240                 R.svg = restore.svg;
241                 R.vml = restore.vml;
242
243                 return svg;
244         };
245 })(window.Raphael);