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