2
PIE: CSS3 rendering for IE
5
Dual-licensed for use under the Apache License Version 2.0 or the General Public License (GPL) Version 2.
7
<PUBLIC:COMPONENT lightWeight="true">
8
<!-- saved from url=(0014)about:internet -->
9
<PUBLIC:ATTACH EVENT="oncontentready" FOR="element" ONEVENT="init()" />
10
<PUBLIC:ATTACH EVENT="ondocumentready" FOR="element" ONEVENT="init()" />
11
<PUBLIC:ATTACH EVENT="ondetach" FOR="element" ONEVENT="cleanup()" />
13
<script type="text/javascript">
14
var doc = element.document;var PIE = window['PIE'];
17
PIE = window['PIE'] = {
27
* Lookup table of elements which cannot take custom children.
44
* Elements that can receive user focus
55
* Values of the type attribute for input elements displayed as buttons
63
emptyFn: function() {}
66
// Force the background cache to be used. No reason it shouldn't be.
68
doc.execCommand( 'BackgroundImageCache', false, true );
73
* IE version detection approach by James Padolsey, with modifications -- from
74
* http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
77
div = doc.createElement('div'),
78
all = div.getElementsByTagName('i'),
81
div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->',
84
PIE.ieVersion = ieVersion;
87
if( ieVersion === 6 ) {
88
// IE6 can't access properties with leading dash, but can without it.
89
PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' );
92
PIE.ieDocMode = doc.documentMode || PIE.ieVersion;
94
// Detect VML support (a small number of IE installs don't have a working VML engine)
95
div.innerHTML = '<v:shape adj="1"/>';
96
shape = div.firstChild;
97
shape.style['behavior'] = 'url(#default#VML)';
98
PIE.supportsVML = (typeof shape['adj'] === "object");
112
* To create a VML element, it must be created by a Document which has the VML
113
* namespace set. Unfortunately, if you try to add the namespace programatically
114
* into the main document, you will get an "Unspecified error" when trying to
115
* access document.namespaces before the document is finished loading. To get
116
* around this, we create a DocumentFragment, which in IE land is apparently a
117
* full-fledged Document. It allows adding namespaces immediately, so we add the
118
* namespace there and then have it create the VML element.
119
* @param {string} tag The tag name for the VML element
120
* @return {Element} The new VML element
122
createVmlElement: function( tag ) {
123
var vmlPrefix = 'css3vml';
124
if( !vmlCreatorDoc ) {
125
vmlCreatorDoc = doc.createDocumentFragment();
126
vmlCreatorDoc.namespaces.add( vmlPrefix, 'urn:schemas-microsoft-com:vml' );
128
return vmlCreatorDoc.createElement( vmlPrefix + ':' + tag );
133
* Generate and return a unique ID for a given object. The generated ID is stored
134
* as a property of the object for future reuse.
135
* @param {Object} obj
137
getUID: function( obj ) {
138
return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + ++idNum );
143
* Simple utility for merging objects
144
* @param {Object} obj1 The main object into which all others will be merged
145
* @param {...Object} var_args Other objects which will be merged into the first, in order
147
merge: function( obj1 ) {
148
var i, len, p, objN, args = arguments;
149
for( i = 1, len = args.length; i < len; i++ ) {
152
if( objN.hasOwnProperty( p ) ) {
153
obj1[ p ] = objN[ p ];
162
* Execute a callback function, passing it the dimensions of a given image once
164
* @param {string} src The source URL of the image
165
* @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known
166
* @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function
168
withImageSize: function( src, func, ctx ) {
169
var size = imageSizes[ src ], img, queue;
171
// If we have a queue, add to it
172
if( Object.prototype.toString.call( size ) === '[object Array]' ) {
173
size.push( [ func, ctx ] );
175
// Already have the size cached, call func right away
177
func.call( ctx, size );
180
queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue
182
img.onload = function() {
183
size = imageSizes[ src ] = { w: img.width, h: img.height };
184
for( var i = 0, len = queue.length; i < len; i++ ) {
185
queue[ i ][ 0 ].call( queue[ i ][ 1 ], size );
194
* Utility functions for handling gradients
198
getGradientMetrics: function( el, width, height, gradientInfo ) {
199
var angle = gradientInfo.angle,
200
startPos = gradientInfo.gradientStart,
203
startCornerX, startCornerY,
204
endCornerX, endCornerY,
208
// Find the "start" and "end" corners; these are the corners furthest along the gradient line.
209
// This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding
210
// the total length of the VML rendered gradient-line corner to corner.
211
function findCorners() {
212
startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0;
213
startCornerY = angle < 180 ? height : 0;
214
endCornerX = width - startCornerX;
215
endCornerY = height - startCornerY;
218
// Normalize the angle to a value between [0, 360)
219
function normalizeAngle() {
226
// Find the start and end points of the gradient
228
startPos = startPos.coords( el, width, height );
233
angle = angle.degrees();
238
// If no start position was specified, then choose a corner as the starting point.
240
startX = startCornerX;
241
startY = startCornerY;
244
// Find the end position by extending a perpendicular line from the gradient-line which
245
// intersects the corner opposite from the starting corner.
246
p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY );
250
else if( startPos ) {
251
// Start position but no angle specified: find the end point by rotating 180deg around the center
252
endX = width - startX;
253
endY = height - startY;
256
// Neither position nor angle specified; create vertical gradient from top to bottom
257
startX = startY = endX = 0;
260
deltaX = endX - startX;
261
deltaY = endY - startY;
263
if( angle === UNDEF ) {
264
// Get the angle based on the change in x/y from start to end point. Checks first for horizontal
265
// or vertical angles so they get exact whole numbers rather than what atan2 gives.
266
angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) :
267
( !deltaY ? ( deltaX < 0 ? 180 : 0 ) :
268
-Math.atan2( deltaY, deltaX ) / Math.PI * 180
281
startCornerX: startCornerX,
282
startCornerY: startCornerY,
283
endCornerX: endCornerX,
284
endCornerY: endCornerY,
287
lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY )
292
* Find the point along a given line (defined by a starting point and an angle), at which
293
* that line is intersected by a perpendicular line extending through another point.
294
* @param x1 - x coord of the starting point
295
* @param y1 - y coord of the starting point
296
* @param angle - angle of the line extending from the starting point (in degrees)
297
* @param x2 - x coord of point along the perpendicular line
298
* @param y2 - y coord of point along the perpendicular line
301
perpendicularIntersect: function( x1, y1, angle, x2, y2 ) {
302
// Handle straight vertical and horizontal angles, for performance and to avoid
303
// divide-by-zero errors.
304
if( angle === 0 || angle === 180 ) {
307
else if( angle === 90 || angle === 270 ) {
311
// General approach: determine the Ax+By=C formula for each line (the slope of the second
312
// line is the negative inverse of the first) and then solve for where both formulas have
313
// the same x/y values.
314
var a1 = Math.tan( -angle * Math.PI / 180 ),
319
endX = ( c2 - c1 ) / d,
320
endY = ( a1 * c2 - a2 * c1 ) / d;
321
return [ endX, endY ];
326
* Find the distance between two points
327
* @param {Number} p1x
328
* @param {Number} p1y
329
* @param {Number} p2x
330
* @param {Number} p2y
331
* @return {Number} the distance
333
distance: function( p1x, p1y, p2x, p2y ) {
339
Math.sqrt( dx * dx + dy * dy )
346
PIE.Observable = function() {
348
* List of registered observer functions
353
* Hash of function ids to their position in the observers list, for fast lookup
357
PIE.Observable.prototype = {
359
observe: function( fn ) {
360
var id = PIE.Util.getUID( fn ),
361
indexes = this.indexes,
362
observers = this.observers;
363
if( !( id in indexes ) ) {
364
indexes[ id ] = observers.length;
365
observers.push( fn );
369
unobserve: function( fn ) {
370
var id = PIE.Util.getUID( fn ),
371
indexes = this.indexes;
372
if( id && id in indexes ) {
373
delete this.observers[ indexes[ id ] ];
374
delete indexes[ id ];
379
var o = this.observers,
387
* Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not
388
* always firing the onmove and onresize events when elements are moved or resized. We check a few
389
* times every second to make sure the elements have the correct position and size. See Element.js
390
* which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9
391
* and false elsewhere.
394
PIE.Heartbeat = new PIE.Observable();
395
PIE.Heartbeat.run = function() {
399
interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250;
402
setTimeout(beat, interval);
408
* Create an observable listener for the onunload event
411
PIE.OnUnload = new PIE.Observable();
413
function handleUnload() {
415
window.detachEvent( 'onunload', handleUnload );
416
window[ 'PIE' ] = null;
419
window.attachEvent( 'onunload', handleUnload );
422
* Attach an event which automatically gets detached onunload
424
PIE.OnUnload.attachManagedEvent = function( target, name, handler ) {
425
target.attachEvent( name, handler );
426
this.observe( function() {
427
target.detachEvent( name, handler );
431
* Create a single observable listener for window resize events.
433
PIE.OnResize = new PIE.Observable();
435
PIE.OnUnload.attachManagedEvent( window, 'onresize', function() { PIE.OnResize.fire(); } );
437
* Create a single observable listener for scroll events. Used for lazy loading based
438
* on the viewport, and for fixed position backgrounds.
441
PIE.OnScroll = new PIE.Observable();
443
function scrolled() {
447
PIE.OnUnload.attachManagedEvent( window, 'onscroll', scrolled );
449
PIE.OnResize.observe( scrolled );
452
* Listen for printing events, destroy all active PIE instances when printing, and
453
* restore them afterward.
459
function beforePrint() {
460
elements = PIE.Element.destroyAll();
463
function afterPrint() {
465
for( var i = 0, len = elements.length; i < len; i++ ) {
466
PIE[ 'attach' ]( elements[i] );
472
if( PIE.ieDocMode < 9 ) {
473
PIE.OnUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint );
474
PIE.OnUnload.attachManagedEvent( window, 'onafterprint', afterPrint );
478
* Create a single observable listener for document mouseup events.
480
PIE.OnMouseup = new PIE.Observable();
482
PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } );
484
* Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique
485
* value is returned from PIE.getLength() - always use that instead of instantiating directly.
487
* @param {string} val The CSS string representing the length. It is assumed that this will already have
488
* been validated as a valid length or percentage syntax.
490
PIE.Length = (function() {
491
var lengthCalcEl = doc.createElement( 'length-calc' ),
492
parent = doc.body || doc.documentElement,
493
s = lengthCalcEl.style,
495
units = [ 'mm', 'cm', 'in', 'pt', 'pc' ],
499
s.position = 'absolute';
500
s.top = s.left = '-9999px';
502
parent.appendChild( lengthCalcEl );
504
s.width = '100' + units[i];
505
conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100;
507
parent.removeChild( lengthCalcEl );
509
// All calcs from here on will use 1em
513
function Length( val ) {
518
* Regular expression for matching the length unit
521
unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/,
524
* Get the numeric value of the length
525
* @return {number} The value
527
getNumber: function() {
530
if( num === UNDEF ) {
531
num = this.num = parseFloat( this.val );
537
* Get the unit of the length
538
* @return {string} The unit
540
getUnit: function() {
541
var unit = this.unit,
544
m = this.val.match( this.unitRE );
545
unit = this.unit = ( m && m[0] ) || 'px';
551
* Determine whether this is a percentage length value
554
isPercentage: function() {
555
return this.getUnit() === '%';
559
* Resolve this length into a number of pixels.
560
* @param {Element} el - the context element, used to resolve font-relative values
561
* @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a
562
* function which will be called to return the number.
564
pixels: function( el, pct100 ) {
565
var num = this.getNumber(),
566
unit = this.getUnit();
571
return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100;
573
return num * this.getEmPixels( el );
575
return num * this.getEmPixels( el ) / 2;
577
return num * conversions[ unit ];
582
* The em and ex units are relative to the font-size of the current element,
583
* however if the font-size is set using non-pixel units then we get that value
584
* rather than a pixel conversion. To get around this, we keep a floating element
585
* with width:1em which we insert into the target element and then read its offsetWidth.
586
* For elements that won't accept a child we insert into the parent node and perform
587
* additional calculation. If the font-size *is* specified in pixels, then we use that
588
* directly to avoid the expensive DOM manipulation.
589
* @param {Element} el
592
getEmPixels: function( el ) {
593
var fs = el.currentStyle.fontSize,
596
if( fs.indexOf( 'px' ) > 0 ) {
597
return parseFloat( fs );
599
else if( el.tagName in PIE.childlessElements ) {
601
parent = el.parentNode;
602
return PIE.getLength( fs ).pixels( parent, function() {
603
return me.getEmPixels( parent );
607
el.appendChild( lengthCalcEl );
608
px = lengthCalcEl.offsetWidth;
609
if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is
610
el.removeChild( lengthCalcEl );
619
* Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value.
620
* @param {string} val The CSS string representing the length. It is assumed that this will already have
621
* been validated as a valid length or percentage syntax.
623
PIE.getLength = function( val ) {
624
return instances[ val ] || ( instances[ val ] = new Length( val ) );
630
* Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages.
632
* @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value.
634
PIE.BgPosition = (function() {
636
var length_fifty = PIE.getLength( '50%' ),
637
vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 },
638
horiz_idents = { 'left': 1, 'center': 1, 'right': 1 };
641
function BgPosition( tokens ) {
642
this.tokens = tokens;
644
BgPosition.prototype = {
646
* Normalize the values into the form:
647
* [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ]
648
* where: xOffsetSide is either 'left' or 'right',
649
* yOffsetSide is either 'top' or 'bottom',
650
* and x/yOffsetLength are both PIE.Length objects.
653
getValues: function() {
654
if( !this._values ) {
655
var tokens = this.tokens,
657
Tokenizer = PIE.Tokenizer,
658
identType = Tokenizer.Type,
659
length_zero = PIE.getLength( '0' ),
660
type_ident = identType.IDENT,
661
type_length = identType.LENGTH,
662
type_percent = identType.PERCENT,
664
vals = [ 'left', length_zero, 'top', length_zero ];
666
// If only one value, the second is assumed to be 'center'
668
tokens.push( new Tokenizer.Token( type_ident, 'center' ) );
674
// If both idents, they can appear in either order, so switch them if needed
675
if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) &&
676
tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) {
677
tokens.push( tokens.shift() );
679
if( tokens[0].tokenType & type_ident ) {
680
if( tokens[0].tokenValue === 'center' ) {
681
vals[1] = length_fifty;
683
vals[0] = tokens[0].tokenValue;
686
else if( tokens[0].isLengthOrPercent() ) {
687
vals[1] = PIE.getLength( tokens[0].tokenValue );
689
if( tokens[1].tokenType & type_ident ) {
690
if( tokens[1].tokenValue === 'center' ) {
691
vals[3] = length_fifty;
693
vals[2] = tokens[1].tokenValue;
696
else if( tokens[1].isLengthOrPercent() ) {
697
vals[3] = PIE.getLength( tokens[1].tokenValue );
701
// Three or four values - CSS3
712
* Find the coordinates of the background image from the upper-left corner of the background area.
713
* Note that these coordinate values are not rounded.
714
* @param {Element} el
715
* @param {number} width - the width for percentages (background area width minus image width)
716
* @param {number} height - the height for percentages (background area height minus image height)
717
* @return {Object} { x: Number, y: Number }
719
coords: function( el, width, height ) {
720
var vals = this.getValues(),
721
pxX = vals[1].pixels( el, width ),
722
pxY = vals[3].pixels( el, height );
725
x: vals[0] === 'right' ? width - pxX : pxX,
726
y: vals[2] === 'bottom' ? height - pxY : pxY
734
* Wrapper for a CSS3 background-size value.
736
* @param {String|PIE.Length} w The width parameter
737
* @param {String|PIE.Length} h The height parameter, if any
739
PIE.BgSize = (function() {
741
var CONTAIN = 'contain',
746
function BgSize( w, h ) {
752
pixels: function( el, areaW, areaH, imgW, imgH ) {
756
areaRatio = areaW / areaH,
757
imgRatio = imgW / imgH;
759
if ( w === CONTAIN ) {
760
w = imgRatio > areaRatio ? areaW : areaH * imgRatio;
761
h = imgRatio > areaRatio ? areaW / imgRatio : areaH;
763
else if ( w === COVER ) {
764
w = imgRatio < areaRatio ? areaW : areaH * imgRatio;
765
h = imgRatio < areaRatio ? areaW / imgRatio : areaH;
767
else if ( w === AUTO ) {
768
h = ( h === AUTO ? imgH : h.pixels( el, areaH ) );
772
w = w.pixels( el, areaW );
773
h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) );
776
return { w: w, h: h };
781
BgSize.DEFAULT = new BgSize( AUTO, AUTO );
786
* Wrapper for angle values; handles conversion to degrees from all allowed angle units
788
* @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated.
790
PIE.Angle = (function() {
791
function Angle( val ) {
798
* @return {string} The unit of the angle value
800
getUnit: function() {
801
return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() );
805
* Get the numeric value of the angle in degrees.
806
* @return {number} The degrees value
808
degrees: function() {
809
var deg = this._deg, u, n;
810
if( deg === undefined ) {
812
n = parseFloat( this.val, 10 );
813
deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 );
821
* Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique
822
* value is returned from PIE.getColor() - always use that instead of instantiating directly.
824
* @param {string} val The raw CSS string value for the color
826
PIE.Color = (function() {
829
function Color( val ) {
834
* Regular expression for matching rgba colors and extracting their components
837
Color.rgbaRE = /\s*rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d+|\d*\.\d+)\s*\)\s*/;
840
"aliceblue":"F0F8FF", "antiquewhite":"FAEBD7", "aqua":"0FF",
841
"aquamarine":"7FFFD4", "azure":"F0FFFF", "beige":"F5F5DC",
842
"bisque":"FFE4C4", "black":"000", "blanchedalmond":"FFEBCD",
843
"blue":"00F", "blueviolet":"8A2BE2", "brown":"A52A2A",
844
"burlywood":"DEB887", "cadetblue":"5F9EA0", "chartreuse":"7FFF00",
845
"chocolate":"D2691E", "coral":"FF7F50", "cornflowerblue":"6495ED",
846
"cornsilk":"FFF8DC", "crimson":"DC143C", "cyan":"0FF",
847
"darkblue":"00008B", "darkcyan":"008B8B", "darkgoldenrod":"B8860B",
848
"darkgray":"A9A9A9", "darkgreen":"006400", "darkkhaki":"BDB76B",
849
"darkmagenta":"8B008B", "darkolivegreen":"556B2F", "darkorange":"FF8C00",
850
"darkorchid":"9932CC", "darkred":"8B0000", "darksalmon":"E9967A",
851
"darkseagreen":"8FBC8F", "darkslateblue":"483D8B", "darkslategray":"2F4F4F",
852
"darkturquoise":"00CED1", "darkviolet":"9400D3", "deeppink":"FF1493",
853
"deepskyblue":"00BFFF", "dimgray":"696969", "dodgerblue":"1E90FF",
854
"firebrick":"B22222", "floralwhite":"FFFAF0", "forestgreen":"228B22",
855
"fuchsia":"F0F", "gainsboro":"DCDCDC", "ghostwhite":"F8F8FF",
856
"gold":"FFD700", "goldenrod":"DAA520", "gray":"808080",
857
"green":"008000", "greenyellow":"ADFF2F", "honeydew":"F0FFF0",
858
"hotpink":"FF69B4", "indianred":"CD5C5C", "indigo":"4B0082",
859
"ivory":"FFFFF0", "khaki":"F0E68C", "lavender":"E6E6FA",
860
"lavenderblush":"FFF0F5", "lawngreen":"7CFC00", "lemonchiffon":"FFFACD",
861
"lightblue":"ADD8E6", "lightcoral":"F08080", "lightcyan":"E0FFFF",
862
"lightgoldenrodyellow":"FAFAD2", "lightgreen":"90EE90", "lightgrey":"D3D3D3",
863
"lightpink":"FFB6C1", "lightsalmon":"FFA07A", "lightseagreen":"20B2AA",
864
"lightskyblue":"87CEFA", "lightslategray":"789", "lightsteelblue":"B0C4DE",
865
"lightyellow":"FFFFE0", "lime":"0F0", "limegreen":"32CD32",
866
"linen":"FAF0E6", "magenta":"F0F", "maroon":"800000",
867
"mediumauqamarine":"66CDAA", "mediumblue":"0000CD", "mediumorchid":"BA55D3",
868
"mediumpurple":"9370D8", "mediumseagreen":"3CB371", "mediumslateblue":"7B68EE",
869
"mediumspringgreen":"00FA9A", "mediumturquoise":"48D1CC", "mediumvioletred":"C71585",
870
"midnightblue":"191970", "mintcream":"F5FFFA", "mistyrose":"FFE4E1",
871
"moccasin":"FFE4B5", "navajowhite":"FFDEAD", "navy":"000080",
872
"oldlace":"FDF5E6", "olive":"808000", "olivedrab":"688E23",
873
"orange":"FFA500", "orangered":"FF4500", "orchid":"DA70D6",
874
"palegoldenrod":"EEE8AA", "palegreen":"98FB98", "paleturquoise":"AFEEEE",
875
"palevioletred":"D87093", "papayawhip":"FFEFD5", "peachpuff":"FFDAB9",
876
"peru":"CD853F", "pink":"FFC0CB", "plum":"DDA0DD",
877
"powderblue":"B0E0E6", "purple":"800080", "red":"F00",
878
"rosybrown":"BC8F8F", "royalblue":"4169E1", "saddlebrown":"8B4513",
879
"salmon":"FA8072", "sandybrown":"F4A460", "seagreen":"2E8B57",
880
"seashell":"FFF5EE", "sienna":"A0522D", "silver":"C0C0C0",
881
"skyblue":"87CEEB", "slateblue":"6A5ACD", "slategray":"708090",
882
"snow":"FFFAFA", "springgreen":"00FF7F", "steelblue":"4682B4",
883
"tan":"D2B48C", "teal":"008080", "thistle":"D8BFD8",
884
"tomato":"FF6347", "turquoise":"40E0D0", "violet":"EE82EE",
885
"wheat":"F5DEB3", "white":"FFF", "whitesmoke":"F5F5F5",
886
"yellow":"FF0", "yellowgreen":"9ACD32"
898
m = v.match( Color.rgbaRE );
900
me._color = 'rgb(' + m[1] + ',' + m[2] + ',' + m[3] + ')';
901
me._alpha = parseFloat( m[4] );
904
if( ( vLower = v.toLowerCase() ) in Color.names ) {
905
v = '#' + Color.names[vLower];
908
me._alpha = ( v === 'transparent' ? 0 : 1 );
914
* Retrieve the value of the color in a format usable by IE natively. This will be the same as
915
* the raw input value, except for rgba values which will be converted to an rgb value.
916
* @param {Element} el The context element, used to get 'currentColor' keyword value.
917
* @return {string} Color value
919
colorValue: function( el ) {
921
return this._color === 'currentColor' ? el.currentStyle.color : this._color;
925
* Retrieve the alpha value of the color. Will be 1 for all values except for rgba values
926
* with an alpha component.
927
* @return {number} The alpha value, from 0 to 1.
937
* Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value.
938
* @param {string} val The CSS string representing the color. It is assumed that this will already have
939
* been validated as a valid color syntax.
941
PIE.getColor = function(val) {
942
return instances[ val ] || ( instances[ val ] = new Color( val ) );
947
* A tokenizer for CSS value strings.
949
* @param {string} css The CSS value string
951
PIE.Tokenizer = (function() {
952
function Tokenizer( css ) {
960
* Enumeration of token type constants.
963
var Type = Tokenizer.Type = {
981
* @param {number} type The type of the token - see PIE.Tokenizer.Type
982
* @param {string} value The value of the token
984
Tokenizer.Token = function( type, value ) {
985
this.tokenType = type;
986
this.tokenValue = value;
988
Tokenizer.Token.prototype = {
989
isLength: function() {
990
return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' );
992
isLengthOrPercent: function() {
993
return this.isLength() || this.tokenType & Type.PERCENT;
997
Tokenizer.prototype = {
999
number: /^[\+\-]?(\d*\.)?\d+/,
1000
url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i,
1001
ident: /^\-?[_a-z][\w-]*/i,
1002
string: /^("([^"]*)"|'([^']*)')/,
1005
hashColor: /^#([\da-f]{6}|[\da-f]{3})/i,
1008
'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH,
1009
'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH,
1010
'pt': Type.LENGTH, 'pc': Type.LENGTH,
1011
'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE
1015
'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1
1020
* Advance to and return the next token in the CSS string. If the end of the CSS string has
1021
* been reached, null will be returned.
1022
* @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev().
1023
* @return {PIE.Tokenizer.Token}
1025
next: function( forget ) {
1026
var css, ch, firstChar, match, val,
1029
function newToken( type, value ) {
1030
var tok = new Tokenizer.Token( type, value );
1032
me.tokens.push( tok );
1037
function failure() {
1042
// In case we previously backed up, return the stored token in the next slot
1043
if( this.tokenIndex < this.tokens.length ) {
1044
return this.tokens[ this.tokenIndex++ ];
1047
// Move past leading whitespace characters
1048
while( this.whitespace.test( this.css.charAt( this.ch ) ) ) {
1051
if( this.ch >= this.css.length ) {
1056
css = this.css.substring( this.ch );
1057
firstChar = css.charAt( 0 );
1058
switch( firstChar ) {
1060
if( match = css.match( this.hashColor ) ) {
1061
this.ch += match[0].length;
1062
return newToken( Type.COLOR, match[0] );
1068
if( match = css.match( this.string ) ) {
1069
this.ch += match[0].length;
1070
return newToken( Type.STRING, match[2] || match[3] || '' );
1077
return newToken( Type.OPERATOR, firstChar );
1080
if( match = css.match( this.url ) ) {
1081
this.ch += match[0].length;
1082
return newToken( Type.URL, match[2] || match[3] || match[4] || '' );
1086
// Numbers and values starting with numbers
1087
if( match = css.match( this.number ) ) {
1089
this.ch += val.length;
1091
// Check if it is followed by a unit
1092
if( css.charAt( val.length ) === '%' ) {
1094
return newToken( Type.PERCENT, val + '%' );
1096
if( match = css.substring( val.length ).match( this.ident ) ) {
1098
this.ch += match[0].length;
1099
return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val );
1103
return newToken( Type.NUMBER, val );
1107
if( match = css.match( this.ident ) ) {
1109
this.ch += val.length;
1112
if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) {
1113
return newToken( Type.COLOR, val );
1117
if( css.charAt( val.length ) === '(' ) {
1120
// Color values in function format: rgb, rgba, hsl, hsla
1121
if( val.toLowerCase() in this.colorFunctions ) {
1122
function isNum( tok ) {
1123
return tok && tok.tokenType & Type.NUMBER;
1125
function isNumOrPct( tok ) {
1126
return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) );
1128
function isValue( tok, val ) {
1129
return tok && tok.tokenValue === val;
1132
return me.next( 1 );
1135
if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) &&
1136
isValue( next(), ',' ) &&
1137
isNumOrPct( next() ) &&
1138
isValue( next(), ',' ) &&
1139
isNumOrPct( next() ) &&
1140
( val === 'rgb' || val === 'hsa' || (
1141
isValue( next(), ',' ) &&
1144
isValue( next(), ')' ) ) {
1145
return newToken( Type.COLOR, this.css.substring( ch, this.ch ) );
1150
return newToken( Type.FUNCTION, val );
1154
return newToken( Type.IDENT, val );
1157
// Standalone character
1159
return newToken( Type.CHARACTER, firstChar );
1163
* Determine whether there is another token
1166
hasNext: function() {
1167
var next = this.next();
1173
* Back up and return the previous token
1174
* @return {PIE.Tokenizer.Token}
1177
return this.tokens[ this.tokenIndex-- - 2 ];
1181
* Retrieve all the tokens in the CSS string
1182
* @return {Array.<PIE.Tokenizer.Token>}
1185
while( this.next() ) {}
1190
* Return a list of tokens from the current position until the given function returns
1191
* true. The final token will not be included in the list.
1192
* @param {function():boolean} func - test function
1193
* @param {boolean} require - if true, then if the end of the CSS string is reached
1194
* before the test function returns true, null will be returned instead of the
1195
* tokens that have been found so far.
1196
* @return {Array.<PIE.Tokenizer.Token>}
1198
until: function( func, require ) {
1199
var list = [], t, hit;
1200
while( t = this.next() ) {
1208
return require && !hit ? null : list;
1214
* Handles calculating, caching, and detecting changes to size and position of the element.
1216
* @param {Element} el the target element
1218
PIE.BoundsInfo = function( el ) {
1219
this.targetElement = el;
1221
PIE.BoundsInfo.prototype = {
1225
positionChanged: function() {
1226
var last = this._lastBounds,
1228
return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) );
1231
sizeChanged: function() {
1232
var last = this._lastBounds,
1234
return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) );
1237
getLiveBounds: function() {
1238
var el = this.targetElement,
1239
rect = el.getBoundingClientRect(),
1240
isIE9 = PIE.ieDocMode === 9,
1241
isIE7 = PIE.ieVersion === 7,
1242
width = rect.right - rect.left;
1246
// In some cases scrolling the page will cause IE9 to report incorrect dimensions
1247
// in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height
1248
// instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements
1249
// so we must calculate the ratio and use it in certain places as a position adjustment.
1250
w: isIE9 || isIE7 ? el.offsetWidth : width,
1251
h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top,
1252
logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1
1256
getBounds: function() {
1257
return this._locked ?
1258
( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) :
1259
this.getLiveBounds();
1262
hasBeenQueried: function() {
1263
return !!this._lastBounds;
1270
unlock: function() {
1271
if( !--this._locked ) {
1272
if( this._lockedBounds ) this._lastBounds = this._lockedBounds;
1273
this._lockedBounds = null;
1280
function cacheWhenLocked( fn ) {
1281
var uid = PIE.Util.getUID( fn );
1283
if( this._locked ) {
1284
var cache = this._lockedValues || ( this._lockedValues = {} );
1285
return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) );
1287
return fn.call( this );
1293
PIE.StyleInfoBase = {
1298
* Create a new StyleInfo class, with the standard constructor, and augmented by
1299
* the StyleInfoBase's members.
1302
newStyleInfo: function( proto ) {
1303
function StyleInfo( el ) {
1304
this.targetElement = el;
1305
this._lastCss = this.getCss();
1307
PIE.Util.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto );
1308
StyleInfo._propsCache = {};
1313
* Get an object representation of the target CSS style, caching it for each unique
1317
getProps: function() {
1318
var css = this.getCss(),
1319
cache = this.constructor._propsCache;
1320
return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null;
1324
* Get the raw CSS value for the target style
1327
getCss: cacheWhenLocked( function() {
1328
var el = this.targetElement,
1329
ctor = this.constructor,
1331
cs = el.currentStyle,
1332
cssProp = this.cssProperty,
1333
styleProp = this.styleProperty,
1334
prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ),
1335
prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) );
1336
return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp );
1340
* Determine whether the target CSS style is active.
1343
isActive: cacheWhenLocked( function() {
1344
return !!this.getProps();
1348
* Determine whether the target CSS style has changed since the last time it was used.
1351
changed: cacheWhenLocked( function() {
1352
var currentCss = this.getCss(),
1353
changed = currentCss !== this._lastCss;
1354
this._lastCss = currentCss;
1358
cacheWhenLocked: cacheWhenLocked,
1364
unlock: function() {
1365
if( !--this._locked ) {
1366
delete this._lockedValues;
1372
* Handles parsing, caching, and detecting changes to background (and -pie-background) CSS
1374
* @param {Element} el the target element
1376
PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1378
cssProperty: PIE.CSS_PREFIX + 'background',
1379
styleProperty: PIE.STYLE_PREFIX + 'Background',
1381
attachIdents: { 'scroll':1, 'fixed':1, 'local':1 },
1382
repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 },
1383
originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 },
1384
positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 },
1385
sizeIdents: { 'contain':1, 'cover':1 },
1387
CLIP: 'backgroundClip',
1388
COLOR: 'backgroundColor',
1389
IMAGE: 'backgroundImage',
1390
ORIGIN: 'backgroundOrigin',
1391
POSITION: 'backgroundPosition',
1392
REPEAT: 'backgroundRepeat',
1393
SIZE: 'backgroundSize'
1397
* For background styles, we support the -pie-background property but fall back to the standard
1398
* backround* properties. The reason we have to use the prefixed version is that IE natively
1399
* parses the standard properties and if it sees something it doesn't know how to parse, for example
1400
* multiple values or gradient definitions, it will throw that away and not make it available through
1403
* Format of return object:
1405
* color: <PIE.Color>,
1409
* imgUrl: 'image.png',
1410
* imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>,
1411
* bgPosition: <PIE.BgPosition>,
1412
* bgAttachment: <'scroll' | 'fixed' | 'local'>,
1413
* bgOrigin: <'border-box' | 'padding-box' | 'content-box'>,
1414
* bgClip: <'border-box' | 'padding-box'>,
1415
* bgSize: <PIE.BgSize>,
1416
* origString: 'url(img.png) no-repeat top left'
1419
* imgType: 'linear-gradient',
1420
* gradientStart: <PIE.BgPosition>,
1421
* angle: <PIE.Angle>,
1423
* { color: <PIE.Color>, offset: <PIE.Length> },
1424
* { color: <PIE.Color>, offset: <PIE.Length> }, ...
1429
* @param {String} css
1432
parseCss: function( css ) {
1433
var el = this.targetElement,
1434
cs = el.currentStyle,
1435
tokenizer, token, image,
1436
tok_type = PIE.Tokenizer.Type,
1437
type_operator = tok_type.OPERATOR,
1438
type_ident = tok_type.IDENT,
1439
type_color = tok_type.COLOR,
1442
positionIdents = this.positionIdents,
1443
gradient, stop, width, height,
1444
props = { bgImages: [] };
1446
function isBgPosToken( token ) {
1447
return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents );
1450
function sizeToken( token ) {
1451
return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) );
1454
// If the CSS3-specific -pie-background property is present, parse it
1455
if( this.getCss3() ) {
1456
tokenizer = new PIE.Tokenizer( css );
1459
while( token = tokenizer.next() ) {
1460
tokType = token.tokenType;
1461
tokVal = token.tokenValue;
1463
if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) {
1464
gradient = { stops: [], imgType: tokVal };
1466
while( token = tokenizer.next() ) {
1467
tokType = token.tokenType;
1468
tokVal = token.tokenValue;
1470
// If we reached the end of the function and had at least 2 stops, flush the info
1471
if( tokType & tok_type.CHARACTER && tokVal === ')' ) {
1473
gradient.stops.push( stop );
1475
if( gradient.stops.length > 1 ) {
1476
PIE.Util.merge( image, gradient );
1481
// Color stop - must start with color
1482
if( tokType & type_color ) {
1483
// if we already have an angle/position, make sure that the previous token was a comma
1484
if( gradient.angle || gradient.gradientStart ) {
1485
token = tokenizer.prev();
1486
if( token.tokenType !== type_operator ) {
1493
color: PIE.getColor( tokVal )
1495
// check for offset following color
1496
token = tokenizer.next();
1497
if( token.isLengthOrPercent() ) {
1498
stop.offset = PIE.getLength( token.tokenValue );
1503
// Angle - can only appear in first spot
1504
else if( tokType & tok_type.ANGLE && !gradient.angle && !stop.color && !gradient.stops.length ) {
1505
gradient.angle = new PIE.Angle( token.tokenValue );
1507
else if( isBgPosToken( token ) && !gradient.gradientStart && !stop.color && !gradient.stops.length ) {
1509
gradient.gradientStart = new PIE.BgPosition(
1510
tokenizer.until( function( t ) {
1511
return !isBgPosToken( t );
1515
else if( tokType & type_operator && tokVal === ',' ) {
1517
gradient.stops.push( stop );
1522
// Found something we didn't recognize; fail without adding image
1527
else if( !image.imgType && tokType & tok_type.URL ) {
1528
image.imgUrl = tokVal;
1529
image.imgType = 'image';
1531
else if( isBgPosToken( token ) && !image.bgPosition ) {
1533
image.bgPosition = new PIE.BgPosition(
1534
tokenizer.until( function( t ) {
1535
return !isBgPosToken( t );
1539
else if( tokType & type_ident ) {
1540
if( tokVal in this.repeatIdents && !image.imgRepeat ) {
1541
image.imgRepeat = tokVal;
1543
else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) {
1544
image.bgOrigin = tokVal;
1545
if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) &&
1546
token.tokenValue in this.originAndClipIdents ) {
1547
image.bgClip = token.tokenValue;
1549
image.bgClip = tokVal;
1553
else if( tokVal in this.attachIdents && !image.bgAttachment ) {
1554
image.bgAttachment = tokVal;
1560
else if( tokType & type_color && !props.color ) {
1561
props.color = PIE.getColor( tokVal );
1563
else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) {
1565
token = tokenizer.next();
1566
if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) {
1567
image.bgSize = new PIE.BgSize( token.tokenValue );
1569
else if( width = sizeToken( token ) ) {
1570
height = sizeToken( tokenizer.next() );
1575
image.bgSize = new PIE.BgSize( width, height );
1582
else if( tokType & type_operator && tokVal === ',' && image.imgType ) {
1583
image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 );
1584
beginCharIndex = tokenizer.ch;
1585
props.bgImages.push( image );
1589
// Found something unrecognized; chuck everything
1595
if( image.imgType ) {
1596
image.origString = css.substring( beginCharIndex );
1597
props.bgImages.push( image );
1601
// Otherwise, use the standard background properties; let IE give us the values rather than parsing them
1603
this.withActualBg( PIE.ieDocMode < 9 ?
1605
var propNames = this.propertyNames,
1606
posX = cs[propNames.POSITION + 'X'],
1607
posY = cs[propNames.POSITION + 'Y'],
1608
img = cs[propNames.IMAGE],
1609
color = cs[propNames.COLOR];
1611
if( color !== 'transparent' ) {
1612
props.color = PIE.getColor( color )
1614
if( img !== 'none' ) {
1615
props.bgImages = [ {
1617
imgUrl: new PIE.Tokenizer( img ).next().tokenValue,
1618
imgRepeat: cs[propNames.REPEAT],
1619
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() )
1624
var propNames = this.propertyNames,
1625
splitter = /\s*,\s*/,
1626
images = cs[propNames.IMAGE].split( splitter ),
1627
color = cs[propNames.COLOR],
1628
repeats, positions, origins, clips, sizes, i, len, image, sizeParts;
1630
if( color !== 'transparent' ) {
1631
props.color = PIE.getColor( color )
1634
len = images.length;
1635
if( len && images[0] !== 'none' ) {
1636
repeats = cs[propNames.REPEAT].split( splitter );
1637
positions = cs[propNames.POSITION].split( splitter );
1638
origins = cs[propNames.ORIGIN].split( splitter );
1639
clips = cs[propNames.CLIP].split( splitter );
1640
sizes = cs[propNames.SIZE].split( splitter );
1642
props.bgImages = [];
1643
for( i = 0; i < len; i++ ) {
1644
image = images[ i ];
1645
if( image && image !== 'none' ) {
1646
sizeParts = sizes[i].split( ' ' );
1647
props.bgImages.push( {
1648
origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' +
1649
origins[ i ] + ' ' + clips[ i ],
1651
imgUrl: new PIE.Tokenizer( image ).next().tokenValue,
1652
imgRepeat: repeats[ i ],
1653
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ),
1654
bgOrigin: origins[ i ],
1656
bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] )
1665
return ( props.color || props.bgImages[0] ) ? props : null;
1669
* Execute a function with the actual background styles (not overridden with runtimeStyle
1670
* properties set by the renderers) available via currentStyle.
1673
withActualBg: function( fn ) {
1674
var isIE9 = PIE.ieDocMode > 8,
1675
propNames = this.propertyNames,
1676
rs = this.targetElement.runtimeStyle,
1677
rsImage = rs[propNames.IMAGE],
1678
rsColor = rs[propNames.COLOR],
1679
rsRepeat = rs[propNames.REPEAT],
1680
rsClip, rsOrigin, rsSize, rsPosition, ret;
1682
if( rsImage ) rs[propNames.IMAGE] = '';
1683
if( rsColor ) rs[propNames.COLOR] = '';
1684
if( rsRepeat ) rs[propNames.REPEAT] = '';
1686
rsClip = rs[propNames.CLIP];
1687
rsOrigin = rs[propNames.ORIGIN];
1688
rsPosition = rs[propNames.POSITION];
1689
rsSize = rs[propNames.SIZE];
1690
if( rsClip ) rs[propNames.CLIP] = '';
1691
if( rsOrigin ) rs[propNames.ORIGIN] = '';
1692
if( rsPosition ) rs[propNames.POSITION] = '';
1693
if( rsSize ) rs[propNames.SIZE] = '';
1696
ret = fn.call( this );
1698
if( rsImage ) rs[propNames.IMAGE] = rsImage;
1699
if( rsColor ) rs[propNames.COLOR] = rsColor;
1700
if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat;
1702
if( rsClip ) rs[propNames.CLIP] = rsClip;
1703
if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin;
1704
if( rsPosition ) rs[propNames.POSITION] = rsPosition;
1705
if( rsSize ) rs[propNames.SIZE] = rsSize;
1711
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
1712
return this.getCss3() ||
1713
this.withActualBg( function() {
1714
var cs = this.targetElement.currentStyle,
1715
propNames = this.propertyNames;
1716
return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' +
1717
cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y'];
1721
getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() {
1722
var el = this.targetElement;
1723
return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty );
1727
* Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6.
1729
isPngFix: function() {
1731
if( PIE.ieVersion < 7 ) {
1732
el = this.targetElement;
1733
val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' );
1739
* The isActive logic is slightly different, because getProps() always returns an object
1740
* even if it is just falling back to the native background properties. But we only want
1741
* to report is as being "active" if either the -pie-background override property is present
1742
* and parses successfully or '-pie-png-fix' is set to true in IE6.
1744
isActive: PIE.StyleInfoBase.cacheWhenLocked( function() {
1745
return (this.getCss3() || this.isPngFix()) && !!this.getProps();
1749
* Handles parsing, caching, and detecting changes to border CSS
1751
* @param {Element} el the target element
1753
PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1755
sides: [ 'Top', 'Right', 'Bottom', 'Left' ],
1762
parseCss: function( css ) {
1771
this.withActualBorder( function() {
1772
var el = this.targetElement,
1773
cs = el.currentStyle,
1775
style, color, width, lastStyle, lastColor, lastWidth, side, ltr;
1776
for( ; i < 4; i++ ) {
1777
side = this.sides[ i ];
1779
ltr = side.charAt(0).toLowerCase();
1780
style = s[ ltr ] = cs[ 'border' + side + 'Style' ];
1781
color = cs[ 'border' + side + 'Color' ];
1782
width = cs[ 'border' + side + 'Width' ];
1785
if( style !== lastStyle ) { stylesSame = false; }
1786
if( color !== lastColor ) { colorsSame = false; }
1787
if( width !== lastWidth ) { widthsSame = false; }
1793
c[ ltr ] = PIE.getColor( color );
1795
width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) );
1796
if( width.pixels( this.targetElement ) > 0 ) {
1806
widthsSame: widthsSame,
1807
colorsSame: colorsSame,
1808
stylesSame: stylesSame
1812
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
1813
var el = this.targetElement,
1814
cs = el.currentStyle,
1817
// Don't redraw or hide borders for cells in border-collapse:collapse tables
1818
if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) {
1819
this.withActualBorder( function() {
1820
css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor;
1827
* Execute a function with the actual border styles (not overridden with runtimeStyle
1828
* properties set by the renderers) available via currentStyle.
1831
withActualBorder: function( fn ) {
1832
var rs = this.targetElement.runtimeStyle,
1833
rsWidth = rs.borderWidth,
1834
rsColor = rs.borderColor,
1837
if( rsWidth ) rs.borderWidth = '';
1838
if( rsColor ) rs.borderColor = '';
1840
ret = fn.call( this );
1842
if( rsWidth ) rs.borderWidth = rsWidth;
1843
if( rsColor ) rs.borderColor = rsColor;
1850
* Handles parsing, caching, and detecting changes to border-radius CSS
1852
* @param {Element} el the target element
1856
PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1858
cssProperty: 'border-radius',
1859
styleProperty: 'borderRadius',
1861
parseCss: function( css ) {
1863
tokenizer, token, length,
1867
tokenizer = new PIE.Tokenizer( css );
1869
function collectLengths() {
1871
while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
1872
length = PIE.getLength( token.tokenValue );
1873
num = length.getNumber();
1882
return arr.length > 0 && arr.length < 5 ? {
1884
'tr': arr[1] || arr[0],
1885
'br': arr[2] || arr[0],
1886
'bl': arr[3] || arr[1] || arr[0]
1890
// Grab the initial sequence of lengths
1891
if( x = collectLengths() ) {
1892
// See if there is a slash followed by more lengths, for the y-axis radii
1894
if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) {
1895
y = collectLengths();
1901
// Treat all-zero values the same as no value
1902
if( hasNonZero && x && y ) {
1903
p = { x: x, y : y };
1912
var zero = PIE.getLength( '0' ),
1913
zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero };
1914
PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros };
1917
* Handles parsing, caching, and detecting changes to border-image CSS
1919
* @param {Element} el the target element
1921
PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1923
cssProperty: 'border-image',
1924
styleProperty: 'borderImage',
1926
repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 },
1928
parseCss: function( css ) {
1929
var p = null, tokenizer, token, type, value,
1930
slices, widths, outsets,
1932
Type = PIE.Tokenizer.Type,
1934
NUMBER = Type.NUMBER,
1935
PERCENT = Type.PERCENT;
1938
tokenizer = new PIE.Tokenizer( css );
1941
function isSlash( token ) {
1942
return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' );
1945
function isFillIdent( token ) {
1946
return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' );
1949
function collectSlicesEtc() {
1950
slices = tokenizer.until( function( tok ) {
1951
return !( tok.tokenType & ( NUMBER | PERCENT ) );
1954
if( isFillIdent( tokenizer.next() ) && !p.fill ) {
1960
if( isSlash( tokenizer.next() ) ) {
1962
widths = tokenizer.until( function( token ) {
1963
return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' );
1966
if( isSlash( tokenizer.next() ) ) {
1968
outsets = tokenizer.until( function( token ) {
1969
return !token.isLength();
1977
while( token = tokenizer.next() ) {
1978
type = token.tokenType;
1979
value = token.tokenValue;
1981
// Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values
1982
if( type & ( NUMBER | PERCENT ) && !slices ) {
1986
else if( isFillIdent( token ) && !p.fill ) {
1991
// Idents: one or values for 'repeat'
1992
else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) {
1993
p.repeat = { h: value };
1994
if( token = tokenizer.next() ) {
1995
if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) {
1996
p.repeat.v = token.tokenValue;
2004
else if( ( type & Type.URL ) && !p.src ) {
2008
// Found something unrecognized; exit.
2014
// Validate what we collected
2015
if( !p.src || !slices || slices.length < 1 || slices.length > 4 ||
2016
( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) ||
2017
( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) {
2021
// Fill in missing values
2023
p.repeat = { h: 'stretch' };
2026
p.repeat.v = p.repeat.h;
2029
function distributeSides( tokens, convertFn ) {
2031
't': convertFn( tokens[0] ),
2032
'r': convertFn( tokens[1] || tokens[0] ),
2033
'b': convertFn( tokens[2] || tokens[0] ),
2034
'l': convertFn( tokens[3] || tokens[1] || tokens[0] )
2038
p.slice = distributeSides( slices, function( tok ) {
2039
return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue );
2042
if( widths && widths[0] ) {
2043
p.widths = distributeSides( widths, function( tok ) {
2044
return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
2048
if( outsets && outsets[0] ) {
2049
p.outset = distributeSides( outsets, function( tok ) {
2050
return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
2059
* Handles parsing, caching, and detecting changes to box-shadow CSS
2061
* @param {Element} el the target element
2063
PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
2065
cssProperty: 'box-shadow',
2066
styleProperty: 'boxShadow',
2068
parseCss: function( css ) {
2070
getLength = PIE.getLength,
2071
Type = PIE.Tokenizer.Type,
2075
tokenizer = new PIE.Tokenizer( css );
2076
props = { outset: [], inset: [] };
2078
function parseItem() {
2079
var token, type, value, color, lengths, inset, len;
2081
while( token = tokenizer.next() ) {
2082
value = token.tokenValue;
2083
type = token.tokenType;
2085
if( type & Type.OPERATOR && value === ',' ) {
2088
else if( token.isLength() && !lengths ) {
2090
lengths = tokenizer.until( function( token ) {
2091
return !token.isLength();
2094
else if( type & Type.COLOR && !color ) {
2097
else if( type & Type.IDENT && value === 'inset' && !inset ) {
2100
else { //encountered an unrecognized token; fail.
2105
len = lengths && lengths.length;
2106
if( len > 1 && len < 5 ) {
2107
( inset ? props.inset : props.outset ).push( {
2108
xOffset: getLength( lengths[0].tokenValue ),
2109
yOffset: getLength( lengths[1].tokenValue ),
2110
blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ),
2111
spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ),
2112
color: PIE.getColor( color || 'currentColor' )
2119
while( parseItem() ) {}
2122
return props && ( props.inset.length || props.outset.length ) ? props : null;
2126
* Retrieves the state of the element's visibility and display
2128
* @param {Element} el the target element
2130
PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
2132
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
2133
var cs = this.targetElement.currentStyle;
2134
return cs.visibility + '|' + cs.display;
2137
parseCss: function() {
2138
var el = this.targetElement,
2139
rs = el.runtimeStyle,
2140
cs = el.currentStyle,
2141
rsVis = rs.visibility,
2145
csVis = cs.visibility;
2146
rs.visibility = rsVis;
2149
visible: csVis !== 'hidden',
2150
displayed: cs.display !== 'none'
2155
* Always return false for isActive, since this property alone will not trigger
2156
* a renderer to do anything.
2158
isActive: function() {
2163
PIE.RendererBase = {
2166
* Create a new Renderer class, with the standard constructor, and augmented by
2167
* the RendererBase's members.
2170
newRenderer: function( proto ) {
2171
function Renderer( el, boundsInfo, styleInfos, parent ) {
2172
this.targetElement = el;
2173
this.boundsInfo = boundsInfo;
2174
this.styleInfos = styleInfos;
2175
this.parent = parent;
2177
PIE.Util.merge( Renderer.prototype, PIE.RendererBase, proto );
2182
* Flag indicating the element has already been positioned at least once.
2185
isPositioned: false,
2188
* Determine if the renderer needs to be updated
2191
needsUpdate: function() {
2196
* Run any preparation logic that would affect the main update logic of this
2197
* renderer or any of the other renderers, e.g. things that might affect the
2198
* element's size or style properties.
2200
prepareUpdate: PIE.emptyFn,
2203
* Tell the renderer to update based on modified properties
2205
updateProps: function() {
2207
if( this.isActive() ) {
2213
* Tell the renderer to update based on modified element position
2215
updatePos: function() {
2216
this.isPositioned = true;
2220
* Tell the renderer to update based on modified element dimensions
2222
updateSize: function() {
2223
if( this.isActive() ) {
2232
* Add a layer element, with the given z-order index, to the renderer's main box element. We can't use
2233
* z-index because that breaks when the root rendering box's z-index is 'auto' in IE8+ standards mode.
2234
* So instead we make sure they are inserted into the DOM in the correct order.
2235
* @param {number} index
2236
* @param {Element} el
2238
addLayer: function( index, el ) {
2239
this.removeLayer( index );
2240
for( var layers = this._layers || ( this._layers = [] ), i = index + 1, len = layers.length, layer; i < len; i++ ) {
2247
this.getBox().insertBefore( el, layer || null );
2251
* Retrieve a layer element by its index, or null if not present
2252
* @param {number} index
2255
getLayer: function( index ) {
2256
var layers = this._layers;
2257
return layers && layers[index] || null;
2261
* Remove a layer element by its index
2262
* @param {number} index
2264
removeLayer: function( index ) {
2265
var layer = this.getLayer( index ),
2267
if( layer && box ) {
2268
box.removeChild( layer );
2269
this._layers[index] = null;
2275
* Get a VML shape by name, creating it if necessary.
2276
* @param {string} name A name identifying the element
2277
* @param {string=} subElName If specified a subelement of the shape will be created with this tag name
2278
* @param {Element} parent The parent element for the shape; will be ignored if 'group' is specified
2279
* @param {number=} group If specified, an ordinal group for the shape. 1 or greater. Groups are rendered
2280
* using container elements in the correct order, to get correct z stacking without z-index.
2282
getShape: function( name, subElName, parent, group ) {
2283
var shapes = this._shapes || ( this._shapes = {} ),
2284
shape = shapes[ name ],
2288
shape = shapes[ name ] = PIE.Util.createVmlElement( 'shape' );
2290
shape.appendChild( shape[ subElName ] = PIE.Util.createVmlElement( subElName ) );
2294
parent = this.getLayer( group );
2296
this.addLayer( group, doc.createElement( 'group' + group ) );
2297
parent = this.getLayer( group );
2301
parent.appendChild( shape );
2304
s.position = 'absolute';
2306
s['behavior'] = 'url(#default#VML)';
2312
* Delete a named shape which was created by getShape(). Returns true if a shape with the
2313
* given name was found and deleted, or false if there was no shape of that name.
2314
* @param {string} name
2317
deleteShape: function( name ) {
2318
var shapes = this._shapes,
2319
shape = shapes && shapes[ name ];
2321
shape.parentNode.removeChild( shape );
2322
delete shapes[ name ];
2329
* For a given set of border radius length/percentage values, convert them to concrete pixel
2330
* values based on the current size of the target element.
2331
* @param {Object} radii
2334
getRadiiPixels: function( radii ) {
2335
var el = this.targetElement,
2336
bounds = this.boundsInfo.getBounds(),
2339
tlX, tlY, trX, trY, brX, brY, blX, blY, f;
2341
tlX = radii.x['tl'].pixels( el, w );
2342
tlY = radii.y['tl'].pixels( el, h );
2343
trX = radii.x['tr'].pixels( el, w );
2344
trY = radii.y['tr'].pixels( el, h );
2345
brX = radii.x['br'].pixels( el, w );
2346
brY = radii.y['br'].pixels( el, h );
2347
blX = radii.x['bl'].pixels( el, w );
2348
blY = radii.y['bl'].pixels( el, h );
2350
// If any corner ellipses overlap, reduce them all by the appropriate factor. This formula
2351
// is taken straight from the CSS3 Backgrounds and Borders spec.
2386
* Return the VML path string for the element's background box, with corners rounded.
2387
* @param {Object.<{t:number, r:number, b:number, l:number}>} shrink - if present, specifies number of
2388
* pixels to shrink the box path inward from the element's four sides.
2389
* @param {number=} mult If specified, all coordinates will be multiplied by this number
2390
* @param {Object=} radii If specified, this will be used for the corner radii instead of the properties
2391
* from this renderer's borderRadiusInfo object.
2392
* @return {string} the VML path
2394
getBoxPath: function( shrink, mult, radii ) {
2398
bounds = this.boundsInfo.getBounds(),
2399
w = bounds.w * mult,
2400
h = bounds.h * mult,
2401
radInfo = this.styleInfos.borderRadiusInfo,
2402
floor = Math.floor, ceil = Math.ceil,
2403
shrinkT = shrink ? shrink.t * mult : 0,
2404
shrinkR = shrink ? shrink.r * mult : 0,
2405
shrinkB = shrink ? shrink.b * mult : 0,
2406
shrinkL = shrink ? shrink.l * mult : 0,
2407
tlX, tlY, trX, trY, brX, brY, blX, blY;
2409
if( radii || radInfo.isActive() ) {
2410
r = this.getRadiiPixels( radii || radInfo.getProps() );
2412
tlX = r.x['tl'] * mult;
2413
tlY = r.y['tl'] * mult;
2414
trX = r.x['tr'] * mult;
2415
trY = r.y['tr'] * mult;
2416
brX = r.x['br'] * mult;
2417
brY = r.y['br'] * mult;
2418
blX = r.x['bl'] * mult;
2419
blY = r.y['bl'] * mult;
2421
str = 'm' + floor( shrinkL ) + ',' + floor( tlY ) +
2422
'qy' + floor( tlX ) + ',' + floor( shrinkT ) +
2423
'l' + ceil( w - trX ) + ',' + floor( shrinkT ) +
2424
'qx' + ceil( w - shrinkR ) + ',' + floor( trY ) +
2425
'l' + ceil( w - shrinkR ) + ',' + ceil( h - brY ) +
2426
'qy' + ceil( w - brX ) + ',' + ceil( h - shrinkB ) +
2427
'l' + floor( blX ) + ',' + ceil( h - shrinkB ) +
2428
'qx' + floor( shrinkL ) + ',' + ceil( h - blY ) + ' x e';
2430
// simplified path for non-rounded box
2431
str = 'm' + floor( shrinkL ) + ',' + floor( shrinkT ) +
2432
'l' + ceil( w - shrinkR ) + ',' + floor( shrinkT ) +
2433
'l' + ceil( w - shrinkR ) + ',' + ceil( h - shrinkB ) +
2434
'l' + floor( shrinkL ) + ',' + ceil( h - shrinkB ) +
2442
* Get the container element for the shapes, creating it if necessary.
2444
getBox: function() {
2445
var box = this.parent.getLayer( this.boxZIndex ), s;
2448
box = doc.createElement( this.boxName );
2450
s.position = 'absolute';
2452
this.parent.addLayer( this.boxZIndex, box );
2460
* Hide the actual border of the element. In IE7 and up we can just set its color to transparent;
2461
* however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements
2462
* like form buttons require removing the border width altogether, so for those we increase the padding
2463
* by the border size.
2465
hideBorder: function() {
2466
var el = this.targetElement,
2467
cs = el.currentStyle,
2468
rs = el.runtimeStyle,
2470
isIE6 = PIE.ieVersion === 6,
2473
if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) ||
2474
tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) {
2475
rs.borderWidth = '';
2476
sides = this.styleInfos.borderInfo.sides;
2477
for( i = sides.length; i--; ) {
2479
rs[ 'padding' + side ] = '';
2480
rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) +
2481
( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) +
2482
( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away
2487
// Wrap all the element's children in a custom element, set the element to visiblity:hidden,
2488
// and set the wrapper element to visiblity:visible. This hides the outer element's decorations
2489
// (background and border) but displays all the contents.
2490
// TODO find a better way to do this that doesn't mess up the DOM parent-child relationship,
2491
// as this can interfere with other author scripts which add/modify/delete children. Also, this
2492
// won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into
2493
// using a compositor filter or some other filter which masks the border.
2494
if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) {
2495
var cont = doc.createElement( 'ie6-mask' ),
2496
s = cont.style, child;
2497
s.visibility = 'visible';
2499
while( child = el.firstChild ) {
2500
cont.appendChild( child );
2502
el.appendChild( cont );
2503
rs.visibility = 'hidden';
2507
rs.borderColor = 'transparent';
2511
unhideBorder: function() {
2517
* Destroy the rendered objects. This is a base implementation which handles common renderer
2518
* structures, but individual renderers may override as necessary.
2520
destroy: function() {
2521
this.parent.removeLayer( this.boxZIndex );
2522
delete this._shapes;
2523
delete this._layers;
2527
* Root renderer; creates the outermost container element and handles keeping it aligned
2528
* with the target element's size and position.
2529
* @param {Element} el The target element
2530
* @param {Object} styleInfos The StyleInfo objects
2532
PIE.RootRenderer = PIE.RendererBase.newRenderer( {
2534
isActive: function() {
2535
var children = this.childRenderers;
2536
for( var i in children ) {
2537
if( children.hasOwnProperty( i ) && children[ i ].isActive() ) {
2544
needsUpdate: function() {
2545
return this.styleInfos.visibilityInfo.changed();
2548
updatePos: function() {
2549
if( this.isActive() ) {
2550
var el = this.getPositioningElement(),
2554
tgtCS = el.currentStyle,
2555
tgtPos = tgtCS.position,
2557
s = this.getBox().style, cs,
2559
elBounds = this.boundsInfo.getBounds(),
2560
logicalZoomRatio = elBounds.logicalZoomRatio;
2562
if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) {
2563
x = elBounds.x * logicalZoomRatio;
2564
y = elBounds.y * logicalZoomRatio;
2567
// Get the element's offsets from its nearest positioned ancestor. Uses
2568
// getBoundingClientRect for accuracy and speed.
2570
par = par.offsetParent;
2571
} while( par && ( par.currentStyle.position === 'static' ) );
2573
parRect = par.getBoundingClientRect();
2574
cs = par.currentStyle;
2575
x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 );
2576
y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 );
2578
docEl = doc.documentElement;
2579
x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio;
2580
y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio;
2582
boxPos = 'absolute';
2585
s.position = boxPos;
2588
s.zIndex = tgtPos === 'static' ? -1 : tgtCS.zIndex;
2589
this.isPositioned = true;
2593
updateSize: PIE.emptyFn,
2595
updateVisibility: function() {
2596
var vis = this.styleInfos.visibilityInfo.getProps();
2597
this.getBox().style.display = ( vis.visible && vis.displayed ) ? '' : 'none';
2600
updateProps: function() {
2601
if( this.isActive() ) {
2602
this.updateVisibility();
2608
getPositioningElement: function() {
2609
var el = this.targetElement;
2610
return el.tagName in PIE.tableCellTags ? el.offsetParent : el;
2613
getBox: function() {
2614
var box = this._box, el;
2616
el = this.getPositioningElement();
2617
box = this._box = doc.createElement( 'css3-container' );
2618
box.style['direction'] = 'ltr'; //fix positioning bug in rtl environments
2620
this.updateVisibility();
2622
el.parentNode.insertBefore( box, el );
2627
finishUpdate: PIE.emptyFn,
2629
destroy: function() {
2630
var box = this._box, par;
2631
if( box && ( par = box.parentNode ) ) {
2632
par.removeChild( box );
2635
delete this._layers;
2640
* Renderer for element backgrounds.
2642
* @param {Element} el The target element
2643
* @param {Object} styleInfos The StyleInfo objects
2644
* @param {PIE.RootRenderer} parent
2646
PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( {
2649
boxName: 'background',
2651
needsUpdate: function() {
2652
var si = this.styleInfos;
2653
return si.backgroundInfo.changed() || si.borderRadiusInfo.changed();
2656
isActive: function() {
2657
var si = this.styleInfos;
2658
return si.borderImageInfo.isActive() ||
2659
si.borderRadiusInfo.isActive() ||
2660
si.backgroundInfo.isActive() ||
2661
( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset );
2668
var bounds = this.boundsInfo.getBounds();
2669
if( bounds.w && bounds.h ) {
2671
this.drawBgImages();
2676
* Draw the background color shape
2678
drawBgColor: function() {
2679
var props = this.styleInfos.backgroundInfo.getProps(),
2680
bounds = this.boundsInfo.getBounds(),
2681
el = this.targetElement,
2682
color = props && props.color,
2683
shape, w, h, s, alpha;
2685
if( color && color.alpha() > 0 ) {
2686
this.hideBackground();
2688
shape = this.getShape( 'bgColor', 'fill', this.getBox(), 1 );
2691
shape.stroked = false;
2692
shape.coordsize = w * 2 + ',' + h * 2;
2693
shape.coordorigin = '1,1';
2694
shape.path = this.getBoxPath( null, 2 );
2698
shape.fill.color = color.colorValue( el );
2700
alpha = color.alpha();
2702
shape.fill.opacity = alpha;
2705
this.deleteShape( 'bgColor' );
2710
* Draw all the background image layers
2712
drawBgImages: function() {
2713
var props = this.styleInfos.backgroundInfo.getProps(),
2714
bounds = this.boundsInfo.getBounds(),
2715
images = props && props.bgImages,
2716
img, shape, w, h, s, i;
2719
this.hideBackground();
2727
shape = this.getShape( 'bgImage' + i, 'fill', this.getBox(), 2 );
2729
shape.stroked = false;
2730
shape.fill.type = 'tile';
2731
shape.fillcolor = 'none';
2732
shape.coordsize = w * 2 + ',' + h * 2;
2733
shape.coordorigin = '1,1';
2734
shape.path = this.getBoxPath( 0, 2 );
2739
if( img.imgType === 'linear-gradient' ) {
2740
this.addLinearGradient( shape, img );
2743
shape.fill.src = img.imgUrl;
2744
this.positionBgImage( shape, i );
2749
// Delete any bgImage shapes previously created which weren't used above
2750
i = images ? images.length : 0;
2751
while( this.deleteShape( 'bgImage' + i++ ) ) {}
2756
* Set the position and clipping of the background image for a layer
2757
* @param {Element} shape
2758
* @param {number} index
2760
positionBgImage: function( shape, index ) {
2762
PIE.Util.withImageSize( shape.fill.src, function( size ) {
2763
var el = me.targetElement,
2764
bounds = me.boundsInfo.getBounds(),
2768
// It's possible that the element dimensions are zero now but weren't when the original
2769
// update executed, make sure that's not the case to avoid divide-by-zero error
2771
var fill = shape.fill,
2773
border = si.borderInfo.getProps(),
2774
bw = border && border.widths,
2775
bwT = bw ? bw['t'].pixels( el ) : 0,
2776
bwR = bw ? bw['r'].pixels( el ) : 0,
2777
bwB = bw ? bw['b'].pixels( el ) : 0,
2778
bwL = bw ? bw['l'].pixels( el ) : 0,
2779
bg = si.backgroundInfo.getProps().bgImages[ index ],
2780
bgPos = bg.bgPosition ? bg.bgPosition.coords( el, elW - size.w - bwL - bwR, elH - size.h - bwT - bwB ) : { x:0, y:0 },
2781
repeat = bg.imgRepeat,
2783
clipT = 0, clipL = 0,
2784
clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel)
2785
clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region
2787
// Positioning - find the pixel offset from the top/left and convert to a ratio
2788
// The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is
2789
// needed to fix antialiasing but makes the bg image fuzzy.
2790
pxX = Math.round( bgPos.x ) + bwL + 0.5;
2791
pxY = Math.round( bgPos.y ) + bwT + 0.5;
2792
fill.position = ( pxX / elW ) + ',' + ( pxY / elH );
2794
// Set the size of the image. We have to actually set it to px values otherwise it will not honor
2795
// the user's browser zoom level and always display at its natural screen size.
2796
fill['size']['x'] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird!
2797
fill['size'] = size.w + 'px,' + size.h + 'px';
2799
// Repeating - clip the image shape
2800
if( repeat && repeat !== 'repeat' ) {
2801
if( repeat === 'repeat-x' || repeat === 'no-repeat' ) {
2803
clipB = pxY + size.h + clipAdjust;
2805
if( repeat === 'repeat-y' || repeat === 'no-repeat' ) {
2807
clipR = pxX + size.w + clipAdjust;
2809
shape.style.clip = 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)';
2817
* Draw the linear gradient for a gradient layer
2818
* @param {Element} shape
2819
* @param {Object} info The object holding the information about the gradient
2821
addLinearGradient: function( shape, info ) {
2822
var el = this.targetElement,
2823
bounds = this.boundsInfo.getBounds(),
2828
stopCount = stops.length,
2830
GradientUtil = PIE.GradientUtil,
2831
perpendicularIntersect = GradientUtil.perpendicularIntersect,
2832
distance = GradientUtil.distance,
2833
metrics = GradientUtil.getGradientMetrics( el, w, h, info ),
2834
angle = metrics.angle,
2835
startX = metrics.startX,
2836
startY = metrics.startY,
2837
startCornerX = metrics.startCornerX,
2838
startCornerY = metrics.startCornerY,
2839
endCornerX = metrics.endCornerX,
2840
endCornerY = metrics.endCornerY,
2841
deltaX = metrics.deltaX,
2842
deltaY = metrics.deltaY,
2843
lineLength = metrics.lineLength,
2844
vmlAngle, vmlGradientLength, vmlColors,
2845
stopPx, vmlOffsetPct,
2846
p, i, j, before, after;
2848
// In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's
2849
// bounding box; for example specifying a 45 deg angle actually results in a gradient
2850
// drawn diagonally from one corner to its opposite corner, which will only appear to the
2851
// viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas
2852
// between the start and end points, multiply one of them by the shape's aspect ratio,
2853
// and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly
2854
// horizontal or vertical then we don't need to do this conversion.
2855
vmlAngle = ( angle % 90 ) ? Math.atan2( deltaX * w / h, deltaY ) / PI * 180 : ( angle + 90 );
2857
// VML angles are 180 degrees offset from CSS angles
2859
vmlAngle = vmlAngle % 360;
2861
// Add all the stops to the VML 'colors' list, including the first and last stops.
2862
// For each, we find its pixel offset along the gradient-line; if the offset of a stop is less
2863
// than that of its predecessor we increase it to be equal. We then map that pixel offset to a
2864
// percentage along the VML gradient-line, which runs from shape corner to corner.
2865
p = perpendicularIntersect( startCornerX, startCornerY, angle, endCornerX, endCornerY );
2866
vmlGradientLength = distance( startCornerX, startCornerY, p[0], p[1] );
2868
p = perpendicularIntersect( startX, startY, angle, startCornerX, startCornerY );
2869
vmlOffsetPct = distance( startX, startY, p[0], p[1] ) / vmlGradientLength * 100;
2871
// Find the pixel offsets along the CSS3 gradient-line for each stop.
2873
for( i = 0; i < stopCount; i++ ) {
2874
stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) :
2875
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
2877
// Fill in gaps with evenly-spaced offsets
2878
for( i = 1; i < stopCount; i++ ) {
2879
if( stopPx[ i ] === null ) {
2880
before = stopPx[ i - 1 ];
2883
after = stopPx[ ++j ];
2884
} while( after === null );
2885
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
2887
// Make sure each stop's offset is no less than the one before it
2888
stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] );
2891
// Convert to percentage along the VML gradient line and add to the VML 'colors' value
2892
for( i = 0; i < stopCount; i++ ) {
2894
( vmlOffsetPct + ( stopPx[ i ] / vmlGradientLength * 100 ) ) + '% ' + stops[i].color.colorValue( el )
2898
// Now, finally, we're ready to render the gradient fill. Set the start and end colors to
2899
// the first and last stop colors; this just sets outer bounds for the gradient.
2900
fill['angle'] = vmlAngle;
2901
fill['type'] = 'gradient';
2902
fill['method'] = 'sigma';
2903
fill['color'] = stops[0].color.colorValue( el );
2904
fill['color2'] = stops[stopCount - 1].color.colorValue( el );
2905
if( fill['colors'] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?)
2906
fill['colors'].value = vmlColors.join( ',' );
2908
fill['colors'] = vmlColors.join( ',' );
2914
* Hide the actual background image and color of the element.
2916
hideBackground: function() {
2917
var rs = this.targetElement.runtimeStyle;
2918
rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events
2919
rs.backgroundColor = 'transparent';
2922
destroy: function() {
2923
PIE.RendererBase.destroy.call( this );
2924
var rs = this.targetElement.runtimeStyle;
2925
rs.backgroundImage = rs.backgroundColor = '';
2930
* Renderer for element borders.
2932
* @param {Element} el The target element
2933
* @param {Object} styleInfos The StyleInfo objects
2934
* @param {PIE.RootRenderer} parent
2936
PIE.BorderRenderer = PIE.RendererBase.newRenderer( {
2941
needsUpdate: function() {
2942
var si = this.styleInfos;
2943
return si.borderInfo.changed() || si.borderRadiusInfo.changed();
2946
isActive: function() {
2947
var si = this.styleInfos;
2948
return si.borderRadiusInfo.isActive() &&
2949
!si.borderImageInfo.isActive() &&
2950
si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive
2954
* Draw the border shape(s)
2957
var el = this.targetElement,
2958
props = this.styleInfos.borderInfo.getProps(),
2959
bounds = this.boundsInfo.getBounds(),
2963
segments, seg, i, len;
2968
segments = this.getBorderSegments( 2 );
2969
for( i = 0, len = segments.length; i < len; i++) {
2971
shape = this.getShape( 'borderPiece' + i, seg.stroke ? 'stroke' : 'fill', this.getBox() );
2972
shape.coordsize = w * 2 + ',' + h * 2;
2973
shape.coordorigin = '1,1';
2974
shape.path = seg.path;
2979
shape.filled = !!seg.fill;
2980
shape.stroked = !!seg.stroke;
2982
stroke = shape.stroke;
2983
stroke['weight'] = seg.weight + 'px';
2984
stroke.color = seg.color.colorValue( el );
2985
stroke['dashstyle'] = seg.stroke === 'dashed' ? '2 2' : seg.stroke === 'dotted' ? '1 1' : 'solid';
2986
stroke['linestyle'] = seg.stroke === 'double' && seg.weight > 2 ? 'ThinThin' : 'Single';
2988
shape.fill.color = seg.fill.colorValue( el );
2992
// remove any previously-created border shapes which didn't get used above
2993
while( this.deleteShape( 'borderPiece' + i++ ) ) {}
2999
* Get the VML path definitions for the border segment(s).
3000
* @param {number=} mult If specified, all coordinates will be multiplied by this number
3001
* @return {Array.<string>}
3003
getBorderSegments: function( mult ) {
3004
var el = this.targetElement,
3006
borderInfo = this.styleInfos.borderInfo,
3008
floor, ceil, wT, wR, wB, wL,
3010
borderProps, radiusInfo, radii, widths, styles, colors;
3012
if( borderInfo.isActive() ) {
3013
borderProps = borderInfo.getProps();
3015
widths = borderProps.widths;
3016
styles = borderProps.styles;
3017
colors = borderProps.colors;
3019
if( borderProps.widthsSame && borderProps.stylesSame && borderProps.colorsSame ) {
3020
if( colors['t'].alpha() > 0 ) {
3021
// shortcut for identical border on all sides - only need 1 stroked shape
3022
wT = widths['t'].pixels( el ); //thickness
3023
wR = wT / 2; //shrink
3025
path: this.getBoxPath( { t: wR, r: wR, b: wR, l: wR }, mult ),
3026
stroke: styles['t'],
3034
bounds = this.boundsInfo.getBounds();
3038
wT = round( widths['t'].pixels( el ) );
3039
wR = round( widths['r'].pixels( el ) );
3040
wB = round( widths['b'].pixels( el ) );
3041
wL = round( widths['l'].pixels( el ) );
3049
radiusInfo = this.styleInfos.borderRadiusInfo;
3050
if( radiusInfo.isActive() ) {
3051
radii = this.getRadiiPixels( radiusInfo.getProps() );
3057
function radius( xy, corner ) {
3058
return radii ? radii[ xy ][ corner ] : 0;
3061
function curve( corner, shrinkX, shrinkY, startAngle, ccw, doMove ) {
3062
var rx = radius( 'x', corner),
3063
ry = radius( 'y', corner),
3065
isRight = corner.charAt( 1 ) === 'r',
3066
isBottom = corner.charAt( 0 ) === 'b';
3067
return ( rx > 0 && ry > 0 ) ?
3068
( doMove ? 'al' : 'ae' ) +
3069
( isRight ? ceil( elW - rx ) : floor( rx ) ) * mult + ',' + // center x
3070
( isBottom ? ceil( elH - ry ) : floor( ry ) ) * mult + ',' + // center y
3071
( floor( rx ) - shrinkX ) * mult + ',' + // width
3072
( floor( ry ) - shrinkY ) * mult + ',' + // height
3073
( startAngle * deg ) + ',' + // start angle
3074
( 45 * deg * ( ccw ? 1 : -1 ) // angle change
3076
( doMove ? 'm' : 'l' ) +
3077
( isRight ? elW - shrinkX : shrinkX ) * mult + ',' +
3078
( isBottom ? elH - shrinkY : shrinkY ) * mult
3082
function line( side, shrink, ccw, doMove ) {
3086
floor( radius( 'x', 'tl') ) * mult + ',' + ceil( shrink ) * mult :
3088
ceil( elW - shrink ) * mult + ',' + floor( radius( 'y', 'tr') ) * mult :
3090
ceil( elW - radius( 'x', 'br') ) * mult + ',' + floor( elH - shrink ) * mult :
3092
floor( shrink ) * mult + ',' + ceil( elH - radius( 'y', 'bl') ) * mult
3096
ceil( elW - radius( 'x', 'tr') ) * mult + ',' + ceil( shrink ) * mult :
3098
ceil( elW - shrink ) * mult + ',' + ceil( elH - radius( 'y', 'br') ) * mult :
3100
floor( radius( 'x', 'bl') ) * mult + ',' + floor( elH - shrink ) * mult :
3102
floor( shrink ) * mult + ',' + floor( radius( 'y', 'tl') ) * mult
3104
return ccw ? ( doMove ? 'm' + end : '' ) + 'l' + start :
3105
( doMove ? 'm' + start : '' ) + 'l' + end;
3109
function addSide( side, sideBefore, sideAfter, cornerBefore, cornerAfter, baseAngle ) {
3110
var vert = side === 'l' || side === 'r',
3111
sideW = pxWidths[ side ],
3112
beforeX, beforeY, afterX, afterY;
3114
if( sideW > 0 && styles[ side ] !== 'none' && colors[ side ].alpha() > 0 ) {
3115
beforeX = pxWidths[ vert ? side : sideBefore ];
3116
beforeY = pxWidths[ vert ? sideBefore : side ];
3117
afterX = pxWidths[ vert ? side : sideAfter ];
3118
afterY = pxWidths[ vert ? sideAfter : side ];
3120
if( styles[ side ] === 'dashed' || styles[ side ] === 'dotted' ) {
3122
path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
3123
curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
3124
fill: colors[ side ]
3127
path: line( side, sideW / 2, 0, 1 ),
3128
stroke: styles[ side ],
3130
color: colors[ side ]
3133
path: curve( cornerAfter, afterX, afterY, baseAngle, 0, 1 ) +
3134
curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ),
3135
fill: colors[ side ]
3140
path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
3141
line( side, sideW, 0, 0 ) +
3142
curve( cornerAfter, afterX, afterY, baseAngle, 0, 0 ) +
3144
( styles[ side ] === 'double' && sideW > 2 ?
3145
curve( cornerAfter, afterX - floor( afterX / 3 ), afterY - floor( afterY / 3 ), baseAngle - 45, 1, 0 ) +
3146
line( side, ceil( sideW / 3 * 2 ), 1, 0 ) +
3147
curve( cornerBefore, beforeX - floor( beforeX / 3 ), beforeY - floor( beforeY / 3 ), baseAngle, 1, 0 ) +
3149
curve( cornerBefore, floor( beforeX / 3 ), floor( beforeY / 3 ), baseAngle + 45, 0, 1 ) +
3150
line( side, floor( sideW / 3 ), 1, 0 ) +
3151
curve( cornerAfter, floor( afterX / 3 ), floor( afterY / 3 ), baseAngle, 0, 0 )
3154
curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ) +
3155
line( side, 0, 1, 0 ) +
3156
curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
3157
fill: colors[ side ]
3163
addSide( 't', 'l', 'r', 'tl', 'tr', 90 );
3164
addSide( 'r', 't', 'b', 'tr', 'br', 0 );
3165
addSide( 'b', 'r', 'l', 'br', 'bl', -90 );
3166
addSide( 'l', 'b', 't', 'bl', 'tl', -180 );
3173
destroy: function() {
3175
if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) {
3176
me.targetElement.runtimeStyle.borderColor = '';
3178
PIE.RendererBase.destroy.call( me );
3184
* Renderer for border-image
3186
* @param {Element} el The target element
3187
* @param {Object} styleInfos The StyleInfo objects
3188
* @param {PIE.RootRenderer} parent
3190
PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( {
3193
pieceNames: [ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl', 'c' ],
3195
needsUpdate: function() {
3196
return this.styleInfos.borderImageInfo.changed();
3199
isActive: function() {
3200
return this.styleInfos.borderImageInfo.isActive();
3204
this.getBox(); //make sure pieces are created
3206
var props = this.styleInfos.borderImageInfo.getProps(),
3207
borderProps = this.styleInfos.borderInfo.getProps(),
3208
bounds = this.boundsInfo.getBounds(),
3209
el = this.targetElement,
3210
pieces = this.pieces;
3212
PIE.Util.withImageSize( props.src, function( imgSize ) {
3215
zero = PIE.getLength( '0' ),
3216
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
3217
widthT = widths['t'].pixels( el ),
3218
widthR = widths['r'].pixels( el ),
3219
widthB = widths['b'].pixels( el ),
3220
widthL = widths['l'].pixels( el ),
3221
slices = props.slice,
3222
sliceT = slices['t'].pixels( el ),
3223
sliceR = slices['r'].pixels( el ),
3224
sliceB = slices['b'].pixels( el ),
3225
sliceL = slices['l'].pixels( el );
3227
// Piece positions and sizes
3228
function setSizeAndPos( piece, w, h, x, y ) {
3229
var s = pieces[piece].style,
3231
s.width = max(w, 0);
3232
s.height = max(h, 0);
3236
setSizeAndPos( 'tl', widthL, widthT, 0, 0 );
3237
setSizeAndPos( 't', elW - widthL - widthR, widthT, widthL, 0 );
3238
setSizeAndPos( 'tr', widthR, widthT, elW - widthR, 0 );
3239
setSizeAndPos( 'r', widthR, elH - widthT - widthB, elW - widthR, widthT );
3240
setSizeAndPos( 'br', widthR, widthB, elW - widthR, elH - widthB );
3241
setSizeAndPos( 'b', elW - widthL - widthR, widthB, widthL, elH - widthB );
3242
setSizeAndPos( 'bl', widthL, widthB, 0, elH - widthB );
3243
setSizeAndPos( 'l', widthL, elH - widthT - widthB, 0, widthT );
3244
setSizeAndPos( 'c', elW - widthL - widthR, elH - widthT - widthB, widthL, widthT );
3248
function setCrops( sides, crop, val ) {
3249
for( var i=0, len=sides.length; i < len; i++ ) {
3250
pieces[ sides[i] ]['imagedata'][ crop ] = val;
3255
setCrops( [ 'tl', 't', 'tr' ], 'cropBottom', ( imgSize.h - sliceT ) / imgSize.h );
3256
setCrops( [ 'tl', 'l', 'bl' ], 'cropRight', ( imgSize.w - sliceL ) / imgSize.w );
3257
setCrops( [ 'bl', 'b', 'br' ], 'cropTop', ( imgSize.h - sliceB ) / imgSize.h );
3258
setCrops( [ 'tr', 'r', 'br' ], 'cropLeft', ( imgSize.w - sliceR ) / imgSize.w );
3261
// TODO right now this treats everything like 'stretch', need to support other schemes
3262
//if( props.repeat.v === 'stretch' ) {
3263
setCrops( [ 'l', 'r', 'c' ], 'cropTop', sliceT / imgSize.h );
3264
setCrops( [ 'l', 'r', 'c' ], 'cropBottom', sliceB / imgSize.h );
3266
//if( props.repeat.h === 'stretch' ) {
3267
setCrops( [ 't', 'b', 'c' ], 'cropLeft', sliceL / imgSize.w );
3268
setCrops( [ 't', 'b', 'c' ], 'cropRight', sliceR / imgSize.w );
3272
pieces['c'].style.display = props.fill ? '' : 'none';
3276
getBox: function() {
3277
var box = this.parent.getLayer( this.boxZIndex ),
3279
pieceNames = this.pieceNames,
3280
len = pieceNames.length;
3283
box = doc.createElement( 'border-image' );
3285
s.position = 'absolute';
3289
for( i = 0; i < len; i++ ) {
3290
piece = this.pieces[ pieceNames[i] ] = PIE.Util.createVmlElement( 'rect' );
3291
piece.appendChild( PIE.Util.createVmlElement( 'imagedata' ) );
3293
s['behavior'] = 'url(#default#VML)';
3294
s.position = "absolute";
3296
piece['imagedata'].src = this.styleInfos.borderImageInfo.getProps().src;
3297
piece.stroked = false;
3298
piece.filled = false;
3299
box.appendChild( piece );
3302
this.parent.addLayer( this.boxZIndex, box );
3308
prepareUpdate: function() {
3309
if (this.isActive()) {
3311
el = me.targetElement,
3312
rs = el.runtimeStyle,
3313
widths = me.styleInfos.borderImageInfo.getProps().widths;
3315
// Force border-style to solid so it doesn't collapse
3316
rs.borderStyle = 'solid';
3318
// If widths specified in border-image shorthand, override border-width
3319
// NOTE px units needed here as this gets used by the IE9 renderer too
3321
rs.borderTopWidth = widths['t'].pixels( el ) + 'px';
3322
rs.borderRightWidth = widths['r'].pixels( el ) + 'px';
3323
rs.borderBottomWidth = widths['b'].pixels( el ) + 'px';
3324
rs.borderLeftWidth = widths['l'].pixels( el ) + 'px';
3327
// Make the border transparent
3332
destroy: function() {
3334
rs = me.targetElement.runtimeStyle;
3335
rs.borderStyle = '';
3336
if (me.finalized || !me.styleInfos.borderInfo.isActive()) {
3337
rs.borderColor = rs.borderWidth = '';
3339
PIE.RendererBase.destroy.call( this );
3344
* Renderer for outset box-shadows
3346
* @param {Element} el The target element
3347
* @param {Object} styleInfos The StyleInfo objects
3348
* @param {PIE.RootRenderer} parent
3350
PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( {
3353
boxName: 'outset-box-shadow',
3355
needsUpdate: function() {
3356
var si = this.styleInfos;
3357
return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed();
3360
isActive: function() {
3361
var boxShadowInfo = this.styleInfos.boxShadowInfo;
3362
return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0];
3367
el = this.targetElement,
3368
box = this.getBox(),
3369
styleInfos = this.styleInfos,
3370
shadowInfos = styleInfos.boxShadowInfo.getProps().outset,
3371
radii = styleInfos.borderRadiusInfo.getProps(),
3372
len = shadowInfos.length,
3374
bounds = this.boundsInfo.getBounds(),
3377
clipAdjust = PIE.ieVersion === 8 ? 1 : 0, //workaround for IE8 bug where VML leaks out top/left of clip region by 1px
3378
corners = [ 'tl', 'tr', 'br', 'bl' ], corner,
3379
shadowInfo, shape, fill, ss, xOff, yOff, spread, blur, shrink, color, alpha, path,
3380
totalW, totalH, focusX, focusY, isBottom, isRight;
3383
function getShadowShape( index, corner, xOff, yOff, color, blur, path ) {
3384
var shape = me.getShape( 'shadow' + index + corner, 'fill', box, len - index ),
3387
// Position and size
3388
shape['coordsize'] = w * 2 + ',' + h * 2;
3389
shape['coordorigin'] = '1,1';
3391
// Color and opacity
3392
shape['stroked'] = false;
3393
shape['filled'] = true;
3394
fill.color = color.colorValue( el );
3396
fill['type'] = 'gradienttitle'; //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?!
3397
fill['color2'] = fill.color;
3398
fill['opacity'] = 0;
3404
// This needs to go last for some reason, to prevent rendering at incorrect size
3416
shadowInfo = shadowInfos[ i ];
3417
xOff = shadowInfo.xOffset.pixels( el );
3418
yOff = shadowInfo.yOffset.pixels( el );
3419
spread = shadowInfo.spread.pixels( el );
3420
blur = shadowInfo.blur.pixels( el );
3421
color = shadowInfo.color;
3423
shrink = -spread - blur;
3424
if( !radii && blur ) {
3425
// If blurring, use a non-null border radius info object so that getBoxPath will
3426
// round the corners of the expanded shadow shape rather than squaring them off.
3427
radii = PIE.BorderRadiusStyleInfo.ALL_ZERO;
3429
path = this.getBoxPath( { t: shrink, r: shrink, b: shrink, l: shrink }, 2, radii );
3432
totalW = ( spread + blur ) * 2 + w;
3433
totalH = ( spread + blur ) * 2 + h;
3434
focusX = totalW ? blur * 2 / totalW : 0;
3435
focusY = totalH ? blur * 2 / totalH : 0;
3436
if( blur - spread > w / 2 || blur - spread > h / 2 ) {
3437
// If the blur is larger than half the element's narrowest dimension, we cannot do
3438
// this with a single shape gradient, because its focussize would have to be less than
3439
// zero which results in ugly artifacts. Instead we create four shapes, each with its
3440
// gradient focus past center, and then clip them so each only shows the quadrant
3441
// opposite the focus.
3442
for( j = 4; j--; ) {
3443
corner = corners[j];
3444
isBottom = corner.charAt( 0 ) === 'b';
3445
isRight = corner.charAt( 1 ) === 'r';
3446
shape = getShadowShape( i, corner, xOff, yOff, color, blur, path );
3448
fill['focusposition'] = ( isRight ? 1 - focusX : focusX ) + ',' +
3449
( isBottom ? 1 - focusY : focusY );
3450
fill['focussize'] = '0,0';
3452
// Clip to show only the appropriate quadrant. Add 1px to the top/left clip values
3453
// in IE8 to prevent a bug where IE8 displays one pixel outside the clip region.
3454
shape.style.clip = 'rect(' + ( ( isBottom ? totalH / 2 : 0 ) + clipAdjust ) + 'px,' +
3455
( isRight ? totalW : totalW / 2 ) + 'px,' +
3456
( isBottom ? totalH : totalH / 2 ) + 'px,' +
3457
( ( isRight ? totalW / 2 : 0 ) + clipAdjust ) + 'px)';
3460
// TODO delete old quadrant shapes if resizing expands past the barrier
3461
shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
3463
fill['focusposition'] = focusX + ',' + focusY;
3464
fill['focussize'] = ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 );
3467
shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
3468
alpha = color.alpha();
3470
// shape.style.filter = 'alpha(opacity=' + ( alpha * 100 ) + ')';
3471
// ss.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=' + ( alpha ) + ')';
3472
shape.fill.opacity = alpha;
3480
* Renderer for re-rendering img elements using VML. Kicks in if the img has
3481
* a border-radius applied, or if the -pie-png-fix flag is set.
3483
* @param {Element} el The target element
3484
* @param {Object} styleInfos The StyleInfo objects
3485
* @param {PIE.RootRenderer} parent
3487
PIE.ImgRenderer = PIE.RendererBase.newRenderer( {
3492
needsUpdate: function() {
3493
var si = this.styleInfos;
3494
return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed();
3497
isActive: function() {
3498
var si = this.styleInfos;
3499
return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix();
3503
this._lastSrc = src;
3504
this.hideActualImg();
3506
var shape = this.getShape( 'img', 'fill', this.getBox() ),
3508
bounds = this.boundsInfo.getBounds(),
3511
borderProps = this.styleInfos.borderInfo.getProps(),
3512
borderWidths = borderProps && borderProps.widths,
3513
el = this.targetElement,
3516
cs = el.currentStyle,
3517
getLength = PIE.getLength,
3520
// In IE6, the BorderRenderer will have hidden the border by moving the border-width to
3521
// the padding; therefore we want to pretend the borders have no width so they aren't doubled
3522
// when adding in the current padding value below.
3523
if( !borderWidths || PIE.ieVersion < 7 ) {
3524
zero = PIE.getLength( '0' );
3525
borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero };
3528
shape.stroked = false;
3529
fill.type = 'frame';
3531
fill.position = (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0);
3532
shape.coordsize = w * 2 + ',' + h * 2;
3533
shape.coordorigin = '1,1';
3534
shape.path = this.getBoxPath( {
3535
t: round( borderWidths['t'].pixels( el ) + getLength( cs.paddingTop ).pixels( el ) ),
3536
r: round( borderWidths['r'].pixels( el ) + getLength( cs.paddingRight ).pixels( el ) ),
3537
b: round( borderWidths['b'].pixels( el ) + getLength( cs.paddingBottom ).pixels( el ) ),
3538
l: round( borderWidths['l'].pixels( el ) + getLength( cs.paddingLeft ).pixels( el ) )
3545
hideActualImg: function() {
3546
this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)';
3549
destroy: function() {
3550
PIE.RendererBase.destroy.call( this );
3551
this.targetElement.runtimeStyle.filter = '';
3556
* Root renderer for IE9; manages the rendering layers in the element's background
3557
* @param {Element} el The target element
3558
* @param {Object} styleInfos The StyleInfo objects
3560
PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( {
3562
updatePos: PIE.emptyFn,
3563
updateSize: PIE.emptyFn,
3564
updateVisibility: PIE.emptyFn,
3565
updateProps: PIE.emptyFn,
3567
outerCommasRE: /^,+|,+$/g,
3568
innerCommasRE: /,+/g,
3570
setBackgroundLayer: function(zIndex, bg) {
3572
bgLayers = me._bgLayers || ( me._bgLayers = [] ),
3574
bgLayers[zIndex] = bg || undef;
3577
finishUpdate: function() {
3579
bgLayers = me._bgLayers,
3581
if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) {
3582
me._lastBg = me.targetElement.runtimeStyle.background = bg;
3586
destroy: function() {
3587
this.targetElement.runtimeStyle.background = '';
3588
delete this._bgLayers;
3593
* Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients
3594
* to an equivalent SVG data URI.
3596
* @param {Element} el The target element
3597
* @param {Object} styleInfos The StyleInfo objects
3599
PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( {
3603
needsUpdate: function() {
3604
var si = this.styleInfos;
3605
return si.backgroundInfo.changed();
3608
isActive: function() {
3609
var si = this.styleInfos;
3610
return si.backgroundInfo.isActive() || si.borderImageInfo.isActive();
3615
props = me.styleInfos.backgroundInfo.getProps(),
3616
bg, images, i = 0, img, bgAreaSize, bgSize;
3621
images = props.bgImages;
3623
while( img = images[ i++ ] ) {
3624
if (img.imgType === 'linear-gradient' ) {
3625
bgAreaSize = me.getBgAreaSize( img.bgOrigin );
3626
bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels(
3627
me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h
3630
'url(data:image/svg+xml,' + escape( me.getGradientSvg( img, bgSize.w, bgSize.h ) ) + ') ' +
3631
me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' +
3632
( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' )
3635
bg.push( img.origString );
3640
if ( props.color ) {
3641
bg.push( props.color.val );
3644
me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(','));
3648
bgPositionToString: function( bgPosition ) {
3649
return bgPosition ? bgPosition.tokens.map(function(token) {
3650
return token.tokenValue;
3651
}).join(' ') : '0 0';
3654
getBgAreaSize: function( bgOrigin ) {
3656
el = me.targetElement,
3657
bounds = me.boundsInfo.getBounds(),
3662
borders, getLength, cs;
3664
if( bgOrigin !== 'border-box' ) {
3665
borders = me.styleInfos.borderInfo.getProps();
3666
if( borders && ( borders = borders.widths ) ) {
3667
w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el );
3668
h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el );
3672
if ( bgOrigin === 'content-box' ) {
3673
getLength = PIE.getLength;
3674
cs = el.currentStyle;
3675
w -= getLength( cs.paddingLeft ).pixels( el ) + getLength( cs.paddingRight ).pixels( el );
3676
h -= getLength( cs.paddingTop ).pixels( el ) + getLength( cs.paddingBottom ).pixels( el );
3679
return { w: w, h: h };
3682
getGradientSvg: function( info, bgWidth, bgHeight ) {
3683
var el = this.targetElement,
3684
stopsInfo = info.stops,
3685
stopCount = stopsInfo.length,
3686
metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ),
3687
startX = metrics.startX,
3688
startY = metrics.startY,
3689
endX = metrics.endX,
3690
endY = metrics.endY,
3691
lineLength = metrics.lineLength,
3693
i, j, before, after,
3696
// Find the pixel offsets along the CSS3 gradient-line for each stop.
3698
for( i = 0; i < stopCount; i++ ) {
3699
stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) :
3700
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
3702
// Fill in gaps with evenly-spaced offsets
3703
for( i = 1; i < stopCount; i++ ) {
3704
if( stopPx[ i ] === null ) {
3705
before = stopPx[ i - 1 ];
3708
after = stopPx[ ++j ];
3709
} while( after === null );
3710
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
3715
'<svg width="' + bgWidth + '" height="' + bgHeight + '" xmlns="http://www.w3.org/2000/svg">' +
3717
'<linearGradient id="g" gradientUnits="userSpaceOnUse"' +
3718
' x1="' + ( startX / bgWidth * 100 ) + '%" y1="' + ( startY / bgHeight * 100 ) + '%" x2="' + ( endX / bgWidth * 100 ) + '%" y2="' + ( endY / bgHeight * 100 ) + '%">'
3721
// Convert to percentage along the SVG gradient line and add to the stops list
3722
for( i = 0; i < stopCount; i++ ) {
3724
'<stop offset="' + ( stopPx[ i ] / lineLength ) +
3725
'" stop-color="' + stopsInfo[i].color.colorValue( el ) +
3726
'" stop-opacity="' + stopsInfo[i].color.alpha() + '"/>'
3731
'</linearGradient>' +
3733
'<rect width="100%" height="100%" fill="url(#g)"/>' +
3737
return svg.join( '' );
3740
destroy: function() {
3741
this.parent.setBackgroundLayer( this.bgLayerZIndex );
3746
* Renderer for border-image
3748
* @param {Element} el The target element
3749
* @param {Object} styleInfos The StyleInfo objects
3750
* @param {PIE.RootRenderer} parent
3752
PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( {
3760
needsUpdate: function() {
3761
return this.styleInfos.borderImageInfo.changed();
3764
isActive: function() {
3765
return this.styleInfos.borderImageInfo.isActive();
3770
props = me.styleInfos.borderImageInfo.getProps(),
3771
borderProps = me.styleInfos.borderInfo.getProps(),
3772
bounds = me.boundsInfo.getBounds(),
3773
repeat = props.repeat,
3776
el = me.targetElement,
3779
PIE.Util.withImageSize( props.src, function( imgSize ) {
3785
// The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange
3786
// security exception (perhaps due to cross-origin policy within data URIs?) Therefore we
3787
// work around this by converting the image data into a data URI itself using a transient
3788
// canvas. This unfortunately requires the border-image src to be within the same domain,
3789
// which isn't a limitation in true border-image, so we need to try and find a better fix.
3790
imgSrc = me.imageToDataURI( props.src, imgW, imgH ),
3793
STRETCH = me.STRETCH,
3797
zero = PIE.getLength( '0' ),
3798
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
3799
widthT = widths['t'].pixels( el ),
3800
widthR = widths['r'].pixels( el ),
3801
widthB = widths['b'].pixels( el ),
3802
widthL = widths['l'].pixels( el ),
3803
slices = props.slice,
3804
sliceT = slices['t'].pixels( el ),
3805
sliceR = slices['r'].pixels( el ),
3806
sliceB = slices['b'].pixels( el ),
3807
sliceL = slices['l'].pixels( el ),
3808
centerW = elW - widthL - widthR,
3809
middleH = elH - widthT - widthB,
3810
imgCenterW = imgW - sliceL - sliceR,
3811
imgMiddleH = imgH - sliceT - sliceB,
3813
// Determine the size of each tile - 'round' is handled below
3814
tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT,
3815
tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR,
3816
tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB,
3817
tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL,
3824
// For 'round', subtract from each tile's size enough so that they fill the space a whole number of times
3825
if (repeatH === ROUND) {
3826
tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT);
3827
tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB);
3829
if (repeatV === ROUND) {
3830
tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR);
3831
tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL);
3835
// Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched
3836
// or repeated as the fill of a rect of appropriate size.
3838
'<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">'
3841
function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) {
3843
'<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' +
3844
'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' +
3845
'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' +
3846
'width="' + tileW + '" height="' + tileH + '">' +
3847
'<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' +
3848
'<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' +
3853
'<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />'
3857
addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left
3858
addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center
3859
addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right
3860
addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left
3861
if ( props.fill ) { // center fill
3862
addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH,
3863
tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH );
3865
addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right
3866
addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left
3867
addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center
3868
addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right
3872
patterns.join('\n') +
3878
me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' );
3880
// If the border-image's src wasn't immediately available, the SVG for its background layer
3881
// will have been created asynchronously after the main element's update has finished; we'll
3882
// therefore need to force the root renderer to sync to the final background once finished.
3884
me.parent.finishUpdate();
3892
* Convert a given image to a data URI
3894
imageToDataURI: (function() {
3896
return function( src, width, height ) {
3897
var uri = uris[ src ],
3900
image = new Image();
3901
canvas = doc.createElement( 'canvas' );
3903
canvas.width = width;
3904
canvas.height = height;
3905
canvas.getContext( '2d' ).drawImage( image, 0, 0 );
3906
uri = uris[ src ] = canvas.toDataURL();
3912
prepareUpdate: PIE.BorderImageRenderer.prototype.prepareUpdate,
3914
destroy: function() {
3916
rs = me.targetElement.runtimeStyle;
3917
me.parent.setBackgroundLayer( me.bgLayerZIndex );
3918
rs.borderColor = rs.borderStyle = rs.borderWidth = '';
3923
PIE.Element = (function() {
3926
lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init',
3927
pollCssProp = PIE.CSS_PREFIX + 'poll',
3928
trackActiveCssProp = PIE.CSS_PREFIX + 'track-active',
3929
trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover',
3930
hoverClass = PIE.CLASS_PREFIX + 'hover',
3931
activeClass = PIE.CLASS_PREFIX + 'active',
3932
focusClass = PIE.CLASS_PREFIX + 'focus',
3933
firstChildClass = PIE.CLASS_PREFIX + 'first-child',
3934
ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 },
3935
classNameRegExes = {},
3939
function addClass( el, className ) {
3940
el.className += ' ' + className;
3943
function removeClass( el, className ) {
3944
var re = classNameRegExes[ className ] ||
3945
( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) );
3946
el.className = el.className.replace( re, '' );
3949
function delayAddClass( el, className /*, className2*/ ) {
3950
var classes = dummyArray.slice.call( arguments, 1 ),
3952
setTimeout( function() {
3955
addClass( el, classes[ i ] );
3961
function delayRemoveClass( el, className /*, className2*/ ) {
3962
var classes = dummyArray.slice.call( arguments, 1 ),
3964
setTimeout( function() {
3967
removeClass( el, classes[ i ] );
3975
function Element( el ) {
3978
boundsInfo = new PIE.BoundsInfo( el ),
3984
eventListeners = [],
3990
* Initialize PIE for this element.
3993
if( !initialized ) {
3996
ieDocMode = PIE.ieDocMode,
3997
cs = el.currentStyle,
3998
lazy = cs.getAttribute( lazyInitCssProp ) === 'true',
3999
trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false',
4000
trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false',
4003
// Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll
4004
poll = cs.getAttribute( pollCssProp );
4005
poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true';
4007
// Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes
4008
// after load, but make sure it only gets called the first time through to avoid recursive calls to init().
4009
if( !initializing ) {
4011
el.runtimeStyle.zoom = 1;
4012
initFirstChildPseudoClass();
4017
// If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization
4018
if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) &&
4019
( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) {
4022
PIE.OnScroll.observe( init );
4026
delayed = initializing = 0;
4027
PIE.OnScroll.unobserve( init );
4029
// Create the style infos and renderers
4030
if ( ieDocMode === 9 ) {
4032
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
4033
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
4034
borderInfo: new PIE.BorderStyleInfo( el )
4037
styleInfos.backgroundInfo,
4038
styleInfos.borderImageInfo
4040
rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos );
4042
new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4043
new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
4048
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
4049
borderInfo: new PIE.BorderStyleInfo( el ),
4050
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
4051
borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ),
4052
boxShadowInfo: new PIE.BoxShadowStyleInfo( el ),
4053
visibilityInfo: new PIE.VisibilityStyleInfo( el )
4056
styleInfos.backgroundInfo,
4057
styleInfos.borderInfo,
4058
styleInfos.borderImageInfo,
4059
styleInfos.borderRadiusInfo,
4060
styleInfos.boxShadowInfo,
4061
styleInfos.visibilityInfo
4063
rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos );
4065
new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4066
new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4067
//new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4068
new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4069
new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
4071
if( el.tagName === 'IMG' ) {
4072
childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) );
4074
rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way?
4076
renderers = [ rootRenderer ].concat( childRenderers );
4078
// Add property change listeners to ancestors if requested
4079
initAncestorEventListeners();
4081
// Add to list of polled elements in IE8
4083
PIE.Heartbeat.observe( update );
4084
PIE.Heartbeat.run();
4087
// Trigger rendering
4091
if( !eventsAttached ) {
4093
if( ieDocMode < 9 ) {
4094
addListener( el, 'onmove', handleMoveOrResize );
4096
addListener( el, 'onresize', handleMoveOrResize );
4097
addListener( el, 'onpropertychange', propChanged );
4099
addListener( el, 'onmouseenter', mouseEntered );
4101
if( trackHover || trackActive ) {
4102
addListener( el, 'onmouseleave', mouseLeft );
4105
addListener( el, 'onmousedown', mousePressed );
4107
if( el.tagName in PIE.focusableElements ) {
4108
addListener( el, 'onfocus', focused );
4109
addListener( el, 'onblur', blurred );
4111
PIE.OnResize.observe( handleMoveOrResize );
4113
PIE.OnUnload.observe( removeEventListeners );
4116
boundsInfo.unlock();
4124
* Event handler for onmove and onresize events. Invokes update() only if the element's
4125
* bounds have previously been calculated, to prevent multiple runs during page load when
4126
* the element has no initial CSS3 properties.
4128
function handleMoveOrResize() {
4129
if( boundsInfo && boundsInfo.hasBeenQueried() ) {
4136
* Update position and/or size as necessary. Both move and resize events call
4137
* this rather than the updatePos/Size functions because sometimes, particularly
4138
* during page load, one will fire but the other won't.
4140
function update( force ) {
4143
var i, len = renderers.length;
4146
for( i = 0; i < len; i++ ) {
4147
renderers[i].prepareUpdate();
4149
if( force || boundsInfo.positionChanged() ) {
4150
/* TODO just using getBoundingClientRect (used internally by BoundsInfo) for detecting
4151
position changes may not always be accurate; it's possible that
4152
an element will actually move relative to its positioning parent, but its position
4153
relative to the viewport will stay the same. Need to come up with a better way to
4154
track movement. The most accurate would be the same logic used in RootRenderer.updatePos()
4155
but that is a more expensive operation since it does some DOM walking, and we want this
4156
check to be as fast as possible. */
4157
for( i = 0; i < len; i++ ) {
4158
renderers[i].updatePos();
4161
if( force || boundsInfo.sizeChanged() ) {
4162
for( i = 0; i < len; i++ ) {
4163
renderers[i].updateSize();
4166
rootRenderer.finishUpdate();
4169
else if( !initializing ) {
4176
* Handle property changes to trigger update when appropriate.
4178
function propChanged() {
4179
var i, len = renderers.length,
4183
// Some elements like <table> fire onpropertychange events for old-school background properties
4184
// ('background', 'bgColor') when runtimeStyle background properties are changed, which
4185
// results in an infinite loop; therefore we filter out those property names. Also, 'display'
4186
// is ignored because size calculations don't work correctly immediately when its onpropertychange
4187
// event fires, and because it will trigger an onresize event anyway.
4188
if( !destroyed && !( e && e.propertyName in ignorePropertyNames ) ) {
4191
for( i = 0; i < len; i++ ) {
4192
renderers[i].prepareUpdate();
4194
for( i = 0; i < len; i++ ) {
4195
renderer = renderers[i];
4196
// Make sure position is synced if the element hasn't already been rendered.
4197
// TODO this feels sloppy - look into merging propChanged and update functions
4198
if( !renderer.isPositioned ) {
4199
renderer.updatePos();
4201
if( renderer.needsUpdate() ) {
4202
renderer.updateProps();
4205
rootRenderer.finishUpdate();
4208
else if( !initializing ) {
4216
* Handle mouseenter events. Adds a custom class to the element to allow IE6 to add
4217
* hover styles to non-link elements, and to trigger a propertychange update.
4219
function mouseEntered() {
4220
//must delay this because the mouseenter event fires before the :hover styles are added.
4221
delayAddClass( el, hoverClass );
4225
* Handle mouseleave events
4227
function mouseLeft() {
4228
//must delay this because the mouseleave event fires before the :hover styles are removed.
4229
delayRemoveClass( el, hoverClass, activeClass );
4233
* Handle mousedown events. Adds a custom class to the element to allow IE6 to add
4234
* active styles to non-link elements, and to trigger a propertychange update.
4236
function mousePressed() {
4237
//must delay this because the mousedown event fires before the :active styles are added.
4238
delayAddClass( el, activeClass );
4240
// listen for mouseups on the document; can't just be on the element because the user might
4241
// have dragged out of the element while the mouse button was held down
4242
PIE.OnMouseup.observe( mouseReleased );
4246
* Handle mouseup events
4248
function mouseReleased() {
4249
//must delay this because the mouseup event fires before the :active styles are removed.
4250
delayRemoveClass( el, activeClass );
4252
PIE.OnMouseup.unobserve( mouseReleased );
4256
* Handle focus events. Adds a custom class to the element to trigger a propertychange update.
4258
function focused() {
4259
//must delay this because the focus event fires before the :focus styles are added.
4260
delayAddClass( el, focusClass );
4264
* Handle blur events
4266
function blurred() {
4267
//must delay this because the blur event fires before the :focus styles are removed.
4268
delayRemoveClass( el, focusClass );
4273
* Handle property changes on ancestors of the element; see initAncestorEventListeners()
4274
* which adds these listeners as requested with the -pie-watch-ancestors CSS property.
4276
function ancestorPropChanged() {
4277
var name = event.propertyName;
4278
if( name === 'className' || name === 'id' ) {
4283
function lockAll() {
4285
for( var i = styleInfosArr.length; i--; ) {
4286
styleInfosArr[i].lock();
4290
function unlockAll() {
4291
for( var i = styleInfosArr.length; i--; ) {
4292
styleInfosArr[i].unlock();
4294
boundsInfo.unlock();
4298
function addListener( targetEl, type, handler ) {
4299
targetEl.attachEvent( type, handler );
4300
eventListeners.push( [ targetEl, type, handler ] );
4304
* Remove all event listeners from the element and any monitored ancestors.
4306
function removeEventListeners() {
4307
if (eventsAttached) {
4308
var i = eventListeners.length,
4312
listener = eventListeners[ i ];
4313
listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] );
4316
PIE.OnUnload.unobserve( removeEventListeners );
4318
eventListeners = [];
4324
* Clean everything up when the behavior is removed from the element, or the element
4325
* is manually destroyed.
4327
function destroy() {
4331
removeEventListeners();
4335
// destroy any active renderers
4337
for( i = 0, len = renderers.length; i < len; i++ ) {
4338
renderers[i].finalized = 1;
4339
renderers[i].destroy();
4343
// Remove from list of polled elements in IE8
4345
PIE.Heartbeat.unobserve( update );
4347
// Stop onresize listening
4348
PIE.OnResize.unobserve( update );
4351
renderers = boundsInfo = styleInfos = styleInfosArr = el = null;
4357
* If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and
4358
* other event listeners to ancestor(s) of the element so we can pick up style changes
4359
* based on CSS rules using descendant selectors.
4361
function initAncestorEventListeners() {
4362
var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ),
4365
watch = parseInt( watch, 10 );
4368
while( a && ( watch === 'NaN' || i++ < watch ) ) {
4369
addListener( a, 'onpropertychange', ancestorPropChanged );
4370
addListener( a, 'onmouseenter', mouseEntered );
4371
addListener( a, 'onmouseleave', mouseLeft );
4372
addListener( a, 'onmousedown', mousePressed );
4373
if( a.tagName in PIE.focusableElements ) {
4374
addListener( a, 'onfocus', focused );
4375
addListener( a, 'onblur', blurred );
4384
* If the target element is a first child, add a pie_first-child class to it. This allows using
4385
* the added class as a workaround for the fact that PIE's rendering element breaks the :first-child
4386
* pseudo-class selector.
4388
function initFirstChildPseudoClass() {
4391
while( tmpEl = tmpEl.previousSibling ) {
4392
if( tmpEl.nodeType === 1 ) {
4398
addClass( el, firstChildClass );
4403
// These methods are all already bound to this instance so there's no need to wrap them
4404
// in a closure to maintain the 'this' scope object when calling them.
4406
this.update = update;
4407
this.destroy = destroy;
4411
Element.getInstance = function( el ) {
4412
var id = PIE.Util.getUID( el );
4413
return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) );
4416
Element.destroy = function( el ) {
4417
var id = PIE.Util.getUID( el ),
4418
wrapper = wrappers[ id ];
4421
delete wrappers[ id ];
4425
Element.destroyAll = function() {
4426
var els = [], wrapper;
4428
for( var w in wrappers ) {
4429
if( wrappers.hasOwnProperty( w ) ) {
4430
wrapper = wrappers[ w ];
4431
els.push( wrapper.el );
4444
* This file exposes the public API for invoking PIE.
4449
* @property supportsVML
4450
* True if the current IE browser environment has a functioning VML engine. Should be true
4451
* in most IEs, but in rare cases may be false. If false, PIE will exit immediately when
4452
* attached to an element; this property may be used for debugging or by external scripts
4453
* to perform some special action when VML support is absent.
4456
PIE[ 'supportsVML' ] = PIE.supportsVML;
4460
* Programatically attach PIE to a single element.
4461
* @param {Element} el
4463
PIE[ 'attach' ] = function( el ) {
4464
if (PIE.ieDocMode < 10 && PIE.supportsVML) {
4465
PIE.Element.getInstance( el ).init();
4471
* Programatically detach PIE from a single element.
4472
* @param {Element} el
4474
PIE[ 'detach' ] = function( el ) {
4475
PIE.Element.destroy( el );
4483
if ( doc.media !== 'print' ) { // IE strangely attaches a second copy of the behavior to elements when printing
4484
var PIE = window[ 'PIE' ];
4486
PIE['attach']( el );
4491
function cleanup() {
4492
if ( doc.media !== 'print' ) {
4493
var PIE = window[ 'PIE' ];
4495
PIE['detach']( el );
4501
if( el.readyState === 'complete' ) {