Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / draw / engine / Svg.js
1 /**
2  * @class Ext.draw.engine.Svg
3  * @extends Ext.draw.Surface
4  * Provides specific methods to draw with SVG.
5  */
6 Ext.define('Ext.draw.engine.Svg', {
7
8     /* Begin Definitions */
9
10     extend: 'Ext.draw.Surface',
11
12     requires: ['Ext.draw.Draw', 'Ext.draw.Sprite', 'Ext.draw.Matrix', 'Ext.core.Element'],
13
14     /* End Definitions */
15
16     engine: 'Svg',
17
18     trimRe: /^\s+|\s+$/g,
19     spacesRe: /\s+/,
20     xlink: "http:/" + "/www.w3.org/1999/xlink",
21
22     translateAttrs: {
23         radius: "r",
24         radiusX: "rx",
25         radiusY: "ry",
26         path: "d",
27         lineWidth: "stroke-width",
28         fillOpacity: "fill-opacity",
29         strokeOpacity: "stroke-opacity",
30         strokeLinejoin: "stroke-linejoin"
31     },
32
33     minDefaults: {
34         circle: {
35             cx: 0,
36             cy: 0,
37             r: 0,
38             fill: "none",
39             stroke: null,
40             "stroke-width": null,
41             opacity: null,
42             "fill-opacity": null,
43             "stroke-opacity": null
44         },
45         ellipse: {
46             cx: 0,
47             cy: 0,
48             rx: 0,
49             ry: 0,
50             fill: "none",
51             stroke: null,
52             "stroke-width": null,
53             opacity: null,
54             "fill-opacity": null,
55             "stroke-opacity": null
56         },
57         rect: {
58             x: 0,
59             y: 0,
60             width: 0,
61             height: 0,
62             rx: 0,
63             ry: 0,
64             fill: "none",
65             stroke: null,
66             "stroke-width": null,
67             opacity: null,
68             "fill-opacity": null,
69             "stroke-opacity": null
70         },
71         text: {
72             x: 0,
73             y: 0,
74             "text-anchor": "start",
75             "font-family": null,
76             "font-size": null,
77             "font-weight": null,
78             "font-style": null,
79             fill: "#000",
80             stroke: null,
81             "stroke-width": null,
82             opacity: null,
83             "fill-opacity": null,
84             "stroke-opacity": null
85         },
86         path: {
87             d: "M0,0",
88             fill: "none",
89             stroke: null,
90             "stroke-width": null,
91             opacity: null,
92             "fill-opacity": null,
93             "stroke-opacity": null
94         },
95         image: {
96             x: 0,
97             y: 0,
98             width: 0,
99             height: 0,
100             preserveAspectRatio: "none",
101             opacity: null
102         }
103     },
104
105     createSvgElement: function(type, attrs) {
106         var el = this.domRef.createElementNS("http:/" + "/www.w3.org/2000/svg", type),
107             key;
108         if (attrs) {
109             for (key in attrs) {
110                 el.setAttribute(key, String(attrs[key]));
111             }
112         }
113         return el;
114     },
115
116     createSpriteElement: function(sprite) {
117         // Create svg element and append to the DOM.
118         var el = this.createSvgElement(sprite.type);
119         el.id = sprite.id;
120         if (el.style) {
121             el.style.webkitTapHighlightColor = "rgba(0,0,0,0)";
122         }
123         sprite.el = Ext.get(el);
124         this.applyZIndex(sprite); //performs the insertion
125         sprite.matrix = Ext.create('Ext.draw.Matrix');
126         sprite.bbox = {
127             plain: 0,
128             transform: 0
129         };
130         sprite.fireEvent("render", sprite);
131         return el;
132     },
133
134     getBBox: function (sprite, isWithoutTransform) {
135         var realPath = this["getPath" + sprite.type](sprite);
136         if (isWithoutTransform) {
137             sprite.bbox.plain = sprite.bbox.plain || Ext.draw.Draw.pathDimensions(realPath);
138             return sprite.bbox.plain;
139         }
140         sprite.bbox.transform = sprite.bbox.transform || Ext.draw.Draw.pathDimensions(Ext.draw.Draw.mapPath(realPath, sprite.matrix));
141         return sprite.bbox.transform;
142     },
143     
144     getBBoxText: function (sprite) {
145         var bbox = {},
146             bb, height, width, i, ln, el;
147
148         if (sprite && sprite.el) {
149             el = sprite.el.dom;
150             try {
151                 bbox = el.getBBox();
152                 return bbox;
153             } catch(e) {
154                 // Firefox 3.0.x plays badly here
155             }
156             bbox = {x: bbox.x, y: Infinity, width: 0, height: 0};
157             ln = el.getNumberOfChars();
158             for (i = 0; i < ln; i++) {
159                 bb = el.getExtentOfChar(i);
160                 bbox.y = Math.min(bb.y, bbox.y);
161                 height = bb.y + bb.height - bbox.y;
162                 bbox.height = Math.max(bbox.height, height);
163                 width = bb.x + bb.width - bbox.x;
164                 bbox.width = Math.max(bbox.width, width);
165             }
166             return bbox;
167         }
168     },
169
170     hide: function() {
171         Ext.get(this.el).hide();
172     },
173
174     show: function() {
175         Ext.get(this.el).show();
176     },
177
178     hidePrim: function(sprite) {
179         this.addCls(sprite, Ext.baseCSSPrefix + 'hide-visibility');
180     },
181
182     showPrim: function(sprite) {
183         this.removeCls(sprite, Ext.baseCSSPrefix + 'hide-visibility');
184     },
185
186     getDefs: function() {
187         return this._defs || (this._defs = this.createSvgElement("defs"));
188     },
189
190     transform: function(sprite) {
191         var me = this,
192             matrix = Ext.create('Ext.draw.Matrix'),
193             transforms = sprite.transformations,
194             transformsLength = transforms.length,
195             i = 0,
196             transform, type;
197             
198         for (; i < transformsLength; i++) {
199             transform = transforms[i];
200             type = transform.type;
201             if (type == "translate") {
202                 matrix.translate(transform.x, transform.y);
203             }
204             else if (type == "rotate") {
205                 matrix.rotate(transform.degrees, transform.x, transform.y);
206             }
207             else if (type == "scale") {
208                 matrix.scale(transform.x, transform.y, transform.centerX, transform.centerY);
209             }
210         }
211         sprite.matrix = matrix;
212         sprite.el.set({transform: matrix.toSvg()});
213     },
214
215     setSize: function(w, h) {
216         var me = this,
217             el = me.el;
218         
219         w = +w || me.width;
220         h = +h || me.height;
221         me.width = w;
222         me.height = h;
223
224         el.setSize(w, h);
225         el.set({
226             width: w,
227             height: h
228         });
229         me.callParent([w, h]);
230     },
231
232     /**
233      * Get the region for the surface's canvas area
234      * @returns {Ext.util.Region}
235      */
236     getRegion: function() {
237         // Mozilla requires using the background rect because the svg element returns an
238         // incorrect region. Webkit gives no region for the rect and must use the svg element.
239         var svgXY = this.el.getXY(),
240             rectXY = this.bgRect.getXY(),
241             max = Math.max,
242             x = max(svgXY[0], rectXY[0]),
243             y = max(svgXY[1], rectXY[1]);
244         return {
245             left: x,
246             top: y,
247             right: x + this.width,
248             bottom: y + this.height
249         };
250     },
251
252     onRemove: function(sprite) {
253         if (sprite.el) {
254             sprite.el.remove();
255             delete sprite.el;
256         }
257         this.callParent(arguments);
258     },
259     
260     setViewBox: function(x, y, width, height) {
261         if (isFinite(x) && isFinite(y) && isFinite(width) && isFinite(height)) {
262             this.callParent(arguments);
263             this.el.dom.setAttribute("viewBox", [x, y, width, height].join(" "));
264         }
265     },
266
267     render: function (container) {
268         var me = this;
269         if (!me.el) {
270             var width = me.width || 10,
271                 height = me.height || 10,
272                 el = me.createSvgElement('svg', {
273                     xmlns: "http:/" + "/www.w3.org/2000/svg",
274                     version: 1.1,
275                     width: width,
276                     height: height
277                 }),
278                 defs = me.getDefs(),
279
280                 // Create a rect that is always the same size as the svg root; this serves 2 purposes:
281                 // (1) It allows mouse events to be fired over empty areas in Webkit, and (2) we can
282                 // use it rather than the svg element for retrieving the correct client rect of the
283                 // surface in Mozilla (see https://bugzilla.mozilla.org/show_bug.cgi?id=530985)
284                 bgRect = me.createSvgElement("rect", {
285                     width: "100%",
286                     height: "100%",
287                     fill: "#000",
288                     stroke: "none",
289                     opacity: 0
290                 }),
291                 webkitRect;
292             
293                 if (Ext.isSafari3) {
294                     // Rect that we will show/hide to fix old WebKit bug with rendering issues.
295                     webkitRect = me.createSvgElement("rect", {
296                         x: -10,
297                         y: -10,
298                         width: "110%",
299                         height: "110%",
300                         fill: "none",
301                         stroke: "#000"
302                     });
303                 }
304             el.appendChild(defs);
305             if (Ext.isSafari3) {
306                 el.appendChild(webkitRect);
307             }
308             el.appendChild(bgRect);
309             container.appendChild(el);
310             me.el = Ext.get(el);
311             me.bgRect = Ext.get(bgRect);
312             if (Ext.isSafari3) {
313                 me.webkitRect = Ext.get(webkitRect);
314                 me.webkitRect.hide();
315             }
316             me.el.on({
317                 scope: me,
318                 mouseup: me.onMouseUp,
319                 mousedown: me.onMouseDown,
320                 mouseover: me.onMouseOver,
321                 mouseout: me.onMouseOut,
322                 mousemove: me.onMouseMove,
323                 mouseenter: me.onMouseEnter,
324                 mouseleave: me.onMouseLeave,
325                 click: me.onClick
326             });
327         }
328         me.renderAll();
329     },
330
331     // private
332     onMouseEnter: function(e) {
333         if (this.el.parent().getRegion().contains(e.getPoint())) {
334             this.fireEvent('mouseenter', e);
335         }
336     },
337
338     // private
339     onMouseLeave: function(e) {
340         if (!this.el.parent().getRegion().contains(e.getPoint())) {
341             this.fireEvent('mouseleave', e);
342         }
343     },
344     // @private - Normalize a delegated single event from the main container to each sprite and sprite group
345     processEvent: function(name, e) {
346         var target = e.getTarget(),
347             surface = this.surface,
348             sprite;
349
350         this.fireEvent(name, e);
351         // We wrap text types in a tspan, sprite is the parent.
352         if (target.nodeName == "tspan" && target.parentNode) {
353             target = target.parentNode;
354         }
355         sprite = this.items.get(target.id);
356         if (sprite) {
357             sprite.fireEvent(name, sprite, e);
358         }
359     },
360
361     /* @private - Wrap SVG text inside a tspan to allow for line wrapping.  In addition this normallizes
362      * the baseline for text the vertical middle of the text to be the same as VML.
363      */
364     tuneText: function (sprite, attrs) {
365         var el = sprite.el.dom,
366             tspans = [],
367             height, tspan, text, i, ln, texts, factor;
368
369         if (attrs.hasOwnProperty("text")) {
370            tspans = this.setText(sprite, attrs.text);
371         }
372         // Normalize baseline via a DY shift of first tspan. Shift other rows by height * line height (1.2)
373         if (tspans.length) {
374             height = this.getBBoxText(sprite).height;
375             for (i = 0, ln = tspans.length; i < ln; i++) {
376                 // The text baseline for FireFox 3.0 and 3.5 is different than other SVG implementations
377                 // so we are going to normalize that here
378                 factor = (Ext.isFF3_0 || Ext.isFF3_5) ? 2 : 4;
379                 tspans[i].setAttribute("dy", i ? height * 1.2 : height / factor);
380             }
381             sprite.dirty = true;
382         }
383     },
384
385     setText: function(sprite, textString) {
386          var me = this,
387              el = sprite.el.dom,
388              x = el.getAttribute("x"),
389              tspans = [],
390              height, tspan, text, i, ln, texts;
391         
392         while (el.firstChild) {
393             el.removeChild(el.firstChild);
394         }
395         // Wrap each row into tspan to emulate rows
396         texts = String(textString).split("\n");
397         for (i = 0, ln = texts.length; i < ln; i++) {
398             text = texts[i];
399             if (text) {
400                 tspan = me.createSvgElement("tspan");
401                 tspan.appendChild(document.createTextNode(Ext.htmlDecode(text)));
402                 tspan.setAttribute("x", x);
403                 el.appendChild(tspan);
404                 tspans[i] = tspan;
405             }
406         }
407         return tspans;
408     },
409
410     renderAll: function() {
411         this.items.each(this.renderItem, this);
412     },
413
414     renderItem: function (sprite) {
415         if (!this.el) {
416             return;
417         }
418         if (!sprite.el) {
419             this.createSpriteElement(sprite);
420         }
421         if (sprite.zIndexDirty) {
422             this.applyZIndex(sprite);
423         }
424         if (sprite.dirty) {
425             this.applyAttrs(sprite);
426             this.applyTransformations(sprite);
427         }
428     },
429
430     redraw: function(sprite) {
431         sprite.dirty = sprite.zIndexDirty = true;
432         this.renderItem(sprite);
433     },
434
435     applyAttrs: function (sprite) {
436         var me = this,
437             el = sprite.el,
438             group = sprite.group,
439             sattr = sprite.attr,
440             groups, i, ln, attrs, font, key, style, name, rect;
441
442         if (group) {
443             groups = [].concat(group);
444             ln = groups.length;
445             for (i = 0; i < ln; i++) {
446                 group = groups[i];
447                 me.getGroup(group).add(sprite);
448             }
449             delete sprite.group;
450         }
451         attrs = me.scrubAttrs(sprite) || {};
452
453         // if (sprite.dirtyPath) {
454             sprite.bbox.plain = 0;
455             sprite.bbox.transform = 0;
456             if (sprite.type == "circle" || sprite.type == "ellipse") {
457                 attrs.cx = attrs.cx || attrs.x;
458                 attrs.cy = attrs.cy || attrs.y;
459             }
460             else if (sprite.type == "rect") {
461                 attrs.rx = attrs.ry = attrs.r;
462             }
463             else if (sprite.type == "path" && attrs.d) {
464                 attrs.d = Ext.draw.Draw.pathToString(Ext.draw.Draw.pathToAbsolute(attrs.d));
465                 
466             }
467             sprite.dirtyPath = false;
468         // }
469         // else {
470         //     delete attrs.d;
471         // }
472
473         if (attrs['clip-rect']) {
474             me.setClip(sprite, attrs);
475             delete attrs['clip-rect'];
476         }
477         if (sprite.type == 'text' && attrs.font && sprite.dirtyFont) {
478             el.set({ style: "font: " + attrs.font});
479             sprite.dirtyFont = false;
480         }
481         if (sprite.type == "image") {
482             el.dom.setAttributeNS(me.xlink, "href", attrs.src);
483         }
484         Ext.applyIf(attrs, me.minDefaults[sprite.type]);
485
486         if (sprite.dirtyHidden) {
487             (sattr.hidden) ? me.hidePrim(sprite) : me.showPrim(sprite);
488             sprite.dirtyHidden = false;
489         }
490         for (key in attrs) {
491             if (attrs.hasOwnProperty(key) && attrs[key] != null) {
492                 el.dom.setAttribute(key, attrs[key]);
493             }
494         }
495         if (sprite.type == 'text') {
496             me.tuneText(sprite, attrs);
497         }
498
499         //set styles
500         style = sattr.style;
501         if (style) {
502             el.setStyle(style);
503         }
504
505         sprite.dirty = false;
506
507         if (Ext.isSafari3) {
508             // Refreshing the view to fix bug EXTJSIV-1: rendering issue in old Safari 3
509             me.webkitRect.show();
510             setTimeout(function () {
511                 me.webkitRect.hide();
512             });
513         }
514     },
515
516     setClip: function(sprite, params) {
517         var me = this,
518             rect = params["clip-rect"],
519             clipEl, clipPath;
520         if (rect) {
521             if (sprite.clip) {
522                 sprite.clip.parentNode.parentNode.removeChild(sprite.clip.parentNode);
523             }
524             clipEl = me.createSvgElement('clipPath');
525             clipPath = me.createSvgElement('rect');
526             clipEl.id = Ext.id(null, 'ext-clip-');
527             clipPath.setAttribute("x", rect.x);
528             clipPath.setAttribute("y", rect.y);
529             clipPath.setAttribute("width", rect.width);
530             clipPath.setAttribute("height", rect.height);
531             clipEl.appendChild(clipPath);
532             me.getDefs().appendChild(clipEl);
533             sprite.el.dom.setAttribute("clip-path", "url(#" + clipEl.id + ")");
534             sprite.clip = clipPath;
535         }
536         // if (!attrs[key]) {
537         //     var clip = Ext.getDoc().dom.getElementById(sprite.el.getAttribute("clip-path").replace(/(^url\(#|\)$)/g, ""));
538         //     clip && clip.parentNode.removeChild(clip);
539         //     sprite.el.setAttribute("clip-path", "");
540         //     delete attrss.clip;
541         // }
542     },
543
544     /**
545      * Insert or move a given sprite's element to the correct place in the DOM list for its zIndex
546      * @param {Ext.draw.Sprite} sprite
547      */
548     applyZIndex: function(sprite) {
549         var idx = this.normalizeSpriteCollection(sprite),
550             el = sprite.el,
551             prevEl;
552         if (this.el.dom.childNodes[idx + 2] !== el.dom) { //shift by 2 to account for defs and bg rect 
553             if (idx > 0) {
554                 // Find the first previous sprite which has its DOM element created already
555                 do {
556                     prevEl = this.items.getAt(--idx).el;
557                 } while (!prevEl && idx > 0);
558             }
559             el.insertAfter(prevEl || this.bgRect);
560         }
561         sprite.zIndexDirty = false;
562     },
563
564     createItem: function (config) {
565         var sprite = Ext.create('Ext.draw.Sprite', config);
566         sprite.surface = this;
567         return sprite;
568     },
569
570     addGradient: function(gradient) {
571         gradient = Ext.draw.Draw.parseGradient(gradient);
572         var ln = gradient.stops.length,
573             vector = gradient.vector,
574             gradientEl,
575             stop,
576             stopEl,
577             i;
578         if (gradient.type == "linear") {
579             gradientEl = this.createSvgElement("linearGradient");
580             gradientEl.setAttribute("x1", vector[0]);
581             gradientEl.setAttribute("y1", vector[1]);
582             gradientEl.setAttribute("x2", vector[2]);
583             gradientEl.setAttribute("y2", vector[3]);
584         }
585         else {
586             gradientEl = this.createSvgElement("radialGradient");
587             gradientEl.setAttribute("cx", gradient.centerX);
588             gradientEl.setAttribute("cy", gradient.centerY);
589             gradientEl.setAttribute("r", gradient.radius);
590             if (Ext.isNumber(gradient.focalX) && Ext.isNumber(gradient.focalY)) {
591                 gradientEl.setAttribute("fx", gradient.focalX);
592                 gradientEl.setAttribute("fy", gradient.focalY);
593             }
594         }    
595         gradientEl.id = gradient.id;
596         this.getDefs().appendChild(gradientEl);
597
598         for (i = 0; i < ln; i++) {
599             stop = gradient.stops[i];
600             stopEl = this.createSvgElement("stop");
601             stopEl.setAttribute("offset", stop.offset + "%");
602             stopEl.setAttribute("stop-color", stop.color);
603             stopEl.setAttribute("stop-opacity",stop.opacity);
604             gradientEl.appendChild(stopEl);
605         }
606     },
607
608     /**
609      * Checks if the specified CSS class exists on this element's DOM node.
610      * @param {String} className The CSS class to check for
611      * @return {Boolean} True if the class exists, else false
612      */
613     hasCls: function(sprite, className) {
614         return className && (' ' + (sprite.el.dom.getAttribute('class') || '') + ' ').indexOf(' ' + className + ' ') != -1;
615     },
616
617     addCls: function(sprite, className) {
618         var el = sprite.el,
619             i,
620             len,
621             v,
622             cls = [],
623             curCls =  el.getAttribute('class') || '';
624         // Separate case is for speed
625         if (!Ext.isArray(className)) {
626             if (typeof className == 'string' && !this.hasCls(sprite, className)) {
627                 el.set({ 'class': curCls + ' ' + className });
628             }
629         }
630         else {
631             for (i = 0, len = className.length; i < len; i++) {
632                 v = className[i];
633                 if (typeof v == 'string' && (' ' + curCls + ' ').indexOf(' ' + v + ' ') == -1) {
634                     cls.push(v);
635                 }
636             }
637             if (cls.length) {
638                 el.set({ 'class': ' ' + cls.join(' ') });
639             }
640         }
641     },
642
643     removeCls: function(sprite, className) {
644         var me = this,
645             el = sprite.el,
646             curCls =  el.getAttribute('class') || '',
647             i, idx, len, cls, elClasses;
648         if (!Ext.isArray(className)){
649             className = [className];
650         }
651         if (curCls) {
652             elClasses = curCls.replace(me.trimRe, ' ').split(me.spacesRe);
653             for (i = 0, len = className.length; i < len; i++) {
654                 cls = className[i];
655                 if (typeof cls == 'string') {
656                     cls = cls.replace(me.trimRe, '');
657                     idx = Ext.Array.indexOf(elClasses, cls);
658                     if (idx != -1) {
659                         elClasses.splice(idx, 1);
660                     }
661                 }
662             }
663             el.set({ 'class': elClasses.join(' ') });
664         }
665     },
666
667     destroy: function() {
668         var me = this;
669         
670         me.callParent();
671         if (me.el) {
672             me.el.remove();
673         }
674         delete me.el;
675     }
676 });