add cassette player
Some checks are pending
/ test (push) Waiting to run

This commit is contained in:
gribse 2025-04-30 22:21:13 +02:00
parent 2c59e935f4
commit 25b5ca2d7e
45 changed files with 3862 additions and 0 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,999 @@
/**
* jquery.cxassette.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2012, Codrops
* http://www.codrops.com
*/
( function( window, $, undefined ) {
var aux = {
getSupportedType : function() {
var audio = document.createElement( 'audio' );
if ( audio.canPlayType('audio/mpeg;') ) {
return 'mp3';
}
else if ( audio.canPlayType('audio/ogg;') ) {
return 'ogg';
}
else {
return 'wav';
}
}
};
// Cassette obj
$.Cassette = function( options, element ) {
this.$el = $( element );
this._init( options );
};
$.Cassette.defaults = {
// song names. Assumes the path of each song is songs/name.filetype
songs : [ 'BlueDucks_FourFlossFiveSix', 'BlankKytt_ThursdaySnowReprise', 'BlueDucks_FlossSuffersFromGammaRadiation', 'BlankKyt_RSPN' ],
fallbackMessage : 'HTML5 audio not supported',
// initial sound volume
initialVolume : 0.7
};
$.Cassette.prototype = {
_init : function( options ) {
var _self = this;
// the options
this.options = $.extend( true, {}, $.Cassette.defaults, options );
// current side of the tape
this.currentSide = 1;
// current time of playing side
this.cntTime = 0;
// current sum of the duration of played songs
this.timeIterator = 0;
// used for rewind / forward
this.elapsed = 0.0;
// action performed
this.lastaction = '';
// if play / forward / rewind active..
this.isMoving = false;
this.$loader = this.$el.find( 'div.vc-loader' ).show();
// create cassette sides
$.when( this._createSides() ).done( function() {
_self.$loader.hide();
// create player
_self._createPlayer();
_self.sound = new $.Sound();
// load events
_self._loadEvents();
} );
},
_getSide : function() {
return ( this.currentSide === 1 ) ? {
current : this.side1,
reverse : this.side2
} : {
current : this.side2,
reverse : this.side1
};
},
// songs are distributed equally on both sides
_createSides : function() {
var playlistSide1 = [],
playlistSide2 = [],
_self = this,
cnt = 0;
return $.Deferred(
function( dfd ) {
for( var i = 0, len = _self.options.songs.length; i < len; ++i ) {
var song = new $.Song( _self.options.songs[i], i );
$.when( song.loadMetadata() ).done( function( song ) {
( song.id < len / 2 ) ? playlistSide1.push( song ) : playlistSide2.push( song );
++cnt;
if( cnt === len ) {
// two sides, each side with multiple songs
_self.side1 = new $.Side( 'side1', playlistSide1, 'start' ),
_self.side2 = new $.Side( 'side2', playlistSide2, 'end' );
dfd.resolve();
}
} );
}
}
).promise();
},
_createPlayer : function() {
// create HTML5 audio element
this.$audioEl = $( '<audio id="audioElem"><span>' + this.options.fallbackMessage + '</span></audio>' );
this.$el.prepend( this.$audioEl );
this.audio = this.$audioEl.get(0);
// create custom controls
this._createControls();
this.$theTape = this.$el.find( 'div.vc-tape' );
this.$wheelLeft = this.$theTape.find( 'div.vc-tape-wheel-left' );
this.$wheelRight= this.$theTape.find( 'div.vc-tape-wheel-right' );
this.$tapeSideA = this.$theTape.find( 'div.vc-tape-side-a' ).show();
this.$tapeSideB = this.$theTape.find( 'div.vc-tape-side-b' );
},
_createControls : function() {
var _self = this;
this.$controls = $( '<ul class="vc-controls" style="display:none;"/>' );
this.$cPlay = $( '<li class="vc-control-play">Play<span></span></li>' );
this.$cRewind = $( '<li class="vc-control-rewind">Rew<span></span></li>' );
this.$cForward = $( '<li class="vc-control-fforward">FF<span></span></li>' );
this.$cStop = $( '<li class="vc-control-stop">Stop<span></span></li>' );
this.$cSwitch = $( '<li class="vc-control-switch">Switch<span></span></li>' );
this.$controls.append( this.$cPlay )
.append( this.$cRewind )
.append( this.$cForward )
.append( this.$cStop )
.append( this.$cSwitch )
.appendTo( this.$el );
this.$volume = $( '<div style="display:none;" class="vc-volume-wrap"><div class="vc-volume-control"><div class="vc-volume-knob"></div></div></div> ').appendTo( this.$el );
if (document.createElement('audio').canPlayType) {
if (!document.createElement('audio').canPlayType('audio/mpeg') && !document.createElement('audio').canPlayType('audio/ogg')) {
// TODO: flash fallback!
}
else {
this.$controls.show();
this.$volume.show();
this.$volume.find( 'div.vc-volume-knob' ).knobKnob({
snap : 10,
value: 359 * this.options.initialVolume,
turn : function( ratio ) {
_self._changeVolume( ratio );
}
});
this.audio.volume = this.options.initialVolume;
}
}
},
_loadEvents : function() {
var _self = this;
this.$cSwitch.on( 'mousedown', function( event ) {
_self._setButtonActive( $( this ) );
_self._switchSides();
} );
this.$cPlay.on( 'mousedown', function( event ) {
_self._setButtonActive( $( this ) );
_self._play();
} );
this.$cStop.on( 'mousedown', function( event ) {
_self._setButtonActive( $( this ) );
_self._stop();
} );
this.$cForward.on( 'mousedown', function( event ) {
_self._setButtonActive( $( this ) );
_self._forward();
} );
this.$cRewind.on( 'mousedown', function( event ) {
_self._setButtonActive( $( this ) );
_self._rewind();
} );
this.$audioEl.on( 'timeupdate', function( event ) {
_self.cntTime = _self.timeIterator + _self.audio.currentTime;
var wheelVal = _self._getWheelValues( _self.cntTime );
_self._updateWheelValue( wheelVal );
});
this.$audioEl.on( 'loadedmetadata', function( event ) {
});
this.$audioEl.on( 'ended', function( event ) {
_self.timeIterator += _self.audio.duration;
_self._play();
});
},
_setButtonActive : function( $button ) {
// TODO. Solve! For now:
$button.addClass( 'vc-control-pressed' );
setTimeout( function() {
$button.removeClass( 'vc-control-pressed' );
}, 100 );
},
_updateAction : function( action ) {
this.lastaction = action;
},
_prepare : function( song ) {
this._clear();
this.$audioEl.attr( 'src', song.getSource( aux.getSupportedType() ) );
},
_switchSides : function() {
if( this.isMoving ) {
alert( 'Please stop the player before switching sides.' );
return false;
}
this.sound.play( 'switch' );
var _self = this;
this.lastaction = '';
if( this.currentSide === 1 ) {
this.currentSide = 2;
this.$theTape.css( {
'-webkit-transform' : 'rotate3d(0, 1, 0, 180deg)',
'-moz-transform' : 'rotate3d(0, 1, 0, 180deg)',
'-o-transform' : 'rotate3d(0, 1, 0, 180deg)',
'-ms-transform' : 'rotate3d(0, 1, 0, 180deg)',
'transform' : 'rotate3d(0, 1, 0, 180deg)'
} );
setTimeout( function() {
_self.$tapeSideA.hide();
_self.$tapeSideB.show();
// update wheels
_self.cntTime = _self._getPosTime();
}, 200 );
}
else {
this.currentSide = 1;
this.$theTape.css( {
'-webkit-transform' : 'rotate3d(0, 1, 0, 0deg)',
'-moz-transform' : 'rotate3d(0, 1, 0, 0deg)',
'-o-transform' : 'rotate3d(0, 1, 0, 0deg)',
'-ms-transform' : 'rotate3d(0, 1, 0, 0deg)',
'transform' : 'rotate3d(0, 1, 0, 0deg)'
} );
setTimeout( function() {
_self.$tapeSideB.hide();
_self.$tapeSideA.show();
// update wheels
_self.cntTime = _self._getPosTime();
}, 200 );
}
},
_updateButtons : function( button ) {
var pressedClass = 'vc-control-active';
this.$cPlay.removeClass( pressedClass );
this.$cStop.removeClass( pressedClass );
this.$cRewind.removeClass( pressedClass );
this.$cForward.removeClass( pressedClass );
switch( button ) {
case 'play' : this.$cPlay.addClass( pressedClass ); break;
case 'rewind' : this.$cRewind.addClass( pressedClass ); break;
case 'forward' : this.$cForward.addClass( pressedClass ); break;
}
},
_changeVolume : function( ratio ) {
this.audio.volume = ratio;
},
_play : function() {
var _self = this;
this._updateButtons( 'play' );
$.when( this.sound.play( 'click' ) ).done( function() {
var data = _self._updateStatus();
if( data ) {
_self._prepare( _self._getSide().current.getSong( data.songIdx ) );
_self.$audioEl.on( 'canplay', function( event ) {
$( this ).off( 'canplay' );
_self.audio.currentTime = data.timeInSong;
_self.audio.play();
_self.isMoving = true;
_self._setWheelAnimation( '2s', 'play' );
});
}
} );
},
_updateStatus : function( buttons ) {
var posTime = this.cntTime;
// first stop
this._stop( true );
this._setSidesPosStatus( 'middle' );
// the current time to play is this.cntTime +/- [this.elapsed]
if( this.lastaction === 'forward' ) {
posTime += this.elapsed;
}
else if( this.lastaction === 'rewind' ) {
posTime -= this.elapsed;
}
// check if we have more songs to play on the current side..
if( posTime >= this._getSide().current.getDuration() ) {
this._stop( buttons );
this._setSidesPosStatus( 'end' );
return false;
}
this._resetElapsed();
// given this, we need to know which song is playing at this point in time,
// and from which point in time within the song we will play
var data = this._getSongInfoByTime( posTime );
// update cntTime
this.cntTime = posTime;
// update timeIterator
this.timeIterator = data.iterator;
return data;
},
_rewind : function() {
var _self = this,
action = 'rewind';
if( this._getSide().current.getPositionStatus() === 'start' ) {
return false;
}
this._updateButtons( action );
$.when( this.sound.play( 'click' ) ).done( function() {
_self._updateStatus( true );
_self.isMoving = true;
_self._updateAction( action );
_self.sound.play( 'rewind', true );
_self._setWheelAnimation( '0.5s', action );
_self._timer();
} );
},
_forward : function() {
var _self = this,
action = 'forward';
if( this._getSide().current.getPositionStatus() === 'end' ) {
return false;
}
this._updateButtons( action );
$.when( this.sound.play( 'click' ) ).done( function() {
_self._updateStatus( true );
_self.isMoving = true;
_self._updateAction( action );
_self.sound.play( 'fforward', true );
_self._setWheelAnimation( '0.5s', action );
_self._timer();
} );
},
_stop : function( buttons ) {
if( !buttons ) {
this._updateButtons( 'stop' );
this.sound.play( 'click' );
}
this.isMoving = false;
this._stopWheels();
this.audio.pause();
this._stopTimer();
},
_clear : function() {
this.$audioEl.children( 'source' ).remove();
},
_setSidesPosStatus : function( position ) {
this._getSide().current.setPositionStatus( position );
switch( position ) {
case 'middle' : this._getSide().reverse.setPositionStatus( position );break;
case 'start' : this._getSide().reverse.setPositionStatus( 'end' );break;
case 'end' : this._getSide().reverse.setPositionStatus( 'start' );break;
}
},
// given a point in time for the current side, returns the respective song of that side and the respective time within the song
_getSongInfoByTime : function( time ) {
var data = { songIdx : 0, timeInSong : 0 },
side = this._getSide().current,
playlist = side.getPlaylist(),
len = side.getPlaylistCount(),
cntTime = 0;
for( var i = 0; i < len; ++i ) {
var song = playlist[ i ],
duration = song.getDuration();
cntTime += duration;
if( cntTime > time ) {
data.songIdx = i;
data.timeInSong = time - ( cntTime - duration );
data.iterator = cntTime - duration;
return data;
}
}
return data;
},
_getWheelValues : function( x ) {
var T = this._getSide().current.getDuration(),
val = {
left : ( this.currentSide === 1 ) ? ( -70 / T ) * x + 70 : ( 70 / T ) * x,
right : ( this.currentSide === 1 ) ? ( 70 / T ) * x : ( -70 / T ) * x + 70
};
return val;
},
_getPosTime : function() {
var wleft = this.$wheelLeft.data( 'wheel' ),
wright = this.$wheelRight.data( 'wheel' );
if( wleft === undefined ) {
wleft = 70;
}
if( wright === undefined ) {
wright = 0;
}
var T = this._getSide().current.getDuration(),
posTime = this.currentSide === 2 ? ( T * wleft ) / 70 : ( T * wright ) / 70;
return posTime;
},
_updateWheelValue : function( wheelVal ) {
this.$wheelLeft.data( 'wheel', wheelVal.left ).css( { 'box-shadow' : '0 0 0 ' + wheelVal.left + 'px black' } );
this.$wheelRight.data( 'wheel', wheelVal.right ).css( { 'box-shadow' : '0 0 0 ' + wheelVal.right + 'px black' } );
},
_setWheelAnimation : function( speed, mode ) {
var _self = this, anim = '';
switch( this.currentSide ) {
case 1 :
if( mode === 'play' || mode === 'forward' ) {
anim = 'rotateLeft';
}
else if( mode === 'rewind' ) {
anim = 'rotateRight';
}
break;
case 2 :
if( mode === 'play' || mode === 'forward' ) {
anim = 'rotateRight';
}
else if( mode === 'rewind' ) {
anim = 'rotateLeft';
}
break;
}
var animStyle = {
'-webkit-animation' : anim + ' ' + speed + ' linear infinite forwards',
'-moz-animation' : anim + ' ' + speed + ' linear infinite forwards',
'-o-animation' : anim + ' ' + speed + ' linear infinite forwards',
'-ms-animation' : anim + ' ' + speed + ' linear infinite forwards',
'animation' : anim + ' ' + speed + ' linear infinite forwards'
};
setTimeout( function() {
_self.$wheelLeft.css(animStyle);
_self.$wheelRight.css(animStyle);
}, 0 );
},
_stopWheels : function() {
var wheelStyle = {
'-webkit-animation' : 'none',
'-moz-animation' : 'none',
'-o-animation' : 'none',
'-ms-animation' : 'none',
'animation' : 'none'
}
this.$wheelLeft.css( wheelStyle );
this.$wheelRight.css( wheelStyle );
},
// credits: http://www.sitepoint.com/creating-accurate-timers-in-javascript/
_timer : function() {
var _self = this,
start = new Date().getTime(),
time = 0;
this._resetElapsed();
this.isSeeking = true;
this._setSidesPosStatus( 'middle' );
if( this.isSeeking ) {
clearTimeout( this.timertimeout );
this.timertimeout = setTimeout( function() {
_self._timerinstance( start, time );
}, 100 );
}
},
_timerinstance : function( start, time ) {
var _self = this;
time += 100;
this.elapsed = Math.floor(time / 20) / 10;
if( Math.round( this.elapsed ) == this.elapsed ) {
this.elapsed += 0.0;
}
// stop if it reaches the end of the cassette / side
// or if it reaches the beginning
var posTime = this.cntTime;
if( this.lastaction === 'forward' ) {
posTime += this.elapsed;
}
else if( this.lastaction === 'rewind' ) {
posTime -= this.elapsed;
}
var wheelVal = this._getWheelValues( posTime );
this._updateWheelValue( wheelVal );
if( posTime >= this._getSide().current.getDuration() || posTime <= 0 ) {
this._stop();
( posTime <= 0) ? this.cntTime = 0 : this.cntTime = posTime;
this._resetElapsed();
( posTime <= 0) ? this._setSidesPosStatus( 'start' ) : this._setSidesPosStatus( 'end' );
return false;
}
var diff = (new Date().getTime() - start) - time;
if( this.isSeeking ) {
clearTimeout( this.timertimeout );
this.timertimeout = setTimeout( function() {
_self._timerinstance( start, time );
}, ( 100 - diff ) );
}
},
_stopTimer : function() {
clearTimeout( this.timertimeout );
this.isSeeking = false;
},
_resetElapsed : function() {
this.elapsed = 0.0;
}
};
// Cassette side obj
$.Side = function( id, playlist, status ) {
// side's name / id
this.id = id;
// status is "start", "middle" or "end"
this.status = status;
// array of songs sorted by song id
this.playlist = playlist.sort( function( a, b ) {
var aid = a.id,
bid = b.id;
return ( ( aid < bid ) ? -1 : ( ( aid > bid ) ? 1 : 0 ) );
} );
// set playlist duration
this._setDuration();
// total number of songs
this.playlistCount = playlist.length;
};
$.Side.prototype = {
getSong : function( num ) {
return this.playlist[ num ];
},
getPlaylist : function() {
return this.playlist;
},
_setDuration : function() {
this.duration = 0;
for( var i = 0, len = this.playlist.length; i < len; ++i ) {
this.duration += this.playlist[ i ].duration;
}
},
getDuration : function() {
return this.duration;
},
getPlaylistCount : function() {
return this.playlistCount;
},
setPositionStatus : function( status ) {
this.status = status;
},
getPositionStatus : function() {
return this.status;
}
};
// Song obj
$.Song = function( name, id ) {
this.id = id;
this.name = name;
this._init();
};
$.Song.prototype = {
_init : function() {
this.sources = {
mp3 : 'songs/' + this.name + '.mp3',
ogg : 'songs/' + this.name + '.ogg'
};
},
getSource : function( type ) {
return this.sources[type];
},
// load metadata to get the duration of the song
loadMetadata : function() {
var _self = this;
return $.Deferred(
function( dfd ) {
var $tmpAudio = $( '<audio/>' ),
songsrc = _self.getSource( aux.getSupportedType() );
$tmpAudio.attr( 'preload', 'auto' );
$tmpAudio.attr( 'src', songsrc );
$tmpAudio.on( 'loadedmetadata', function( event ) {
_self.duration = $tmpAudio.get(0).duration;
dfd.resolve( _self );
});
}
).promise();
},
getDuration : function() {
return this.duration;
}
};
// Sound obj
$.Sound = function() {
this._init();
};
$.Sound.prototype = {
_init : function() {
this.$audio = $( '<audio/>' ).attr( 'preload', 'auto' );
},
getSource : function( type ) {
return 'sounds/' + this.action + '.' + type;
},
play : function( action, loop ) {
var _self = this;
return $.Deferred( function( dfd ) {
_self.action = action;
var soundsrc = _self.getSource( aux.getSupportedType() );
_self.$audio.attr( 'src', soundsrc );
if( loop ) {
_self.$audio.attr( 'loop', loop );
}
else {
_self.$audio.removeAttr( 'loop' );
}
_self.$audio.on( 'canplay', function( event ) {
$( this ).on( 'ended', function() {
$( this ).off( 'ended' );
dfd.resolve();
} ).get(0).play();
});
});
}
};
var logError = function( message ) {
if ( window.console ) {
window.console.error( message );
}
};
$.fn.cassette = function( options ) {
if ( typeof options === 'string' ) {
var args = Array.prototype.slice.call( arguments, 1 );
this.each(function() {
var instance = $.data( this, 'cassette' );
if ( !instance ) {
logError( "cannot call methods on cassette prior to initialization; " +
"attempted to call method '" + options + "'" );
return;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
logError( "no such method '" + options + "' for cassette instance" );
return;
}
instance[ options ].apply( instance, args );
});
}
else {
this.each(function() {
var instance = $.data( this, 'cassette' );
if ( !instance ) {
$.data( this, 'cassette', new $.Cassette( options, this ) );
}
});
}
return this;
};
} )( window, jQuery );

