1// Copyright 2016 Google Inc. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15(function() { 16 17 if (document.createElement('div').animate([]).oncancel !== undefined) { 18 return; 19 } 20 21 if (WEB_ANIMATIONS_TESTING) { 22 var now = function() { return webAnimations1.timeline.currentTime; }; 23 } else if (window.performance && performance.now) { 24 var now = function() { return performance.now(); }; 25 } else { 26 var now = function() { return Date.now(); }; 27 } 28 29 var AnimationCancelEvent = function(target, currentTime, timelineTime) { 30 this.target = target; 31 this.currentTime = currentTime; 32 this.timelineTime = timelineTime; 33 34 this.type = 'cancel'; 35 this.bubbles = false; 36 this.cancelable = false; 37 this.currentTarget = target; 38 this.defaultPrevented = false; 39 this.eventPhase = Event.AT_TARGET; 40 this.timeStamp = Date.now(); 41 }; 42 43 var originalElementAnimate = window.Element.prototype.animate; 44 window.Element.prototype.animate = function(effectInput, options) { 45 var animation = originalElementAnimate.call(this, effectInput, options); 46 47 animation._cancelHandlers = []; 48 animation.oncancel = null; 49 50 var originalCancel = animation.cancel; 51 animation.cancel = function() { 52 originalCancel.call(this); 53 var event = new AnimationCancelEvent(this, null, now()); 54 var handlers = this._cancelHandlers.concat(this.oncancel ? [this.oncancel] : []); 55 setTimeout(function() { 56 handlers.forEach(function(handler) { 57 handler.call(event.target, event); 58 }); 59 }, 0); 60 }; 61 62 var originalAddEventListener = animation.addEventListener; 63 animation.addEventListener = function(type, handler) { 64 if (typeof handler == 'function' && type == 'cancel') 65 this._cancelHandlers.push(handler); 66 else 67 originalAddEventListener.call(this, type, handler); 68 }; 69 70 var originalRemoveEventListener = animation.removeEventListener; 71 animation.removeEventListener = function(type, handler) { 72 if (type == 'cancel') { 73 var index = this._cancelHandlers.indexOf(handler); 74 if (index >= 0) 75 this._cancelHandlers.splice(index, 1); 76 } else { 77 originalRemoveEventListener.call(this, type, handler); 78 } 79 }; 80 81 return animation; 82 }; 83})(); 84