-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSVGEventListener.js
294 lines (266 loc) · 9.17 KB
/
SVGEventListener.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// SVGEventListener.js
// Version - 0.2.3
//
// by MAD - @madsgraphics - ecrire[at]madsgraphics[dot]com
//
// https://github.com/madsgraphics/SVGEventListener/
//
// Tri-license - WTFPL | MIT | BSD
//
// Please minify before use.
( function ( undefined ) {
'use strict';
var legacy,
svgns,
isArray,
supportedEvents;
legacy = {
addEventListener : Element.prototype.addEventListener,
svgAnimateBeginElement : SVGAnimateElement.prototype.beginElement,
svgAnimateTransformBeginElement : SVGAnimateTransformElement.prototype.beginElement
};
svgns = 'http://www.w3.org/2000/svg';
// helper functions
function isString( s ) {
return typeof s === 'string';
};
isArray = Array.isArray || function ( obj ) {
return {}.toString.call( obj ) === '[object Array]';
};
function isUndefined( obj ) {
return obj === undefined;
};
// String prototyping to add `contains`
String.prototype.contains = function(pattern) {
return (this.indexOf(pattern) !== -1);
};
// Cache events support
supportedEvents = {};
function isEventSupported( eventName ) {
// early return if the event is in cache
if ( supportedEvents[eventName] !== undefined ) {
return supportedEvents[eventName];
}
// initiliaze the support at false for detection
supportedEvents[eventName] = false;
// create svg (and childs) nodes
var svg = document.createElementNS( svgns, 'svg' ),
element = document.createElementNS( svgns, 'rect'),
animate = document.createElementNS( svgns, 'animate' );
// set duration to 1ms to detect endEvent
animate.setAttributeNS(null, 'dur', '1ms');
animate.setAttributeNS(null, 'attributeName', 'x');
// append elements
element.appendChild(animate);
svg.appendChild(element);
// attach a listener to the event that update the events cache
legacy.addEventListener.call(animate, eventName + 'Event', function() {
supportedEvents[eventName] = true;
}, false);
// attach svg to the DOM (else it doesn't detect anything) but cache it
svg.setAttributeNS(null, 'style', 'display:none');
document.body.appendChild(svg);
// Set a timeout to remove the dummy SVG element
// It is setted to 50 to leave the DOM breath and get the SVG event
// result before removing it :)
setTimeout(function() { document.body.removeChild(svg); }, 50);
// Return the current event support status
return supportedEvents[eventName];
};
//////////////////////////////////////////////////////////////////////////////
// Clocker.js
// Convert a legal clock string value (in SMIL definition) to milliseconds
//
// Originaly released here: https://github.com/madsgraphics/clocker.js
function clocker( timestr ) {
var time,
times = timestr.split( ':' );
// Timecount-value
// = Formats without ':'
if ( times.length === 1 ) {
time = times[0];
// Time already given in milliseconds (250ms)
if ( time.lastIndexOf('ms') !== -1 ) {
return +(time);
}
// Othermetrics
else {
// minutes
if( time.lastIndexOf('min') !== -1 ) {
time = parseFloat(time) * 60;
}
// hours
else if( time.lastIndexOf('h') !== -1 ) {
time = parseFloat(time) * 3600;
}
// Time is now in seconds.
// If time is without metric, then assume in seconds,
// maybe float (2.05 == 2050ms)
// So convert in ms…
return parseFloat(time) * 1000;
}
}
// Full-clock-value || Partial-clock-value
else {
// Reverse order to iterate from seconds to hours
times.reverse();
// Init time
time = 0;
for ( var t in times ) {
// Value * 60^t (hours / minutes to seconds) * 1000 (s to ms)
time += times[t]*Math.pow(60, t)*1000;
}
return time;
}
}
//////////////////////////////////////////////////////////////////////////////
// Event Listener
//
// Custom Event listener
// Implements Observer pattern
// Create custom listener object with private property to store listeners
//
// initially inspired by:
// http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/
function EventListener( element ) {
// store SVG node
this.el = element;
// Initialize events stack
this._listeners = {};
// constructs stack
this._init();
}
// Extends it to add and fire events
EventListener.prototype = {
constructor: EventListener,
_delayEvent: function (eventName, duration) {
var that = this,
dur = clocker( duration );
return function () {
window.setTimeout( function () {
that.fire( eventName + 'Event' );
}, dur);
};
},
_attachEvent: function (eventName, id) {
var that = this,
previousAnimate = document.getElementById( id );
// Early exit if there is no previousAnimate element available
if (previousAnimate == null) { return; }
// Add an endEvent that launch the next animation
previousAnimate.addEventListener( eventName + 'Event', function () {
that.fire( 'beginEvent' );
});
},
// initializer
_init: function () {
var that = this,
begin = this.el.getAttribute('begin'),
dur = this.el.getAttribute('dur'),
index;
// End event
// ---------
// Add a delayed at duration time
this.add('beginEvent', this._delayEvent('end', dur));
// Begin event
// -----------
// Begin event delayed
if ( begin !== 'indefinite' && !begin.contains('.end') && !begin.contains('.begin') ) {
this._delayEvent('begin', begin);
}
// if the launch depends of the **end** of another animation
else if ( begin.contains('.end') ) {
this._attachEvent('end', begin.replace('.end', ''));
}
// if the launch depends of the **begin** of another animation
else if ( begin.contains('.begin') ) {
this._attachEvent('begin', begin.replace('.begin', ''));
}
},
// add new event to listeners
add: function addListener( type, listener ) {
// if there is no triggers already defined for this events,
// init an a-empty array
if ( isUndefined( this._listeners[type] ) ) {
this._listeners[type] = [];
}
// add trigger to the event
this._listeners[type].push( listener );
},
// fire the event
fire: function fireListeners( event ) {
var name;
// if called only by event name (useful), build a correct object
if ( isString( event ) ) {
event = {
type: event,
bubbles: false,
cancelable: false,
defaultPrevented: false,
currentTarget : null,
};
}
// Early return at fire if the event is already supported
name = event.type.substr(0, event.type.indexOf('Event'));
if (isEventSupported( name )) { return; }
// set target if unavailable
if ( !event.target ) {
event.target = event.currentTarget = this.el;
}
// if there is no event given, throw an error
if ( !event.type ) {
throw new Error( 'Event object missing "type" property.' );
}
// If the type has associated triggers, then launch them
if ( isArray( this._listeners[event.type] ) ) {
var listeners = this._listeners[event.type];
for ( var l in listeners ) {
listeners[l].call( this.el, event );
}
}
}
};
// Overwrite Element.addEventListener method for transparency fallback
//
// Inpired by:
// http://stackoverflow.com/questions/7220515/extending-node-addeventlistener-method-with-the-same-name#7220628
Element.prototype.addEventListener = function ( type, listener, useCapture ) {
if ( this instanceof SVGAnimateElement
|| this instanceof SVGAnimateTransformElement ) {
// ***
// Attach a new event listeners stack if it doesn't exists
if ( isUndefined( this.listeners ) )
{
this.listeners = new EventListener( this );
}
// ***
// check event name and support for endEvent
if ( type === 'endEvent' && !isEventSupported( 'end' ) ) {
// Add listener to the endEvent stack
this.listeners.add( type, listener );
}
// ***
// check event name and suport for beginEvent
if ( type === 'beginEvent' && !isEventSupported( 'begin' ) ) {
// Add listener to the endEvent stack
this.listeners.add( type, listener );
}
}
// ***
// call the original method for fallback
return legacy.addEventListener.call( this, type, listener, useCapture );
};
// Overwrite Element.beginElement method to trigger begin event
SVGAnimateElement.prototype.beginElement = function() {
if ( !isEventSupported( 'begin' ) && this.listeners !== undefined) {
this.listeners.fire('beginEvent');
}
return legacy.svgAnimateBeginElement.call(this);
};
SVGAnimateTransformElement.prototype.beginElement = function() {
if ( !isEventSupported( 'begin' ) && this.listeners !== undefined) {
this.listeners.fire('beginEvent');
}
return legacy.svgAnimateTransformBeginElement.call(this);
};
})();