View file

@ -0,0 +1,120 @@
/**
* @name jQuery KnobKnob plugin
* @author Martin Angelov
* @version 1.0
* @url http://tutorialzine.com/2011/11/pretty-switches-css3-jquery/
* @license MIT License
*/
(function($){
$.fn.knobKnob = function(props){
var options = $.extend({
snap: 0,
value: 0,
turn: function(){}
}, props || {});
var tpl = '<div class="knob">\
<div class="top"></div>\
<div class="base"></div>\
</div>';
return this.each(function(){
var el = $(this);
el.append(tpl);
var knob = $('.knob',el),
knobTop = knob.find('.top'),
startDeg = -1,
currentDeg = 0,
rotation = 0,
lastDeg = 0,
doc = $(document);
if(options.value > 0 && options.value <= 359){
rotation = lastDeg = currentDeg = options.value;
knobTop.css('transform','rotate('+(currentDeg)+'deg)');
options.turn(currentDeg/359);
}
knob.on('mousedown touchstart', function(e){
e.preventDefault();
var offset = knob.offset();
var center = {
y : offset.top + knob.height()/2,
x: offset.left + knob.width()/2
};
var a, b, deg, tmp,
rad2deg = 180/Math.PI;
knob.on('mousemove.rem touchmove.rem',function(e){
e = (e.originalEvent.touches) ? e.originalEvent.touches[0] : e;
a = center.y - e.pageY;
b = center.x - e.pageX;
deg = Math.atan2(a,b)*rad2deg;
// we have to make sure that negative
// angles are turned into positive:
if(deg<0){
deg = 360 + deg;
}
// Save the starting position of the drag
if(startDeg == -1){
startDeg = deg;
}
// Calculating the current rotation
tmp = Math.floor((deg-startDeg) + rotation);
// Making sure the current rotation
// stays between 0 and 359
if(tmp < 0){
tmp = 360 + tmp;
}
else if(tmp > 359){
tmp = tmp % 360;
}
// Snapping in the off position:
if(options.snap && tmp < options.snap){
tmp = 0;
}
// This would suggest we are at an end position;
// we need to block further rotation.
if(Math.abs(tmp - lastDeg) > 180){
return false;
}
currentDeg = tmp;
lastDeg = tmp;
knobTop.css('transform','rotate('+(currentDeg)+'deg)');
options.turn(currentDeg/360);
});
doc.on('mouseup.rem touchend.rem',function(){
knob.off('.rem');
doc.off('.rem');
// Saving the current rotation
rotation = currentDeg;
// Marking the starting degree as invalid
startDeg = -1;
});
});
});
};
})(jQuery);

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,532 @@
/*
* transform: A jQuery cssHooks adding cross-browser 2d transform capabilities to $.fn.css() and $.fn.animate()
*
* limitations:
* - requires jQuery 1.4.3+
* - Should you use the *translate* property, then your elements need to be absolutely positionned in a relatively positionned wrapper **or it will fail in IE678**.
* - transformOrigin is not accessible
*
* latest version and complete README available on Github:
* https://github.com/louisremi/jquery.transform.js
*
* Copyright 2011 @louis_remi
* Licensed under the MIT license.
*
* This saved you an hour of work?
* Send me music http://www.amazon.co.uk/wishlist/HNTU0468LQON
*
*/
(function( $ ) {
/*
* Feature tests and global variables
*/
var div = document.createElement('div'),
divStyle = div.style,
propertyName = 'transform',
suffix = 'Transform',
testProperties = [
'O' + suffix,
'ms' + suffix,
'Webkit' + suffix,
'Moz' + suffix,
// prefix-less property
propertyName
],
i = testProperties.length,
supportProperty,
supportMatrixFilter,
propertyHook,
propertyGet,
rMatrix = /Matrix([^)]*)/;
// test different vendor prefixes of this property
while ( i-- ) {
if ( testProperties[i] in divStyle ) {
$.support[propertyName] = supportProperty = testProperties[i];
continue;
}
}
// IE678 alternative
if ( !supportProperty ) {
$.support.matrixFilter = supportMatrixFilter = divStyle.filter === '';
}
// prevent IE memory leak
div = divStyle = null;
// px isn't the default unit of this property
$.cssNumber[propertyName] = true;
/*
* fn.css() hooks
*/
if ( supportProperty && supportProperty != propertyName ) {
// Modern browsers can use jQuery.cssProps as a basic hook
$.cssProps[propertyName] = supportProperty;
// Firefox needs a complete hook because it stuffs matrix with 'px'
if ( supportProperty == 'Moz' + suffix ) {
propertyHook = {
get: function( elem, computed ) {
return (computed ?
// remove 'px' from the computed matrix
$.css( elem, supportProperty ).split('px').join(''):
elem.style[supportProperty]
)
},
set: function( elem, value ) {
// remove 'px' from matrices
elem.style[supportProperty] = /matrix[^)p]*\)/.test(value) ?
value.replace(/matrix((?:[^,]*,){4})([^,]*),([^)]*)/, 'matrix$1$2px,$3px'):
value;
}
}
/* Fix two jQuery bugs still present in 1.5.1
* - rupper is incompatible with IE9, see http://jqbug.com/8346
* - jQuery.css is not really jQuery.cssProps aware, see http://jqbug.com/8402
*/
} else if ( /^1\.[0-5](?:\.|$)/.test($.fn.jquery) ) {
propertyHook = {
get: function( elem, computed ) {
return (computed ?
$.css( elem, supportProperty.replace(/^ms/, 'Ms') ):
elem.style[supportProperty]
)
}
}
}
/* TODO: leverage hardware acceleration of 3d transform in Webkit only
else if ( supportProperty == 'Webkit' + suffix && support3dTransform ) {
propertyHook = {
set: function( elem, value ) {
elem.style[supportProperty] =
value.replace();
}
}
}*/
} else if ( supportMatrixFilter ) {
propertyHook = {
get: function( elem, computed ) {
var elemStyle = ( computed && elem.currentStyle ? elem.currentStyle : elem.style ),
matrix;
if ( elemStyle && rMatrix.test( elemStyle.filter ) ) {
matrix = RegExp.$1.split(',');
matrix = [
matrix[0].split('=')[1],
matrix[2].split('=')[1],
matrix[1].split('=')[1],
matrix[3].split('=')[1]
];
} else {
matrix = [1,0,0,1];
}
matrix[4] = elemStyle ? elemStyle.left : 0;
matrix[5] = elemStyle ? elemStyle.top : 0;
return "matrix(" + matrix + ")";
},
set: function( elem, value, animate ) {
var elemStyle = elem.style,
currentStyle,
Matrix,
filter;
if ( !animate ) {
elemStyle.zoom = 1;
}
value = matrix(value);
// rotate, scale and skew
if ( !animate || animate.M ) {
Matrix = [
"Matrix("+
"M11="+value[0],
"M12="+value[2],
"M21="+value[1],
"M22="+value[3],
"SizingMethod='auto expand'"
].join();
filter = ( currentStyle = elem.currentStyle ) && currentStyle.filter || elemStyle.filter || "";
elemStyle.filter = rMatrix.test(filter) ?
filter.replace(rMatrix, Matrix) :
filter + " progid:DXImageTransform.Microsoft." + Matrix + ")";
// center the transform origin, from pbakaus's Transformie http://github.com/pbakaus/transformie
if ( (centerOrigin = $.transform.centerOrigin) ) {
elemStyle[centerOrigin == 'margin' ? 'marginLeft' : 'left'] = -(elem.offsetWidth/2) + (elem.clientWidth/2) + 'px';
elemStyle[centerOrigin == 'margin' ? 'marginTop' : 'top'] = -(elem.offsetHeight/2) + (elem.clientHeight/2) + 'px';
}
}
// translate
if ( !animate || animate.T ) {
// We assume that the elements are absolute positionned inside a relative positionned wrapper
elemStyle.left = value[4] + 'px';
elemStyle.top = value[5] + 'px';
}
}
}
}
// populate jQuery.cssHooks with the appropriate hook if necessary
if ( propertyHook ) {
$.cssHooks[propertyName] = propertyHook;
}
// we need a unique setter for the animation logic
propertyGet = propertyHook && propertyHook.get || $.css;
/*
* fn.animate() hooks
*/
$.fx.step.transform = function( fx ) {
var elem = fx.elem,
start = fx.start,
end = fx.end,
split,
pos = fx.pos,
transform,
translate,
rotate,
scale,
skew,
T = false,
M = false,
prop;
translate = rotate = scale = skew = '';
// fx.end and fx.start need to be converted to their translate/rotate/scale/skew components
// so that we can interpolate them
if ( !start || typeof start === "string" ) {
// the following block can be commented out with jQuery 1.5.1+, see #7912
if (!start) {
start = propertyGet( elem, supportProperty );
}
// force layout only once per animation
if ( supportMatrixFilter ) {
elem.style.zoom = 1;
}
// if the start computed matrix is in end, we are doing a relative animation
split = end.split(start);
if ( split.length == 2 ) {
// remove the start computed matrix to make animations more accurate
end = split.join('');
fx.origin = start;
start = 'none';
}
// start is either 'none' or a matrix(...) that has to be parsed
fx.start = start = start == 'none'?
{
translate: [0,0],
rotate: 0,
scale: [1,1],
skew: [0,0]
}:
unmatrix( toArray(start) );
// fx.end has to be parsed and decomposed
fx.end = end = ~end.indexOf('matrix')?
// bullet-proof parser
unmatrix(matrix(end)):
// faster and more precise parser
components(end);
// get rid of properties that do not change
for ( prop in start) {
if ( prop == 'rotate' ?
start[prop] == end[prop]:
start[prop][0] == end[prop][0] && start[prop][1] == end[prop][1]
) {
delete start[prop];
}
}
}
/*
* We want a fast interpolation algorithm.
* This implies avoiding function calls and sacrifying DRY principle:
* - avoid $.each(function(){})
* - round values using bitewise hacks, see http://jsperf.com/math-round-vs-hack/3
*/
if ( start.translate ) {
// round translate to the closest pixel
translate = ' translate('+
((start.translate[0] + (end.translate[0] - start.translate[0]) * pos + .5) | 0) +'px,'+
((start.translate[1] + (end.translate[1] - start.translate[1]) * pos + .5) | 0) +'px'+
')';
T = true;
}
if ( start.rotate != undefined ) {
rotate = ' rotate('+ (start.rotate + (end.rotate - start.rotate) * pos) +'rad)';
M = true;
}
if ( start.scale ) {
scale = ' scale('+
(start.scale[0] + (end.scale[0] - start.scale[0]) * pos) +','+
(start.scale[1] + (end.scale[1] - start.scale[1]) * pos) +
')';
M = true;
}
if ( start.skew ) {
skew = ' skew('+
(start.skew[0] + (end.skew[0] - start.skew[0]) * pos) +'rad,'+
(start.skew[1] + (end.skew[1] - start.skew[1]) * pos) +'rad'+
')';
M = true;
}
// In case of relative animation, restore the origin computed matrix here.
transform = fx.origin ?
fx.origin + translate + skew + scale + rotate:
translate + rotate + scale + skew;
propertyHook && propertyHook.set ?
propertyHook.set( elem, transform, {M: M, T: T} ):
elem.style[supportProperty] = transform;
};
/*
* Utility functions
*/
// turns a transform string into its 'matrix(A,B,C,D,X,Y)' form (as an array, though)
function matrix( transform ) {
transform = transform.split(')');
var
trim = $.trim
// last element of the array is an empty string, get rid of it
, i = transform.length -1
, split, prop, val
, A = 1
, B = 0
, C = 0
, D = 1
, A_, B_, C_, D_
, tmp1, tmp2
, X = 0
, Y = 0
;
// Loop through the transform properties, parse and multiply them
while (i--) {
split = transform[i].split('(');
prop = trim(split[0]);
val = split[1];
A_ = B_ = C_ = D_ = 0;
switch (prop) {
case 'translateX':
X += parseInt(val, 10);
continue;
case 'translateY':
Y += parseInt(val, 10);
continue;
case 'translate':
val = val.split(',');
X += parseInt(val[0], 10);
Y += parseInt(val[1] || 0, 10);
continue;
case 'rotate':
val = toRadian(val);
A_ = Math.cos(val);
B_ = Math.sin(val);
C_ = -Math.sin(val);
D_ = Math.cos(val);
break;
case 'scaleX':
A_ = val;
D_ = 1;
break;
case 'scaleY':
A_ = 1;
D_ = val;
break;
case 'scale':
val = val.split(',');
A_ = val[0];
D_ = val.length>1 ? val[1] : val[0];
break;
case 'skewX':
A_ = D_ = 1;
C_ = Math.tan(toRadian(val));
break;
case 'skewY':
A_ = D_ = 1;
B_ = Math.tan(toRadian(val));
break;
case 'skew':
A_ = D_ = 1;
val = val.split(',');
C_ = Math.tan(toRadian(val[0]));
B_ = Math.tan(toRadian(val[1] || 0));
break;
case 'matrix':
val = val.split(',');
A_ = +val[0];
B_ = +val[1];
C_ = +val[2];
D_ = +val[3];
X += parseInt(val[4], 10);
Y += parseInt(val[5], 10);
}
// Matrix product
tmp1 = A * A_ + B * C_;
B = A * B_ + B * D_;
tmp2 = C * A_ + D * C_;
D = C * B_ + D * D_;
A = tmp1;
C = tmp2;
}
return [A,B,C,D,X,Y];
}
// turns a matrix into its rotate, scale and skew components
// algorithm from http://hg.mozilla.org/mozilla-central/file/7cb3e9795d04/layout/style/nsStyleAnimation.cpp
function unmatrix(matrix) {
var
scaleX
, scaleY
, skew
, A = matrix[0]
, B = matrix[1]
, C = matrix[2]
, D = matrix[3]
;
// Make sure matrix is not singular
if ( A * D - B * C ) {
// step (3)
scaleX = Math.sqrt( A * A + B * B );
A /= scaleX;
B /= scaleX;
// step (4)
skew = A * C + B * D;
C -= A * skew;
D -= B * skew;
// step (5)
scaleY = Math.sqrt( C * C + D * D );
C /= scaleY;
D /= scaleY;
skew /= scaleY;
// step (6)
if ( A * D < B * C ) {
//scaleY = -scaleY;
//skew = -skew;
A = -A;
B = -B;
skew = -skew;
scaleX = -scaleX;
}
// matrix is singular and cannot be interpolated
} else {
rotate = scaleX = scaleY = skew = 0;
}
return {
translate: [+matrix[4], +matrix[5]],
rotate: Math.atan2(B, A),
scale: [scaleX, scaleY],
skew: [skew, 0]
}
}
// parse tranform components of a transform string not containing 'matrix(...)'
function components( transform ) {
// split the != transforms
transform = transform.split(')');
var translate = [0,0],
rotate = 0,
scale = [1,1],
skew = [0,0],
i = transform.length -1,
trim = $.trim,
split, name, value;
// add components
while ( i-- ) {
split = transform[i].split('(');
name = trim(split[0]);
value = split[1];
if (name == 'translateX') {
translate[0] += parseInt(value, 10);
} else if (name == 'translateY') {
translate[1] += parseInt(value, 10);
} else if (name == 'translate') {
value = value.split(',');
translate[0] += parseInt(value[0], 10);
translate[1] += parseInt(value[1] || 0, 10);
} else if (name == 'rotate') {
rotate += toRadian(value);
} else if (name == 'scaleX') {
scale[0] *= value;
} else if (name == 'scaleY') {
scale[1] *= value;
} else if (name == 'scale') {
value = value.split(',');
scale[0] *= value[0];
scale[1] *= (value.length>1? value[1] : value[0]);
} else if (name == 'skewX') {
skew[0] += toRadian(value);
} else if (name == 'skewY') {
skew[1] += toRadian(value);
} else if (name == 'skew') {
value = value.split(',');
skew[0] += toRadian(value[0]);
skew[1] += toRadian(value[1] || '0');
}
}
return {
translate: translate,
rotate: rotate,
scale: scale,
skew: skew
};
}
// converts an angle string in any unit to a radian Float
function toRadian(value) {
return ~value.indexOf('deg') ?
parseInt(value,10) * (Math.PI * 2 / 360):
~value.indexOf('grad') ?
parseInt(value,10) * (Math.PI/200):
parseFloat(value);
}
// Converts 'matrix(A,B,C,D,X,Y)' to [A,B,C,D,X,Y]
function toArray(matrix) {
// Fremove the unit of X and Y for Firefox
matrix = /\(([^,]*),([^,]*),([^,]*),([^,]*),([^,p]*)(?:px)?,([^)p]*)(?:px)?/.exec(matrix);
return [matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6]];
}
$.transform = {
centerOrigin: 'margin'
};
})( jQuery );