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.
8
var doc = document;var PIE = window['PIE'];
11
PIE = window['PIE'] = {
21
* Lookup table of elements which cannot take custom children.
38
* Elements that can receive user focus
49
* Values of the type attribute for input elements displayed as buttons
57
emptyFn: function() {}
60
// Force the background cache to be used. No reason it shouldn't be.
62
doc.execCommand( 'BackgroundImageCache', false, true );
67
* IE version detection approach by James Padolsey, with modifications -- from
68
* http://james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
71
div = doc.createElement('div'),
72
all = div.getElementsByTagName('i'),
75
div.innerHTML = '<!--[if gt IE ' + (++ieVersion) + ']><i></i><![endif]-->',
78
PIE.ieVersion = ieVersion;
81
if( ieVersion === 6 ) {
82
// IE6 can't access properties with leading dash, but can without it.
83
PIE.CSS_PREFIX = PIE.CSS_PREFIX.replace( /^-/, '' );
86
PIE.ieDocMode = doc.documentMode || PIE.ieVersion;
88
// Detect VML support (a small number of IE installs don't have a working VML engine)
89
div.innerHTML = '<v:shape adj="1"/>';
90
shape = div.firstChild;
91
shape.style['behavior'] = 'url(#default#VML)';
92
PIE.supportsVML = (typeof shape['adj'] === "object");
106
* To create a VML element, it must be created by a Document which has the VML
107
* namespace set. Unfortunately, if you try to add the namespace programatically
108
* into the main document, you will get an "Unspecified error" when trying to
109
* access document.namespaces before the document is finished loading. To get
110
* around this, we create a DocumentFragment, which in IE land is apparently a
111
* full-fledged Document. It allows adding namespaces immediately, so we add the
112
* namespace there and then have it create the VML element.
113
* @param {string} tag The tag name for the VML element
114
* @return {Element} The new VML element
116
createVmlElement: function( tag ) {
117
var vmlPrefix = 'css3vml';
118
if( !vmlCreatorDoc ) {
119
vmlCreatorDoc = doc.createDocumentFragment();
120
vmlCreatorDoc.namespaces.add( vmlPrefix, 'urn:schemas-microsoft-com:vml' );
122
return vmlCreatorDoc.createElement( vmlPrefix + ':' + tag );
127
* Generate and return a unique ID for a given object. The generated ID is stored
128
* as a property of the object for future reuse.
129
* @param {Object} obj
131
getUID: function( obj ) {
132
return obj && obj[ '_pieId' ] || ( obj[ '_pieId' ] = '_' + ++idNum );
137
* Simple utility for merging objects
138
* @param {Object} obj1 The main object into which all others will be merged
139
* @param {...Object} var_args Other objects which will be merged into the first, in order
141
merge: function( obj1 ) {
142
var i, len, p, objN, args = arguments;
143
for( i = 1, len = args.length; i < len; i++ ) {
146
if( objN.hasOwnProperty( p ) ) {
147
obj1[ p ] = objN[ p ];
156
* Execute a callback function, passing it the dimensions of a given image once
158
* @param {string} src The source URL of the image
159
* @param {function({w:number, h:number})} func The callback function to be called once the image dimensions are known
160
* @param {Object} ctx A context object which will be used as the 'this' value within the executed callback function
162
withImageSize: function( src, func, ctx ) {
163
var size = imageSizes[ src ], img, queue;
165
// If we have a queue, add to it
166
if( Object.prototype.toString.call( size ) === '[object Array]' ) {
167
size.push( [ func, ctx ] );
169
// Already have the size cached, call func right away
171
func.call( ctx, size );
174
queue = imageSizes[ src ] = [ [ func, ctx ] ]; //create queue
176
img.onload = function() {
177
size = imageSizes[ src ] = { w: img.width, h: img.height };
178
for( var i = 0, len = queue.length; i < len; i++ ) {
179
queue[ i ][ 0 ].call( queue[ i ][ 1 ], size );
188
* Utility functions for handling gradients
192
getGradientMetrics: function( el, width, height, gradientInfo ) {
193
var angle = gradientInfo.angle,
194
startPos = gradientInfo.gradientStart,
197
startCornerX, startCornerY,
198
endCornerX, endCornerY,
202
// Find the "start" and "end" corners; these are the corners furthest along the gradient line.
203
// This is used below to find the start/end positions of the CSS3 gradient-line, and also in finding
204
// the total length of the VML rendered gradient-line corner to corner.
205
function findCorners() {
206
startCornerX = ( angle >= 90 && angle < 270 ) ? width : 0;
207
startCornerY = angle < 180 ? height : 0;
208
endCornerX = width - startCornerX;
209
endCornerY = height - startCornerY;
212
// Normalize the angle to a value between [0, 360)
213
function normalizeAngle() {
220
// Find the start and end points of the gradient
222
startPos = startPos.coords( el, width, height );
227
angle = angle.degrees();
232
// If no start position was specified, then choose a corner as the starting point.
234
startX = startCornerX;
235
startY = startCornerY;
238
// Find the end position by extending a perpendicular line from the gradient-line which
239
// intersects the corner opposite from the starting corner.
240
p = PIE.GradientUtil.perpendicularIntersect( startX, startY, angle, endCornerX, endCornerY );
244
else if( startPos ) {
245
// Start position but no angle specified: find the end point by rotating 180deg around the center
246
endX = width - startX;
247
endY = height - startY;
250
// Neither position nor angle specified; create vertical gradient from top to bottom
251
startX = startY = endX = 0;
254
deltaX = endX - startX;
255
deltaY = endY - startY;
257
if( angle === UNDEF ) {
258
// Get the angle based on the change in x/y from start to end point. Checks first for horizontal
259
// or vertical angles so they get exact whole numbers rather than what atan2 gives.
260
angle = ( !deltaX ? ( deltaY < 0 ? 90 : 270 ) :
261
( !deltaY ? ( deltaX < 0 ? 180 : 0 ) :
262
-Math.atan2( deltaY, deltaX ) / Math.PI * 180
275
startCornerX: startCornerX,
276
startCornerY: startCornerY,
277
endCornerX: endCornerX,
278
endCornerY: endCornerY,
281
lineLength: PIE.GradientUtil.distance( startX, startY, endX, endY )
286
* Find the point along a given line (defined by a starting point and an angle), at which
287
* that line is intersected by a perpendicular line extending through another point.
288
* @param x1 - x coord of the starting point
289
* @param y1 - y coord of the starting point
290
* @param angle - angle of the line extending from the starting point (in degrees)
291
* @param x2 - x coord of point along the perpendicular line
292
* @param y2 - y coord of point along the perpendicular line
295
perpendicularIntersect: function( x1, y1, angle, x2, y2 ) {
296
// Handle straight vertical and horizontal angles, for performance and to avoid
297
// divide-by-zero errors.
298
if( angle === 0 || angle === 180 ) {
301
else if( angle === 90 || angle === 270 ) {
305
// General approach: determine the Ax+By=C formula for each line (the slope of the second
306
// line is the negative inverse of the first) and then solve for where both formulas have
307
// the same x/y values.
308
var a1 = Math.tan( -angle * Math.PI / 180 ),
313
endX = ( c2 - c1 ) / d,
314
endY = ( a1 * c2 - a2 * c1 ) / d;
315
return [ endX, endY ];
320
* Find the distance between two points
321
* @param {Number} p1x
322
* @param {Number} p1y
323
* @param {Number} p2x
324
* @param {Number} p2y
325
* @return {Number} the distance
327
distance: function( p1x, p1y, p2x, p2y ) {
333
Math.sqrt( dx * dx + dy * dy )
340
PIE.Observable = function() {
342
* List of registered observer functions
347
* Hash of function ids to their position in the observers list, for fast lookup
351
PIE.Observable.prototype = {
353
observe: function( fn ) {
354
var id = PIE.Util.getUID( fn ),
355
indexes = this.indexes,
356
observers = this.observers;
357
if( !( id in indexes ) ) {
358
indexes[ id ] = observers.length;
359
observers.push( fn );
363
unobserve: function( fn ) {
364
var id = PIE.Util.getUID( fn ),
365
indexes = this.indexes;
366
if( id && id in indexes ) {
367
delete this.observers[ indexes[ id ] ];
368
delete indexes[ id ];
373
var o = this.observers,
381
* Simple heartbeat timer - this is a brute-force workaround for syncing issues caused by IE not
382
* always firing the onmove and onresize events when elements are moved or resized. We check a few
383
* times every second to make sure the elements have the correct position and size. See Element.js
384
* which adds heartbeat listeners based on the custom -pie-poll flag, which defaults to true in IE8-9
385
* and false elsewhere.
388
PIE.Heartbeat = new PIE.Observable();
389
PIE.Heartbeat.run = function() {
393
interval = doc.documentElement.currentStyle.getAttribute( PIE.CSS_PREFIX + 'poll-interval' ) || 250;
396
setTimeout(beat, interval);
402
* Create an observable listener for the onunload event
405
PIE.OnUnload = new PIE.Observable();
407
function handleUnload() {
409
window.detachEvent( 'onunload', handleUnload );
410
window[ 'PIE' ] = null;
413
window.attachEvent( 'onunload', handleUnload );
416
* Attach an event which automatically gets detached onunload
418
PIE.OnUnload.attachManagedEvent = function( target, name, handler ) {
419
target.attachEvent( name, handler );
420
this.observe( function() {
421
target.detachEvent( name, handler );
425
* Create a single observable listener for window resize events.
427
PIE.OnResize = new PIE.Observable();
429
PIE.OnUnload.attachManagedEvent( window, 'onresize', function() { PIE.OnResize.fire(); } );
431
* Create a single observable listener for scroll events. Used for lazy loading based
432
* on the viewport, and for fixed position backgrounds.
435
PIE.OnScroll = new PIE.Observable();
437
function scrolled() {
441
PIE.OnUnload.attachManagedEvent( window, 'onscroll', scrolled );
443
PIE.OnResize.observe( scrolled );
446
* Listen for printing events, destroy all active PIE instances when printing, and
447
* restore them afterward.
453
function beforePrint() {
454
elements = PIE.Element.destroyAll();
457
function afterPrint() {
459
for( var i = 0, len = elements.length; i < len; i++ ) {
460
PIE[ 'attach' ]( elements[i] );
466
if( PIE.ieDocMode < 9 ) {
467
PIE.OnUnload.attachManagedEvent( window, 'onbeforeprint', beforePrint );
468
PIE.OnUnload.attachManagedEvent( window, 'onafterprint', afterPrint );
472
* Create a single observable listener for document mouseup events.
474
PIE.OnMouseup = new PIE.Observable();
476
PIE.OnUnload.attachManagedEvent( doc, 'onmouseup', function() { PIE.OnMouseup.fire(); } );
478
* Wrapper for length and percentage style values. The value is immutable. A singleton instance per unique
479
* value is returned from PIE.getLength() - always use that instead of instantiating directly.
481
* @param {string} val The CSS string representing the length. It is assumed that this will already have
482
* been validated as a valid length or percentage syntax.
484
PIE.Length = (function() {
485
var lengthCalcEl = doc.createElement( 'length-calc' ),
486
parent = doc.body || doc.documentElement,
487
s = lengthCalcEl.style,
489
units = [ 'mm', 'cm', 'in', 'pt', 'pc' ],
493
s.position = 'absolute';
494
s.top = s.left = '-9999px';
496
parent.appendChild( lengthCalcEl );
498
s.width = '100' + units[i];
499
conversions[ units[i] ] = lengthCalcEl.offsetWidth / 100;
501
parent.removeChild( lengthCalcEl );
503
// All calcs from here on will use 1em
507
function Length( val ) {
512
* Regular expression for matching the length unit
515
unitRE: /(px|em|ex|mm|cm|in|pt|pc|%)$/,
518
* Get the numeric value of the length
519
* @return {number} The value
521
getNumber: function() {
524
if( num === UNDEF ) {
525
num = this.num = parseFloat( this.val );
531
* Get the unit of the length
532
* @return {string} The unit
534
getUnit: function() {
535
var unit = this.unit,
538
m = this.val.match( this.unitRE );
539
unit = this.unit = ( m && m[0] ) || 'px';
545
* Determine whether this is a percentage length value
548
isPercentage: function() {
549
return this.getUnit() === '%';
553
* Resolve this length into a number of pixels.
554
* @param {Element} el - the context element, used to resolve font-relative values
555
* @param {(function():number|number)=} pct100 - the number of pixels that equal a 100% percentage. This can be either a number or a
556
* function which will be called to return the number.
558
pixels: function( el, pct100 ) {
559
var num = this.getNumber(),
560
unit = this.getUnit();
565
return num * ( typeof pct100 === 'function' ? pct100() : pct100 ) / 100;
567
return num * this.getEmPixels( el );
569
return num * this.getEmPixels( el ) / 2;
571
return num * conversions[ unit ];
576
* The em and ex units are relative to the font-size of the current element,
577
* however if the font-size is set using non-pixel units then we get that value
578
* rather than a pixel conversion. To get around this, we keep a floating element
579
* with width:1em which we insert into the target element and then read its offsetWidth.
580
* For elements that won't accept a child we insert into the parent node and perform
581
* additional calculation. If the font-size *is* specified in pixels, then we use that
582
* directly to avoid the expensive DOM manipulation.
583
* @param {Element} el
586
getEmPixels: function( el ) {
587
var fs = el.currentStyle.fontSize,
590
if( fs.indexOf( 'px' ) > 0 ) {
591
return parseFloat( fs );
593
else if( el.tagName in PIE.childlessElements ) {
595
parent = el.parentNode;
596
return PIE.getLength( fs ).pixels( parent, function() {
597
return me.getEmPixels( parent );
601
el.appendChild( lengthCalcEl );
602
px = lengthCalcEl.offsetWidth;
603
if( lengthCalcEl.parentNode === el ) { //not sure how this could be false but it sometimes is
604
el.removeChild( lengthCalcEl );
613
* Retrieve a PIE.Length instance for the given value. A shared singleton instance is returned for each unique value.
614
* @param {string} val The CSS string representing the length. It is assumed that this will already have
615
* been validated as a valid length or percentage syntax.
617
PIE.getLength = function( val ) {
618
return instances[ val ] || ( instances[ val ] = new Length( val ) );
624
* Wrapper for a CSS3 bg-position value. Takes up to 2 position keywords and 2 lengths/percentages.
626
* @param {Array.<PIE.Tokenizer.Token>} tokens The tokens making up the background position value.
628
PIE.BgPosition = (function() {
630
var length_fifty = PIE.getLength( '50%' ),
631
vert_idents = { 'top': 1, 'center': 1, 'bottom': 1 },
632
horiz_idents = { 'left': 1, 'center': 1, 'right': 1 };
635
function BgPosition( tokens ) {
636
this.tokens = tokens;
638
BgPosition.prototype = {
640
* Normalize the values into the form:
641
* [ xOffsetSide, xOffsetLength, yOffsetSide, yOffsetLength ]
642
* where: xOffsetSide is either 'left' or 'right',
643
* yOffsetSide is either 'top' or 'bottom',
644
* and x/yOffsetLength are both PIE.Length objects.
647
getValues: function() {
648
if( !this._values ) {
649
var tokens = this.tokens,
651
Tokenizer = PIE.Tokenizer,
652
identType = Tokenizer.Type,
653
length_zero = PIE.getLength( '0' ),
654
type_ident = identType.IDENT,
655
type_length = identType.LENGTH,
656
type_percent = identType.PERCENT,
658
vals = [ 'left', length_zero, 'top', length_zero ];
660
// If only one value, the second is assumed to be 'center'
662
tokens.push( new Tokenizer.Token( type_ident, 'center' ) );
668
// If both idents, they can appear in either order, so switch them if needed
669
if( type_ident & ( tokens[0].tokenType | tokens[1].tokenType ) &&
670
tokens[0].tokenValue in vert_idents && tokens[1].tokenValue in horiz_idents ) {
671
tokens.push( tokens.shift() );
673
if( tokens[0].tokenType & type_ident ) {
674
if( tokens[0].tokenValue === 'center' ) {
675
vals[1] = length_fifty;
677
vals[0] = tokens[0].tokenValue;
680
else if( tokens[0].isLengthOrPercent() ) {
681
vals[1] = PIE.getLength( tokens[0].tokenValue );
683
if( tokens[1].tokenType & type_ident ) {
684
if( tokens[1].tokenValue === 'center' ) {
685
vals[3] = length_fifty;
687
vals[2] = tokens[1].tokenValue;
690
else if( tokens[1].isLengthOrPercent() ) {
691
vals[3] = PIE.getLength( tokens[1].tokenValue );
695
// Three or four values - CSS3
706
* Find the coordinates of the background image from the upper-left corner of the background area.
707
* Note that these coordinate values are not rounded.
708
* @param {Element} el
709
* @param {number} width - the width for percentages (background area width minus image width)
710
* @param {number} height - the height for percentages (background area height minus image height)
711
* @return {Object} { x: Number, y: Number }
713
coords: function( el, width, height ) {
714
var vals = this.getValues(),
715
pxX = vals[1].pixels( el, width ),
716
pxY = vals[3].pixels( el, height );
719
x: vals[0] === 'right' ? width - pxX : pxX,
720
y: vals[2] === 'bottom' ? height - pxY : pxY
728
* Wrapper for a CSS3 background-size value.
730
* @param {String|PIE.Length} w The width parameter
731
* @param {String|PIE.Length} h The height parameter, if any
733
PIE.BgSize = (function() {
735
var CONTAIN = 'contain',
740
function BgSize( w, h ) {
746
pixels: function( el, areaW, areaH, imgW, imgH ) {
750
areaRatio = areaW / areaH,
751
imgRatio = imgW / imgH;
753
if ( w === CONTAIN ) {
754
w = imgRatio > areaRatio ? areaW : areaH * imgRatio;
755
h = imgRatio > areaRatio ? areaW / imgRatio : areaH;
757
else if ( w === COVER ) {
758
w = imgRatio < areaRatio ? areaW : areaH * imgRatio;
759
h = imgRatio < areaRatio ? areaW / imgRatio : areaH;
761
else if ( w === AUTO ) {
762
h = ( h === AUTO ? imgH : h.pixels( el, areaH ) );
766
w = w.pixels( el, areaW );
767
h = ( h === AUTO ? w / imgRatio : h.pixels( el, areaH ) );
770
return { w: w, h: h };
775
BgSize.DEFAULT = new BgSize( AUTO, AUTO );
780
* Wrapper for angle values; handles conversion to degrees from all allowed angle units
782
* @param {string} val The raw CSS value for the angle. It is assumed it has been pre-validated.
784
PIE.Angle = (function() {
785
function Angle( val ) {
792
* @return {string} The unit of the angle value
794
getUnit: function() {
795
return this._unit || ( this._unit = this.val.match( this.unitRE )[0].toLowerCase() );
799
* Get the numeric value of the angle in degrees.
800
* @return {number} The degrees value
802
degrees: function() {
803
var deg = this._deg, u, n;
804
if( deg === undefined ) {
806
n = parseFloat( this.val, 10 );
807
deg = this._deg = ( u === 'deg' ? n : u === 'rad' ? n / Math.PI * 180 : u === 'grad' ? n / 400 * 360 : u === 'turn' ? n * 360 : 0 );
815
* Abstraction for colors values. Allows detection of rgba values. A singleton instance per unique
816
* value is returned from PIE.getColor() - always use that instead of instantiating directly.
818
* @param {string} val The raw CSS string value for the color
820
PIE.Color = (function() {
823
function Color( val ) {
828
* Regular expression for matching rgba colors and extracting their components
831
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*/;
834
"aliceblue":"F0F8FF", "antiquewhite":"FAEBD7", "aqua":"0FF",
835
"aquamarine":"7FFFD4", "azure":"F0FFFF", "beige":"F5F5DC",
836
"bisque":"FFE4C4", "black":"000", "blanchedalmond":"FFEBCD",
837
"blue":"00F", "blueviolet":"8A2BE2", "brown":"A52A2A",
838
"burlywood":"DEB887", "cadetblue":"5F9EA0", "chartreuse":"7FFF00",
839
"chocolate":"D2691E", "coral":"FF7F50", "cornflowerblue":"6495ED",
840
"cornsilk":"FFF8DC", "crimson":"DC143C", "cyan":"0FF",
841
"darkblue":"00008B", "darkcyan":"008B8B", "darkgoldenrod":"B8860B",
842
"darkgray":"A9A9A9", "darkgreen":"006400", "darkkhaki":"BDB76B",
843
"darkmagenta":"8B008B", "darkolivegreen":"556B2F", "darkorange":"FF8C00",
844
"darkorchid":"9932CC", "darkred":"8B0000", "darksalmon":"E9967A",
845
"darkseagreen":"8FBC8F", "darkslateblue":"483D8B", "darkslategray":"2F4F4F",
846
"darkturquoise":"00CED1", "darkviolet":"9400D3", "deeppink":"FF1493",
847
"deepskyblue":"00BFFF", "dimgray":"696969", "dodgerblue":"1E90FF",
848
"firebrick":"B22222", "floralwhite":"FFFAF0", "forestgreen":"228B22",
849
"fuchsia":"F0F", "gainsboro":"DCDCDC", "ghostwhite":"F8F8FF",
850
"gold":"FFD700", "goldenrod":"DAA520", "gray":"808080",
851
"green":"008000", "greenyellow":"ADFF2F", "honeydew":"F0FFF0",
852
"hotpink":"FF69B4", "indianred":"CD5C5C", "indigo":"4B0082",
853
"ivory":"FFFFF0", "khaki":"F0E68C", "lavender":"E6E6FA",
854
"lavenderblush":"FFF0F5", "lawngreen":"7CFC00", "lemonchiffon":"FFFACD",
855
"lightblue":"ADD8E6", "lightcoral":"F08080", "lightcyan":"E0FFFF",
856
"lightgoldenrodyellow":"FAFAD2", "lightgreen":"90EE90", "lightgrey":"D3D3D3",
857
"lightpink":"FFB6C1", "lightsalmon":"FFA07A", "lightseagreen":"20B2AA",
858
"lightskyblue":"87CEFA", "lightslategray":"789", "lightsteelblue":"B0C4DE",
859
"lightyellow":"FFFFE0", "lime":"0F0", "limegreen":"32CD32",
860
"linen":"FAF0E6", "magenta":"F0F", "maroon":"800000",
861
"mediumauqamarine":"66CDAA", "mediumblue":"0000CD", "mediumorchid":"BA55D3",
862
"mediumpurple":"9370D8", "mediumseagreen":"3CB371", "mediumslateblue":"7B68EE",
863
"mediumspringgreen":"00FA9A", "mediumturquoise":"48D1CC", "mediumvioletred":"C71585",
864
"midnightblue":"191970", "mintcream":"F5FFFA", "mistyrose":"FFE4E1",
865
"moccasin":"FFE4B5", "navajowhite":"FFDEAD", "navy":"000080",
866
"oldlace":"FDF5E6", "olive":"808000", "olivedrab":"688E23",
867
"orange":"FFA500", "orangered":"FF4500", "orchid":"DA70D6",
868
"palegoldenrod":"EEE8AA", "palegreen":"98FB98", "paleturquoise":"AFEEEE",
869
"palevioletred":"D87093", "papayawhip":"FFEFD5", "peachpuff":"FFDAB9",
870
"peru":"CD853F", "pink":"FFC0CB", "plum":"DDA0DD",
871
"powderblue":"B0E0E6", "purple":"800080", "red":"F00",
872
"rosybrown":"BC8F8F", "royalblue":"4169E1", "saddlebrown":"8B4513",
873
"salmon":"FA8072", "sandybrown":"F4A460", "seagreen":"2E8B57",
874
"seashell":"FFF5EE", "sienna":"A0522D", "silver":"C0C0C0",
875
"skyblue":"87CEEB", "slateblue":"6A5ACD", "slategray":"708090",
876
"snow":"FFFAFA", "springgreen":"00FF7F", "steelblue":"4682B4",
877
"tan":"D2B48C", "teal":"008080", "thistle":"D8BFD8",
878
"tomato":"FF6347", "turquoise":"40E0D0", "violet":"EE82EE",
879
"wheat":"F5DEB3", "white":"FFF", "whitesmoke":"F5F5F5",
880
"yellow":"FF0", "yellowgreen":"9ACD32"
892
m = v.match( Color.rgbaRE );
894
me._color = 'rgb(' + m[1] + ',' + m[2] + ',' + m[3] + ')';
895
me._alpha = parseFloat( m[4] );
898
if( ( vLower = v.toLowerCase() ) in Color.names ) {
899
v = '#' + Color.names[vLower];
902
me._alpha = ( v === 'transparent' ? 0 : 1 );
908
* Retrieve the value of the color in a format usable by IE natively. This will be the same as
909
* the raw input value, except for rgba values which will be converted to an rgb value.
910
* @param {Element} el The context element, used to get 'currentColor' keyword value.
911
* @return {string} Color value
913
colorValue: function( el ) {
915
return this._color === 'currentColor' ? el.currentStyle.color : this._color;
919
* Retrieve the alpha value of the color. Will be 1 for all values except for rgba values
920
* with an alpha component.
921
* @return {number} The alpha value, from 0 to 1.
931
* Retrieve a PIE.Color instance for the given value. A shared singleton instance is returned for each unique value.
932
* @param {string} val The CSS string representing the color. It is assumed that this will already have
933
* been validated as a valid color syntax.
935
PIE.getColor = function(val) {
936
return instances[ val ] || ( instances[ val ] = new Color( val ) );
941
* A tokenizer for CSS value strings.
943
* @param {string} css The CSS value string
945
PIE.Tokenizer = (function() {
946
function Tokenizer( css ) {
954
* Enumeration of token type constants.
957
var Type = Tokenizer.Type = {
975
* @param {number} type The type of the token - see PIE.Tokenizer.Type
976
* @param {string} value The value of the token
978
Tokenizer.Token = function( type, value ) {
979
this.tokenType = type;
980
this.tokenValue = value;
982
Tokenizer.Token.prototype = {
983
isLength: function() {
984
return this.tokenType & Type.LENGTH || ( this.tokenType & Type.NUMBER && this.tokenValue === '0' );
986
isLengthOrPercent: function() {
987
return this.isLength() || this.tokenType & Type.PERCENT;
991
Tokenizer.prototype = {
993
number: /^[\+\-]?(\d*\.)?\d+/,
994
url: /^url\(\s*("([^"]*)"|'([^']*)'|([!#$%&*-~]*))\s*\)/i,
995
ident: /^\-?[_a-z][\w-]*/i,
996
string: /^("([^"]*)"|'([^']*)')/,
999
hashColor: /^#([\da-f]{6}|[\da-f]{3})/i,
1002
'px': Type.LENGTH, 'em': Type.LENGTH, 'ex': Type.LENGTH,
1003
'mm': Type.LENGTH, 'cm': Type.LENGTH, 'in': Type.LENGTH,
1004
'pt': Type.LENGTH, 'pc': Type.LENGTH,
1005
'deg': Type.ANGLE, 'rad': Type.ANGLE, 'grad': Type.ANGLE
1009
'rgb': 1, 'rgba': 1, 'hsl': 1, 'hsla': 1
1014
* Advance to and return the next token in the CSS string. If the end of the CSS string has
1015
* been reached, null will be returned.
1016
* @param {boolean} forget - if true, the token will not be stored for the purposes of backtracking with prev().
1017
* @return {PIE.Tokenizer.Token}
1019
next: function( forget ) {
1020
var css, ch, firstChar, match, val,
1023
function newToken( type, value ) {
1024
var tok = new Tokenizer.Token( type, value );
1026
me.tokens.push( tok );
1031
function failure() {
1036
// In case we previously backed up, return the stored token in the next slot
1037
if( this.tokenIndex < this.tokens.length ) {
1038
return this.tokens[ this.tokenIndex++ ];
1041
// Move past leading whitespace characters
1042
while( this.whitespace.test( this.css.charAt( this.ch ) ) ) {
1045
if( this.ch >= this.css.length ) {
1050
css = this.css.substring( this.ch );
1051
firstChar = css.charAt( 0 );
1052
switch( firstChar ) {
1054
if( match = css.match( this.hashColor ) ) {
1055
this.ch += match[0].length;
1056
return newToken( Type.COLOR, match[0] );
1062
if( match = css.match( this.string ) ) {
1063
this.ch += match[0].length;
1064
return newToken( Type.STRING, match[2] || match[3] || '' );
1071
return newToken( Type.OPERATOR, firstChar );
1074
if( match = css.match( this.url ) ) {
1075
this.ch += match[0].length;
1076
return newToken( Type.URL, match[2] || match[3] || match[4] || '' );
1080
// Numbers and values starting with numbers
1081
if( match = css.match( this.number ) ) {
1083
this.ch += val.length;
1085
// Check if it is followed by a unit
1086
if( css.charAt( val.length ) === '%' ) {
1088
return newToken( Type.PERCENT, val + '%' );
1090
if( match = css.substring( val.length ).match( this.ident ) ) {
1092
this.ch += match[0].length;
1093
return newToken( this.unitTypes[ match[0].toLowerCase() ] || Type.DIMEN, val );
1097
return newToken( Type.NUMBER, val );
1101
if( match = css.match( this.ident ) ) {
1103
this.ch += val.length;
1106
if( val.toLowerCase() in PIE.Color.names || val === 'currentColor' || val === 'transparent' ) {
1107
return newToken( Type.COLOR, val );
1111
if( css.charAt( val.length ) === '(' ) {
1114
// Color values in function format: rgb, rgba, hsl, hsla
1115
if( val.toLowerCase() in this.colorFunctions ) {
1116
function isNum( tok ) {
1117
return tok && tok.tokenType & Type.NUMBER;
1119
function isNumOrPct( tok ) {
1120
return tok && ( tok.tokenType & ( Type.NUMBER | Type.PERCENT ) );
1122
function isValue( tok, val ) {
1123
return tok && tok.tokenValue === val;
1126
return me.next( 1 );
1129
if( ( val.charAt(0) === 'r' ? isNumOrPct( next() ) : isNum( next() ) ) &&
1130
isValue( next(), ',' ) &&
1131
isNumOrPct( next() ) &&
1132
isValue( next(), ',' ) &&
1133
isNumOrPct( next() ) &&
1134
( val === 'rgb' || val === 'hsa' || (
1135
isValue( next(), ',' ) &&
1138
isValue( next(), ')' ) ) {
1139
return newToken( Type.COLOR, this.css.substring( ch, this.ch ) );
1144
return newToken( Type.FUNCTION, val );
1148
return newToken( Type.IDENT, val );
1151
// Standalone character
1153
return newToken( Type.CHARACTER, firstChar );
1157
* Determine whether there is another token
1160
hasNext: function() {
1161
var next = this.next();
1167
* Back up and return the previous token
1168
* @return {PIE.Tokenizer.Token}
1171
return this.tokens[ this.tokenIndex-- - 2 ];
1175
* Retrieve all the tokens in the CSS string
1176
* @return {Array.<PIE.Tokenizer.Token>}
1179
while( this.next() ) {}
1184
* Return a list of tokens from the current position until the given function returns
1185
* true. The final token will not be included in the list.
1186
* @param {function():boolean} func - test function
1187
* @param {boolean} require - if true, then if the end of the CSS string is reached
1188
* before the test function returns true, null will be returned instead of the
1189
* tokens that have been found so far.
1190
* @return {Array.<PIE.Tokenizer.Token>}
1192
until: function( func, require ) {
1193
var list = [], t, hit;
1194
while( t = this.next() ) {
1202
return require && !hit ? null : list;
1208
* Handles calculating, caching, and detecting changes to size and position of the element.
1210
* @param {Element} el the target element
1212
PIE.BoundsInfo = function( el ) {
1213
this.targetElement = el;
1215
PIE.BoundsInfo.prototype = {
1219
positionChanged: function() {
1220
var last = this._lastBounds,
1222
return !last || ( ( bounds = this.getBounds() ) && ( last.x !== bounds.x || last.y !== bounds.y ) );
1225
sizeChanged: function() {
1226
var last = this._lastBounds,
1228
return !last || ( ( bounds = this.getBounds() ) && ( last.w !== bounds.w || last.h !== bounds.h ) );
1231
getLiveBounds: function() {
1232
var el = this.targetElement,
1233
rect = el.getBoundingClientRect(),
1234
isIE9 = PIE.ieDocMode === 9,
1235
isIE7 = PIE.ieVersion === 7,
1236
width = rect.right - rect.left;
1240
// In some cases scrolling the page will cause IE9 to report incorrect dimensions
1241
// in the rect returned by getBoundingClientRect, so we must query offsetWidth/Height
1242
// instead. Also IE7 is inconsistent in using logical vs. device pixels in measurements
1243
// so we must calculate the ratio and use it in certain places as a position adjustment.
1244
w: isIE9 || isIE7 ? el.offsetWidth : width,
1245
h: isIE9 || isIE7 ? el.offsetHeight : rect.bottom - rect.top,
1246
logicalZoomRatio: ( isIE7 && width ) ? el.offsetWidth / width : 1
1250
getBounds: function() {
1251
return this._locked ?
1252
( this._lockedBounds || ( this._lockedBounds = this.getLiveBounds() ) ) :
1253
this.getLiveBounds();
1256
hasBeenQueried: function() {
1257
return !!this._lastBounds;
1264
unlock: function() {
1265
if( !--this._locked ) {
1266
if( this._lockedBounds ) this._lastBounds = this._lockedBounds;
1267
this._lockedBounds = null;
1274
function cacheWhenLocked( fn ) {
1275
var uid = PIE.Util.getUID( fn );
1277
if( this._locked ) {
1278
var cache = this._lockedValues || ( this._lockedValues = {} );
1279
return ( uid in cache ) ? cache[ uid ] : ( cache[ uid ] = fn.call( this ) );
1281
return fn.call( this );
1287
PIE.StyleInfoBase = {
1292
* Create a new StyleInfo class, with the standard constructor, and augmented by
1293
* the StyleInfoBase's members.
1296
newStyleInfo: function( proto ) {
1297
function StyleInfo( el ) {
1298
this.targetElement = el;
1299
this._lastCss = this.getCss();
1301
PIE.Util.merge( StyleInfo.prototype, PIE.StyleInfoBase, proto );
1302
StyleInfo._propsCache = {};
1307
* Get an object representation of the target CSS style, caching it for each unique
1311
getProps: function() {
1312
var css = this.getCss(),
1313
cache = this.constructor._propsCache;
1314
return css ? ( css in cache ? cache[ css ] : ( cache[ css ] = this.parseCss( css ) ) ) : null;
1318
* Get the raw CSS value for the target style
1321
getCss: cacheWhenLocked( function() {
1322
var el = this.targetElement,
1323
ctor = this.constructor,
1325
cs = el.currentStyle,
1326
cssProp = this.cssProperty,
1327
styleProp = this.styleProperty,
1328
prefixedCssProp = ctor._prefixedCssProp || ( ctor._prefixedCssProp = PIE.CSS_PREFIX + cssProp ),
1329
prefixedStyleProp = ctor._prefixedStyleProp || ( ctor._prefixedStyleProp = PIE.STYLE_PREFIX + styleProp.charAt(0).toUpperCase() + styleProp.substring(1) );
1330
return s[ prefixedStyleProp ] || cs.getAttribute( prefixedCssProp ) || s[ styleProp ] || cs.getAttribute( cssProp );
1334
* Determine whether the target CSS style is active.
1337
isActive: cacheWhenLocked( function() {
1338
return !!this.getProps();
1342
* Determine whether the target CSS style has changed since the last time it was used.
1345
changed: cacheWhenLocked( function() {
1346
var currentCss = this.getCss(),
1347
changed = currentCss !== this._lastCss;
1348
this._lastCss = currentCss;
1352
cacheWhenLocked: cacheWhenLocked,
1358
unlock: function() {
1359
if( !--this._locked ) {
1360
delete this._lockedValues;
1366
* Handles parsing, caching, and detecting changes to background (and -pie-background) CSS
1368
* @param {Element} el the target element
1370
PIE.BackgroundStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1372
cssProperty: PIE.CSS_PREFIX + 'background',
1373
styleProperty: PIE.STYLE_PREFIX + 'Background',
1375
attachIdents: { 'scroll':1, 'fixed':1, 'local':1 },
1376
repeatIdents: { 'repeat-x':1, 'repeat-y':1, 'repeat':1, 'no-repeat':1 },
1377
originAndClipIdents: { 'padding-box':1, 'border-box':1, 'content-box':1 },
1378
positionIdents: { 'top':1, 'right':1, 'bottom':1, 'left':1, 'center':1 },
1379
sizeIdents: { 'contain':1, 'cover':1 },
1381
CLIP: 'backgroundClip',
1382
COLOR: 'backgroundColor',
1383
IMAGE: 'backgroundImage',
1384
ORIGIN: 'backgroundOrigin',
1385
POSITION: 'backgroundPosition',
1386
REPEAT: 'backgroundRepeat',
1387
SIZE: 'backgroundSize'
1391
* For background styles, we support the -pie-background property but fall back to the standard
1392
* backround* properties. The reason we have to use the prefixed version is that IE natively
1393
* parses the standard properties and if it sees something it doesn't know how to parse, for example
1394
* multiple values or gradient definitions, it will throw that away and not make it available through
1397
* Format of return object:
1399
* color: <PIE.Color>,
1403
* imgUrl: 'image.png',
1404
* imgRepeat: <'no-repeat' | 'repeat-x' | 'repeat-y' | 'repeat'>,
1405
* bgPosition: <PIE.BgPosition>,
1406
* bgAttachment: <'scroll' | 'fixed' | 'local'>,
1407
* bgOrigin: <'border-box' | 'padding-box' | 'content-box'>,
1408
* bgClip: <'border-box' | 'padding-box'>,
1409
* bgSize: <PIE.BgSize>,
1410
* origString: 'url(img.png) no-repeat top left'
1413
* imgType: 'linear-gradient',
1414
* gradientStart: <PIE.BgPosition>,
1415
* angle: <PIE.Angle>,
1417
* { color: <PIE.Color>, offset: <PIE.Length> },
1418
* { color: <PIE.Color>, offset: <PIE.Length> }, ...
1423
* @param {String} css
1426
parseCss: function( css ) {
1427
var el = this.targetElement,
1428
cs = el.currentStyle,
1429
tokenizer, token, image,
1430
tok_type = PIE.Tokenizer.Type,
1431
type_operator = tok_type.OPERATOR,
1432
type_ident = tok_type.IDENT,
1433
type_color = tok_type.COLOR,
1436
positionIdents = this.positionIdents,
1437
gradient, stop, width, height,
1438
props = { bgImages: [] };
1440
function isBgPosToken( token ) {
1441
return token && token.isLengthOrPercent() || ( token.tokenType & type_ident && token.tokenValue in positionIdents );
1444
function sizeToken( token ) {
1445
return token && ( ( token.isLengthOrPercent() && PIE.getLength( token.tokenValue ) ) || ( token.tokenValue === 'auto' && 'auto' ) );
1448
// If the CSS3-specific -pie-background property is present, parse it
1449
if( this.getCss3() ) {
1450
tokenizer = new PIE.Tokenizer( css );
1453
while( token = tokenizer.next() ) {
1454
tokType = token.tokenType;
1455
tokVal = token.tokenValue;
1457
if( !image.imgType && tokType & tok_type.FUNCTION && tokVal === 'linear-gradient' ) {
1458
gradient = { stops: [], imgType: tokVal };
1460
while( token = tokenizer.next() ) {
1461
tokType = token.tokenType;
1462
tokVal = token.tokenValue;
1464
// If we reached the end of the function and had at least 2 stops, flush the info
1465
if( tokType & tok_type.CHARACTER && tokVal === ')' ) {
1467
gradient.stops.push( stop );
1469
if( gradient.stops.length > 1 ) {
1470
PIE.Util.merge( image, gradient );
1475
// Color stop - must start with color
1476
if( tokType & type_color ) {
1477
// if we already have an angle/position, make sure that the previous token was a comma
1478
if( gradient.angle || gradient.gradientStart ) {
1479
token = tokenizer.prev();
1480
if( token.tokenType !== type_operator ) {
1487
color: PIE.getColor( tokVal )
1489
// check for offset following color
1490
token = tokenizer.next();
1491
if( token.isLengthOrPercent() ) {
1492
stop.offset = PIE.getLength( token.tokenValue );
1497
// Angle - can only appear in first spot
1498
else if( tokType & tok_type.ANGLE && !gradient.angle && !stop.color && !gradient.stops.length ) {
1499
gradient.angle = new PIE.Angle( token.tokenValue );
1501
else if( isBgPosToken( token ) && !gradient.gradientStart && !stop.color && !gradient.stops.length ) {
1503
gradient.gradientStart = new PIE.BgPosition(
1504
tokenizer.until( function( t ) {
1505
return !isBgPosToken( t );
1509
else if( tokType & type_operator && tokVal === ',' ) {
1511
gradient.stops.push( stop );
1516
// Found something we didn't recognize; fail without adding image
1521
else if( !image.imgType && tokType & tok_type.URL ) {
1522
image.imgUrl = tokVal;
1523
image.imgType = 'image';
1525
else if( isBgPosToken( token ) && !image.bgPosition ) {
1527
image.bgPosition = new PIE.BgPosition(
1528
tokenizer.until( function( t ) {
1529
return !isBgPosToken( t );
1533
else if( tokType & type_ident ) {
1534
if( tokVal in this.repeatIdents && !image.imgRepeat ) {
1535
image.imgRepeat = tokVal;
1537
else if( tokVal in this.originAndClipIdents && !image.bgOrigin ) {
1538
image.bgOrigin = tokVal;
1539
if( ( token = tokenizer.next() ) && ( token.tokenType & type_ident ) &&
1540
token.tokenValue in this.originAndClipIdents ) {
1541
image.bgClip = token.tokenValue;
1543
image.bgClip = tokVal;
1547
else if( tokVal in this.attachIdents && !image.bgAttachment ) {
1548
image.bgAttachment = tokVal;
1554
else if( tokType & type_color && !props.color ) {
1555
props.color = PIE.getColor( tokVal );
1557
else if( tokType & type_operator && tokVal === '/' && !image.bgSize && image.bgPosition ) {
1559
token = tokenizer.next();
1560
if( token.tokenType & type_ident && token.tokenValue in this.sizeIdents ) {
1561
image.bgSize = new PIE.BgSize( token.tokenValue );
1563
else if( width = sizeToken( token ) ) {
1564
height = sizeToken( tokenizer.next() );
1569
image.bgSize = new PIE.BgSize( width, height );
1576
else if( tokType & type_operator && tokVal === ',' && image.imgType ) {
1577
image.origString = css.substring( beginCharIndex, tokenizer.ch - 1 );
1578
beginCharIndex = tokenizer.ch;
1579
props.bgImages.push( image );
1583
// Found something unrecognized; chuck everything
1589
if( image.imgType ) {
1590
image.origString = css.substring( beginCharIndex );
1591
props.bgImages.push( image );
1595
// Otherwise, use the standard background properties; let IE give us the values rather than parsing them
1597
this.withActualBg( PIE.ieDocMode < 9 ?
1599
var propNames = this.propertyNames,
1600
posX = cs[propNames.POSITION + 'X'],
1601
posY = cs[propNames.POSITION + 'Y'],
1602
img = cs[propNames.IMAGE],
1603
color = cs[propNames.COLOR];
1605
if( color !== 'transparent' ) {
1606
props.color = PIE.getColor( color )
1608
if( img !== 'none' ) {
1609
props.bgImages = [ {
1611
imgUrl: new PIE.Tokenizer( img ).next().tokenValue,
1612
imgRepeat: cs[propNames.REPEAT],
1613
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( posX + ' ' + posY ).all() )
1618
var propNames = this.propertyNames,
1619
splitter = /\s*,\s*/,
1620
images = cs[propNames.IMAGE].split( splitter ),
1621
color = cs[propNames.COLOR],
1622
repeats, positions, origins, clips, sizes, i, len, image, sizeParts;
1624
if( color !== 'transparent' ) {
1625
props.color = PIE.getColor( color )
1628
len = images.length;
1629
if( len && images[0] !== 'none' ) {
1630
repeats = cs[propNames.REPEAT].split( splitter );
1631
positions = cs[propNames.POSITION].split( splitter );
1632
origins = cs[propNames.ORIGIN].split( splitter );
1633
clips = cs[propNames.CLIP].split( splitter );
1634
sizes = cs[propNames.SIZE].split( splitter );
1636
props.bgImages = [];
1637
for( i = 0; i < len; i++ ) {
1638
image = images[ i ];
1639
if( image && image !== 'none' ) {
1640
sizeParts = sizes[i].split( ' ' );
1641
props.bgImages.push( {
1642
origString: image + ' ' + repeats[ i ] + ' ' + positions[ i ] + ' / ' + sizes[ i ] + ' ' +
1643
origins[ i ] + ' ' + clips[ i ],
1645
imgUrl: new PIE.Tokenizer( image ).next().tokenValue,
1646
imgRepeat: repeats[ i ],
1647
bgPosition: new PIE.BgPosition( new PIE.Tokenizer( positions[ i ] ).all() ),
1648
bgOrigin: origins[ i ],
1650
bgSize: new PIE.BgSize( sizeParts[ 0 ], sizeParts[ 1 ] )
1659
return ( props.color || props.bgImages[0] ) ? props : null;
1663
* Execute a function with the actual background styles (not overridden with runtimeStyle
1664
* properties set by the renderers) available via currentStyle.
1667
withActualBg: function( fn ) {
1668
var isIE9 = PIE.ieDocMode > 8,
1669
propNames = this.propertyNames,
1670
rs = this.targetElement.runtimeStyle,
1671
rsImage = rs[propNames.IMAGE],
1672
rsColor = rs[propNames.COLOR],
1673
rsRepeat = rs[propNames.REPEAT],
1674
rsClip, rsOrigin, rsSize, rsPosition, ret;
1676
if( rsImage ) rs[propNames.IMAGE] = '';
1677
if( rsColor ) rs[propNames.COLOR] = '';
1678
if( rsRepeat ) rs[propNames.REPEAT] = '';
1680
rsClip = rs[propNames.CLIP];
1681
rsOrigin = rs[propNames.ORIGIN];
1682
rsPosition = rs[propNames.POSITION];
1683
rsSize = rs[propNames.SIZE];
1684
if( rsClip ) rs[propNames.CLIP] = '';
1685
if( rsOrigin ) rs[propNames.ORIGIN] = '';
1686
if( rsPosition ) rs[propNames.POSITION] = '';
1687
if( rsSize ) rs[propNames.SIZE] = '';
1690
ret = fn.call( this );
1692
if( rsImage ) rs[propNames.IMAGE] = rsImage;
1693
if( rsColor ) rs[propNames.COLOR] = rsColor;
1694
if( rsRepeat ) rs[propNames.REPEAT] = rsRepeat;
1696
if( rsClip ) rs[propNames.CLIP] = rsClip;
1697
if( rsOrigin ) rs[propNames.ORIGIN] = rsOrigin;
1698
if( rsPosition ) rs[propNames.POSITION] = rsPosition;
1699
if( rsSize ) rs[propNames.SIZE] = rsSize;
1705
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
1706
return this.getCss3() ||
1707
this.withActualBg( function() {
1708
var cs = this.targetElement.currentStyle,
1709
propNames = this.propertyNames;
1710
return cs[propNames.COLOR] + ' ' + cs[propNames.IMAGE] + ' ' + cs[propNames.REPEAT] + ' ' +
1711
cs[propNames.POSITION + 'X'] + ' ' + cs[propNames.POSITION + 'Y'];
1715
getCss3: PIE.StyleInfoBase.cacheWhenLocked( function() {
1716
var el = this.targetElement;
1717
return el.style[ this.styleProperty ] || el.currentStyle.getAttribute( this.cssProperty );
1721
* Tests if style.PiePngFix or the -pie-png-fix property is set to true in IE6.
1723
isPngFix: function() {
1725
if( PIE.ieVersion < 7 ) {
1726
el = this.targetElement;
1727
val = ( '' + ( el.style[ PIE.STYLE_PREFIX + 'PngFix' ] || el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'png-fix' ) ) === 'true' );
1733
* The isActive logic is slightly different, because getProps() always returns an object
1734
* even if it is just falling back to the native background properties. But we only want
1735
* to report is as being "active" if either the -pie-background override property is present
1736
* and parses successfully or '-pie-png-fix' is set to true in IE6.
1738
isActive: PIE.StyleInfoBase.cacheWhenLocked( function() {
1739
return (this.getCss3() || this.isPngFix()) && !!this.getProps();
1743
* Handles parsing, caching, and detecting changes to border CSS
1745
* @param {Element} el the target element
1747
PIE.BorderStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1749
sides: [ 'Top', 'Right', 'Bottom', 'Left' ],
1756
parseCss: function( css ) {
1765
this.withActualBorder( function() {
1766
var el = this.targetElement,
1767
cs = el.currentStyle,
1769
style, color, width, lastStyle, lastColor, lastWidth, side, ltr;
1770
for( ; i < 4; i++ ) {
1771
side = this.sides[ i ];
1773
ltr = side.charAt(0).toLowerCase();
1774
style = s[ ltr ] = cs[ 'border' + side + 'Style' ];
1775
color = cs[ 'border' + side + 'Color' ];
1776
width = cs[ 'border' + side + 'Width' ];
1779
if( style !== lastStyle ) { stylesSame = false; }
1780
if( color !== lastColor ) { colorsSame = false; }
1781
if( width !== lastWidth ) { widthsSame = false; }
1787
c[ ltr ] = PIE.getColor( color );
1789
width = w[ ltr ] = PIE.getLength( s[ ltr ] === 'none' ? '0' : ( this.namedWidths[ width ] || width ) );
1790
if( width.pixels( this.targetElement ) > 0 ) {
1800
widthsSame: widthsSame,
1801
colorsSame: colorsSame,
1802
stylesSame: stylesSame
1806
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
1807
var el = this.targetElement,
1808
cs = el.currentStyle,
1811
// Don't redraw or hide borders for cells in border-collapse:collapse tables
1812
if( !( el.tagName in PIE.tableCellTags && el.offsetParent.currentStyle.borderCollapse === 'collapse' ) ) {
1813
this.withActualBorder( function() {
1814
css = cs.borderWidth + '|' + cs.borderStyle + '|' + cs.borderColor;
1821
* Execute a function with the actual border styles (not overridden with runtimeStyle
1822
* properties set by the renderers) available via currentStyle.
1825
withActualBorder: function( fn ) {
1826
var rs = this.targetElement.runtimeStyle,
1827
rsWidth = rs.borderWidth,
1828
rsColor = rs.borderColor,
1831
if( rsWidth ) rs.borderWidth = '';
1832
if( rsColor ) rs.borderColor = '';
1834
ret = fn.call( this );
1836
if( rsWidth ) rs.borderWidth = rsWidth;
1837
if( rsColor ) rs.borderColor = rsColor;
1844
* Handles parsing, caching, and detecting changes to border-radius CSS
1846
* @param {Element} el the target element
1850
PIE.BorderRadiusStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1852
cssProperty: 'border-radius',
1853
styleProperty: 'borderRadius',
1855
parseCss: function( css ) {
1857
tokenizer, token, length,
1861
tokenizer = new PIE.Tokenizer( css );
1863
function collectLengths() {
1865
while( ( token = tokenizer.next() ) && token.isLengthOrPercent() ) {
1866
length = PIE.getLength( token.tokenValue );
1867
num = length.getNumber();
1876
return arr.length > 0 && arr.length < 5 ? {
1878
'tr': arr[1] || arr[0],
1879
'br': arr[2] || arr[0],
1880
'bl': arr[3] || arr[1] || arr[0]
1884
// Grab the initial sequence of lengths
1885
if( x = collectLengths() ) {
1886
// See if there is a slash followed by more lengths, for the y-axis radii
1888
if( token.tokenType & PIE.Tokenizer.Type.OPERATOR && token.tokenValue === '/' ) {
1889
y = collectLengths();
1895
// Treat all-zero values the same as no value
1896
if( hasNonZero && x && y ) {
1897
p = { x: x, y : y };
1906
var zero = PIE.getLength( '0' ),
1907
zeros = { 'tl': zero, 'tr': zero, 'br': zero, 'bl': zero };
1908
PIE.BorderRadiusStyleInfo.ALL_ZERO = { x: zeros, y: zeros };
1911
* Handles parsing, caching, and detecting changes to border-image CSS
1913
* @param {Element} el the target element
1915
PIE.BorderImageStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
1917
cssProperty: 'border-image',
1918
styleProperty: 'borderImage',
1920
repeatIdents: { 'stretch':1, 'round':1, 'repeat':1, 'space':1 },
1922
parseCss: function( css ) {
1923
var p = null, tokenizer, token, type, value,
1924
slices, widths, outsets,
1926
Type = PIE.Tokenizer.Type,
1928
NUMBER = Type.NUMBER,
1929
PERCENT = Type.PERCENT;
1932
tokenizer = new PIE.Tokenizer( css );
1935
function isSlash( token ) {
1936
return token && ( token.tokenType & Type.OPERATOR ) && ( token.tokenValue === '/' );
1939
function isFillIdent( token ) {
1940
return token && ( token.tokenType & IDENT ) && ( token.tokenValue === 'fill' );
1943
function collectSlicesEtc() {
1944
slices = tokenizer.until( function( tok ) {
1945
return !( tok.tokenType & ( NUMBER | PERCENT ) );
1948
if( isFillIdent( tokenizer.next() ) && !p.fill ) {
1954
if( isSlash( tokenizer.next() ) ) {
1956
widths = tokenizer.until( function( token ) {
1957
return !token.isLengthOrPercent() && !( ( token.tokenType & IDENT ) && token.tokenValue === 'auto' );
1960
if( isSlash( tokenizer.next() ) ) {
1962
outsets = tokenizer.until( function( token ) {
1963
return !token.isLength();
1971
while( token = tokenizer.next() ) {
1972
type = token.tokenType;
1973
value = token.tokenValue;
1975
// Numbers and/or 'fill' keyword: slice values. May be followed optionally by width values, followed optionally by outset values
1976
if( type & ( NUMBER | PERCENT ) && !slices ) {
1980
else if( isFillIdent( token ) && !p.fill ) {
1985
// Idents: one or values for 'repeat'
1986
else if( ( type & IDENT ) && this.repeatIdents[value] && !p.repeat ) {
1987
p.repeat = { h: value };
1988
if( token = tokenizer.next() ) {
1989
if( ( token.tokenType & IDENT ) && this.repeatIdents[token.tokenValue] ) {
1990
p.repeat.v = token.tokenValue;
1998
else if( ( type & Type.URL ) && !p.src ) {
2002
// Found something unrecognized; exit.
2008
// Validate what we collected
2009
if( !p.src || !slices || slices.length < 1 || slices.length > 4 ||
2010
( widths && widths.length > 4 ) || ( slashCount === 1 && widths.length < 1 ) ||
2011
( outsets && outsets.length > 4 ) || ( slashCount === 2 && outsets.length < 1 ) ) {
2015
// Fill in missing values
2017
p.repeat = { h: 'stretch' };
2020
p.repeat.v = p.repeat.h;
2023
function distributeSides( tokens, convertFn ) {
2025
't': convertFn( tokens[0] ),
2026
'r': convertFn( tokens[1] || tokens[0] ),
2027
'b': convertFn( tokens[2] || tokens[0] ),
2028
'l': convertFn( tokens[3] || tokens[1] || tokens[0] )
2032
p.slice = distributeSides( slices, function( tok ) {
2033
return PIE.getLength( ( tok.tokenType & NUMBER ) ? tok.tokenValue + 'px' : tok.tokenValue );
2036
if( widths && widths[0] ) {
2037
p.widths = distributeSides( widths, function( tok ) {
2038
return tok.isLengthOrPercent() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
2042
if( outsets && outsets[0] ) {
2043
p.outset = distributeSides( outsets, function( tok ) {
2044
return tok.isLength() ? PIE.getLength( tok.tokenValue ) : tok.tokenValue;
2053
* Handles parsing, caching, and detecting changes to box-shadow CSS
2055
* @param {Element} el the target element
2057
PIE.BoxShadowStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
2059
cssProperty: 'box-shadow',
2060
styleProperty: 'boxShadow',
2062
parseCss: function( css ) {
2064
getLength = PIE.getLength,
2065
Type = PIE.Tokenizer.Type,
2069
tokenizer = new PIE.Tokenizer( css );
2070
props = { outset: [], inset: [] };
2072
function parseItem() {
2073
var token, type, value, color, lengths, inset, len;
2075
while( token = tokenizer.next() ) {
2076
value = token.tokenValue;
2077
type = token.tokenType;
2079
if( type & Type.OPERATOR && value === ',' ) {
2082
else if( token.isLength() && !lengths ) {
2084
lengths = tokenizer.until( function( token ) {
2085
return !token.isLength();
2088
else if( type & Type.COLOR && !color ) {
2091
else if( type & Type.IDENT && value === 'inset' && !inset ) {
2094
else { //encountered an unrecognized token; fail.
2099
len = lengths && lengths.length;
2100
if( len > 1 && len < 5 ) {
2101
( inset ? props.inset : props.outset ).push( {
2102
xOffset: getLength( lengths[0].tokenValue ),
2103
yOffset: getLength( lengths[1].tokenValue ),
2104
blur: getLength( lengths[2] ? lengths[2].tokenValue : '0' ),
2105
spread: getLength( lengths[3] ? lengths[3].tokenValue : '0' ),
2106
color: PIE.getColor( color || 'currentColor' )
2113
while( parseItem() ) {}
2116
return props && ( props.inset.length || props.outset.length ) ? props : null;
2120
* Retrieves the state of the element's visibility and display
2122
* @param {Element} el the target element
2124
PIE.VisibilityStyleInfo = PIE.StyleInfoBase.newStyleInfo( {
2126
getCss: PIE.StyleInfoBase.cacheWhenLocked( function() {
2127
var cs = this.targetElement.currentStyle;
2128
return cs.visibility + '|' + cs.display;
2131
parseCss: function() {
2132
var el = this.targetElement,
2133
rs = el.runtimeStyle,
2134
cs = el.currentStyle,
2135
rsVis = rs.visibility,
2139
csVis = cs.visibility;
2140
rs.visibility = rsVis;
2143
visible: csVis !== 'hidden',
2144
displayed: cs.display !== 'none'
2149
* Always return false for isActive, since this property alone will not trigger
2150
* a renderer to do anything.
2152
isActive: function() {
2157
PIE.RendererBase = {
2160
* Create a new Renderer class, with the standard constructor, and augmented by
2161
* the RendererBase's members.
2164
newRenderer: function( proto ) {
2165
function Renderer( el, boundsInfo, styleInfos, parent ) {
2166
this.targetElement = el;
2167
this.boundsInfo = boundsInfo;
2168
this.styleInfos = styleInfos;
2169
this.parent = parent;
2171
PIE.Util.merge( Renderer.prototype, PIE.RendererBase, proto );
2176
* Flag indicating the element has already been positioned at least once.
2179
isPositioned: false,
2182
* Determine if the renderer needs to be updated
2185
needsUpdate: function() {
2190
* Run any preparation logic that would affect the main update logic of this
2191
* renderer or any of the other renderers, e.g. things that might affect the
2192
* element's size or style properties.
2194
prepareUpdate: PIE.emptyFn,
2197
* Tell the renderer to update based on modified properties
2199
updateProps: function() {
2201
if( this.isActive() ) {
2207
* Tell the renderer to update based on modified element position
2209
updatePos: function() {
2210
this.isPositioned = true;
2214
* Tell the renderer to update based on modified element dimensions
2216
updateSize: function() {
2217
if( this.isActive() ) {
2226
* Add a layer element, with the given z-order index, to the renderer's main box element. We can't use
2227
* z-index because that breaks when the root rendering box's z-index is 'auto' in IE8+ standards mode.
2228
* So instead we make sure they are inserted into the DOM in the correct order.
2229
* @param {number} index
2230
* @param {Element} el
2232
addLayer: function( index, el ) {
2233
this.removeLayer( index );
2234
for( var layers = this._layers || ( this._layers = [] ), i = index + 1, len = layers.length, layer; i < len; i++ ) {
2241
this.getBox().insertBefore( el, layer || null );
2245
* Retrieve a layer element by its index, or null if not present
2246
* @param {number} index
2249
getLayer: function( index ) {
2250
var layers = this._layers;
2251
return layers && layers[index] || null;
2255
* Remove a layer element by its index
2256
* @param {number} index
2258
removeLayer: function( index ) {
2259
var layer = this.getLayer( index ),
2261
if( layer && box ) {
2262
box.removeChild( layer );
2263
this._layers[index] = null;
2269
* Get a VML shape by name, creating it if necessary.
2270
* @param {string} name A name identifying the element
2271
* @param {string=} subElName If specified a subelement of the shape will be created with this tag name
2272
* @param {Element} parent The parent element for the shape; will be ignored if 'group' is specified
2273
* @param {number=} group If specified, an ordinal group for the shape. 1 or greater. Groups are rendered
2274
* using container elements in the correct order, to get correct z stacking without z-index.
2276
getShape: function( name, subElName, parent, group ) {
2277
var shapes = this._shapes || ( this._shapes = {} ),
2278
shape = shapes[ name ],
2282
shape = shapes[ name ] = PIE.Util.createVmlElement( 'shape' );
2284
shape.appendChild( shape[ subElName ] = PIE.Util.createVmlElement( subElName ) );
2288
parent = this.getLayer( group );
2290
this.addLayer( group, doc.createElement( 'group' + group ) );
2291
parent = this.getLayer( group );
2295
parent.appendChild( shape );
2298
s.position = 'absolute';
2300
s['behavior'] = 'url(#default#VML)';
2306
* Delete a named shape which was created by getShape(). Returns true if a shape with the
2307
* given name was found and deleted, or false if there was no shape of that name.
2308
* @param {string} name
2311
deleteShape: function( name ) {
2312
var shapes = this._shapes,
2313
shape = shapes && shapes[ name ];
2315
shape.parentNode.removeChild( shape );
2316
delete shapes[ name ];
2323
* For a given set of border radius length/percentage values, convert them to concrete pixel
2324
* values based on the current size of the target element.
2325
* @param {Object} radii
2328
getRadiiPixels: function( radii ) {
2329
var el = this.targetElement,
2330
bounds = this.boundsInfo.getBounds(),
2333
tlX, tlY, trX, trY, brX, brY, blX, blY, f;
2335
tlX = radii.x['tl'].pixels( el, w );
2336
tlY = radii.y['tl'].pixels( el, h );
2337
trX = radii.x['tr'].pixels( el, w );
2338
trY = radii.y['tr'].pixels( el, h );
2339
brX = radii.x['br'].pixels( el, w );
2340
brY = radii.y['br'].pixels( el, h );
2341
blX = radii.x['bl'].pixels( el, w );
2342
blY = radii.y['bl'].pixels( el, h );
2344
// If any corner ellipses overlap, reduce them all by the appropriate factor. This formula
2345
// is taken straight from the CSS3 Backgrounds and Borders spec.
2380
* Return the VML path string for the element's background box, with corners rounded.
2381
* @param {Object.<{t:number, r:number, b:number, l:number}>} shrink - if present, specifies number of
2382
* pixels to shrink the box path inward from the element's four sides.
2383
* @param {number=} mult If specified, all coordinates will be multiplied by this number
2384
* @param {Object=} radii If specified, this will be used for the corner radii instead of the properties
2385
* from this renderer's borderRadiusInfo object.
2386
* @return {string} the VML path
2388
getBoxPath: function( shrink, mult, radii ) {
2392
bounds = this.boundsInfo.getBounds(),
2393
w = bounds.w * mult,
2394
h = bounds.h * mult,
2395
radInfo = this.styleInfos.borderRadiusInfo,
2396
floor = Math.floor, ceil = Math.ceil,
2397
shrinkT = shrink ? shrink.t * mult : 0,
2398
shrinkR = shrink ? shrink.r * mult : 0,
2399
shrinkB = shrink ? shrink.b * mult : 0,
2400
shrinkL = shrink ? shrink.l * mult : 0,
2401
tlX, tlY, trX, trY, brX, brY, blX, blY;
2403
if( radii || radInfo.isActive() ) {
2404
r = this.getRadiiPixels( radii || radInfo.getProps() );
2406
tlX = r.x['tl'] * mult;
2407
tlY = r.y['tl'] * mult;
2408
trX = r.x['tr'] * mult;
2409
trY = r.y['tr'] * mult;
2410
brX = r.x['br'] * mult;
2411
brY = r.y['br'] * mult;
2412
blX = r.x['bl'] * mult;
2413
blY = r.y['bl'] * mult;
2415
str = 'm' + floor( shrinkL ) + ',' + floor( tlY ) +
2416
'qy' + floor( tlX ) + ',' + floor( shrinkT ) +
2417
'l' + ceil( w - trX ) + ',' + floor( shrinkT ) +
2418
'qx' + ceil( w - shrinkR ) + ',' + floor( trY ) +
2419
'l' + ceil( w - shrinkR ) + ',' + ceil( h - brY ) +
2420
'qy' + ceil( w - brX ) + ',' + ceil( h - shrinkB ) +
2421
'l' + floor( blX ) + ',' + ceil( h - shrinkB ) +
2422
'qx' + floor( shrinkL ) + ',' + ceil( h - blY ) + ' x e';
2424
// simplified path for non-rounded box
2425
str = 'm' + floor( shrinkL ) + ',' + floor( shrinkT ) +
2426
'l' + ceil( w - shrinkR ) + ',' + floor( shrinkT ) +
2427
'l' + ceil( w - shrinkR ) + ',' + ceil( h - shrinkB ) +
2428
'l' + floor( shrinkL ) + ',' + ceil( h - shrinkB ) +
2436
* Get the container element for the shapes, creating it if necessary.
2438
getBox: function() {
2439
var box = this.parent.getLayer( this.boxZIndex ), s;
2442
box = doc.createElement( this.boxName );
2444
s.position = 'absolute';
2446
this.parent.addLayer( this.boxZIndex, box );
2454
* Hide the actual border of the element. In IE7 and up we can just set its color to transparent;
2455
* however IE6 does not support transparent borders so we have to get tricky with it. Also, some elements
2456
* like form buttons require removing the border width altogether, so for those we increase the padding
2457
* by the border size.
2459
hideBorder: function() {
2460
var el = this.targetElement,
2461
cs = el.currentStyle,
2462
rs = el.runtimeStyle,
2464
isIE6 = PIE.ieVersion === 6,
2467
if( ( isIE6 && ( tag in PIE.childlessElements || tag === 'FIELDSET' ) ) ||
2468
tag === 'BUTTON' || ( tag === 'INPUT' && el.type in PIE.inputButtonTypes ) ) {
2469
rs.borderWidth = '';
2470
sides = this.styleInfos.borderInfo.sides;
2471
for( i = sides.length; i--; ) {
2473
rs[ 'padding' + side ] = '';
2474
rs[ 'padding' + side ] = ( PIE.getLength( cs[ 'padding' + side ] ) ).pixels( el ) +
2475
( PIE.getLength( cs[ 'border' + side + 'Width' ] ) ).pixels( el ) +
2476
( PIE.ieVersion !== 8 && i % 2 ? 1 : 0 ); //needs an extra horizontal pixel to counteract the extra "inner border" going away
2481
// Wrap all the element's children in a custom element, set the element to visiblity:hidden,
2482
// and set the wrapper element to visiblity:visible. This hides the outer element's decorations
2483
// (background and border) but displays all the contents.
2484
// TODO find a better way to do this that doesn't mess up the DOM parent-child relationship,
2485
// as this can interfere with other author scripts which add/modify/delete children. Also, this
2486
// won't work for elements which cannot take children, e.g. input/button/textarea/img/etc. Look into
2487
// using a compositor filter or some other filter which masks the border.
2488
if( el.childNodes.length !== 1 || el.firstChild.tagName !== 'ie6-mask' ) {
2489
var cont = doc.createElement( 'ie6-mask' ),
2490
s = cont.style, child;
2491
s.visibility = 'visible';
2493
while( child = el.firstChild ) {
2494
cont.appendChild( child );
2496
el.appendChild( cont );
2497
rs.visibility = 'hidden';
2501
rs.borderColor = 'transparent';
2505
unhideBorder: function() {
2511
* Destroy the rendered objects. This is a base implementation which handles common renderer
2512
* structures, but individual renderers may override as necessary.
2514
destroy: function() {
2515
this.parent.removeLayer( this.boxZIndex );
2516
delete this._shapes;
2517
delete this._layers;
2521
* Root renderer; creates the outermost container element and handles keeping it aligned
2522
* with the target element's size and position.
2523
* @param {Element} el The target element
2524
* @param {Object} styleInfos The StyleInfo objects
2526
PIE.RootRenderer = PIE.RendererBase.newRenderer( {
2528
isActive: function() {
2529
var children = this.childRenderers;
2530
for( var i in children ) {
2531
if( children.hasOwnProperty( i ) && children[ i ].isActive() ) {
2538
needsUpdate: function() {
2539
return this.styleInfos.visibilityInfo.changed();
2542
updatePos: function() {
2543
if( this.isActive() ) {
2544
var el = this.getPositioningElement(),
2548
tgtCS = el.currentStyle,
2549
tgtPos = tgtCS.position,
2551
s = this.getBox().style, cs,
2553
elBounds = this.boundsInfo.getBounds(),
2554
logicalZoomRatio = elBounds.logicalZoomRatio;
2556
if( tgtPos === 'fixed' && PIE.ieVersion > 6 ) {
2557
x = elBounds.x * logicalZoomRatio;
2558
y = elBounds.y * logicalZoomRatio;
2561
// Get the element's offsets from its nearest positioned ancestor. Uses
2562
// getBoundingClientRect for accuracy and speed.
2564
par = par.offsetParent;
2565
} while( par && ( par.currentStyle.position === 'static' ) );
2567
parRect = par.getBoundingClientRect();
2568
cs = par.currentStyle;
2569
x = ( elBounds.x - parRect.left ) * logicalZoomRatio - ( parseFloat(cs.borderLeftWidth) || 0 );
2570
y = ( elBounds.y - parRect.top ) * logicalZoomRatio - ( parseFloat(cs.borderTopWidth) || 0 );
2572
docEl = doc.documentElement;
2573
x = ( elBounds.x + docEl.scrollLeft - docEl.clientLeft ) * logicalZoomRatio;
2574
y = ( elBounds.y + docEl.scrollTop - docEl.clientTop ) * logicalZoomRatio;
2576
boxPos = 'absolute';
2579
s.position = boxPos;
2582
s.zIndex = tgtPos === 'static' ? -1 : tgtCS.zIndex;
2583
this.isPositioned = true;
2587
updateSize: PIE.emptyFn,
2589
updateVisibility: function() {
2590
var vis = this.styleInfos.visibilityInfo.getProps();
2591
this.getBox().style.display = ( vis.visible && vis.displayed ) ? '' : 'none';
2594
updateProps: function() {
2595
if( this.isActive() ) {
2596
this.updateVisibility();
2602
getPositioningElement: function() {
2603
var el = this.targetElement;
2604
return el.tagName in PIE.tableCellTags ? el.offsetParent : el;
2607
getBox: function() {
2608
var box = this._box, el;
2610
el = this.getPositioningElement();
2611
box = this._box = doc.createElement( 'css3-container' );
2612
box.style['direction'] = 'ltr'; //fix positioning bug in rtl environments
2614
this.updateVisibility();
2616
el.parentNode.insertBefore( box, el );
2621
finishUpdate: PIE.emptyFn,
2623
destroy: function() {
2624
var box = this._box, par;
2625
if( box && ( par = box.parentNode ) ) {
2626
par.removeChild( box );
2629
delete this._layers;
2634
* Renderer for element backgrounds.
2636
* @param {Element} el The target element
2637
* @param {Object} styleInfos The StyleInfo objects
2638
* @param {PIE.RootRenderer} parent
2640
PIE.BackgroundRenderer = PIE.RendererBase.newRenderer( {
2643
boxName: 'background',
2645
needsUpdate: function() {
2646
var si = this.styleInfos;
2647
return si.backgroundInfo.changed() || si.borderRadiusInfo.changed();
2650
isActive: function() {
2651
var si = this.styleInfos;
2652
return si.borderImageInfo.isActive() ||
2653
si.borderRadiusInfo.isActive() ||
2654
si.backgroundInfo.isActive() ||
2655
( si.boxShadowInfo.isActive() && si.boxShadowInfo.getProps().inset );
2662
var bounds = this.boundsInfo.getBounds();
2663
if( bounds.w && bounds.h ) {
2665
this.drawBgImages();
2670
* Draw the background color shape
2672
drawBgColor: function() {
2673
var props = this.styleInfos.backgroundInfo.getProps(),
2674
bounds = this.boundsInfo.getBounds(),
2675
el = this.targetElement,
2676
color = props && props.color,
2677
shape, w, h, s, alpha;
2679
if( color && color.alpha() > 0 ) {
2680
this.hideBackground();
2682
shape = this.getShape( 'bgColor', 'fill', this.getBox(), 1 );
2685
shape.stroked = false;
2686
shape.coordsize = w * 2 + ',' + h * 2;
2687
shape.coordorigin = '1,1';
2688
shape.path = this.getBoxPath( null, 2 );
2692
shape.fill.color = color.colorValue( el );
2694
alpha = color.alpha();
2696
shape.fill.opacity = alpha;
2699
this.deleteShape( 'bgColor' );
2704
* Draw all the background image layers
2706
drawBgImages: function() {
2707
var props = this.styleInfos.backgroundInfo.getProps(),
2708
bounds = this.boundsInfo.getBounds(),
2709
images = props && props.bgImages,
2710
img, shape, w, h, s, i;
2713
this.hideBackground();
2721
shape = this.getShape( 'bgImage' + i, 'fill', this.getBox(), 2 );
2723
shape.stroked = false;
2724
shape.fill.type = 'tile';
2725
shape.fillcolor = 'none';
2726
shape.coordsize = w * 2 + ',' + h * 2;
2727
shape.coordorigin = '1,1';
2728
shape.path = this.getBoxPath( 0, 2 );
2733
if( img.imgType === 'linear-gradient' ) {
2734
this.addLinearGradient( shape, img );
2737
shape.fill.src = img.imgUrl;
2738
this.positionBgImage( shape, i );
2743
// Delete any bgImage shapes previously created which weren't used above
2744
i = images ? images.length : 0;
2745
while( this.deleteShape( 'bgImage' + i++ ) ) {}
2750
* Set the position and clipping of the background image for a layer
2751
* @param {Element} shape
2752
* @param {number} index
2754
positionBgImage: function( shape, index ) {
2756
PIE.Util.withImageSize( shape.fill.src, function( size ) {
2757
var el = me.targetElement,
2758
bounds = me.boundsInfo.getBounds(),
2762
// It's possible that the element dimensions are zero now but weren't when the original
2763
// update executed, make sure that's not the case to avoid divide-by-zero error
2765
var fill = shape.fill,
2767
border = si.borderInfo.getProps(),
2768
bw = border && border.widths,
2769
bwT = bw ? bw['t'].pixels( el ) : 0,
2770
bwR = bw ? bw['r'].pixels( el ) : 0,
2771
bwB = bw ? bw['b'].pixels( el ) : 0,
2772
bwL = bw ? bw['l'].pixels( el ) : 0,
2773
bg = si.backgroundInfo.getProps().bgImages[ index ],
2774
bgPos = bg.bgPosition ? bg.bgPosition.coords( el, elW - size.w - bwL - bwR, elH - size.h - bwT - bwB ) : { x:0, y:0 },
2775
repeat = bg.imgRepeat,
2777
clipT = 0, clipL = 0,
2778
clipR = elW + 1, clipB = elH + 1, //make sure the default clip region is not inside the box (by a subpixel)
2779
clipAdjust = PIE.ieVersion === 8 ? 0 : 1; //prior to IE8 requires 1 extra pixel in the image clip region
2781
// Positioning - find the pixel offset from the top/left and convert to a ratio
2782
// The position is shifted by half a pixel, to adjust for the half-pixel coordorigin shift which is
2783
// needed to fix antialiasing but makes the bg image fuzzy.
2784
pxX = Math.round( bgPos.x ) + bwL + 0.5;
2785
pxY = Math.round( bgPos.y ) + bwT + 0.5;
2786
fill.position = ( pxX / elW ) + ',' + ( pxY / elH );
2788
// Set the size of the image. We have to actually set it to px values otherwise it will not honor
2789
// the user's browser zoom level and always display at its natural screen size.
2790
fill['size']['x'] = 1; //Can be any value, just has to be set to "prime" it so the next line works. Weird!
2791
fill['size'] = size.w + 'px,' + size.h + 'px';
2793
// Repeating - clip the image shape
2794
if( repeat && repeat !== 'repeat' ) {
2795
if( repeat === 'repeat-x' || repeat === 'no-repeat' ) {
2797
clipB = pxY + size.h + clipAdjust;
2799
if( repeat === 'repeat-y' || repeat === 'no-repeat' ) {
2801
clipR = pxX + size.w + clipAdjust;
2803
shape.style.clip = 'rect(' + clipT + 'px,' + clipR + 'px,' + clipB + 'px,' + clipL + 'px)';
2811
* Draw the linear gradient for a gradient layer
2812
* @param {Element} shape
2813
* @param {Object} info The object holding the information about the gradient
2815
addLinearGradient: function( shape, info ) {
2816
var el = this.targetElement,
2817
bounds = this.boundsInfo.getBounds(),
2822
stopCount = stops.length,
2824
GradientUtil = PIE.GradientUtil,
2825
perpendicularIntersect = GradientUtil.perpendicularIntersect,
2826
distance = GradientUtil.distance,
2827
metrics = GradientUtil.getGradientMetrics( el, w, h, info ),
2828
angle = metrics.angle,
2829
startX = metrics.startX,
2830
startY = metrics.startY,
2831
startCornerX = metrics.startCornerX,
2832
startCornerY = metrics.startCornerY,
2833
endCornerX = metrics.endCornerX,
2834
endCornerY = metrics.endCornerY,
2835
deltaX = metrics.deltaX,
2836
deltaY = metrics.deltaY,
2837
lineLength = metrics.lineLength,
2838
vmlAngle, vmlGradientLength, vmlColors,
2839
stopPx, vmlOffsetPct,
2840
p, i, j, before, after;
2842
// In VML land, the angle of the rendered gradient depends on the aspect ratio of the shape's
2843
// bounding box; for example specifying a 45 deg angle actually results in a gradient
2844
// drawn diagonally from one corner to its opposite corner, which will only appear to the
2845
// viewer as 45 degrees if the shape is equilateral. We adjust for this by taking the x/y deltas
2846
// between the start and end points, multiply one of them by the shape's aspect ratio,
2847
// and get their arctangent, resulting in an appropriate VML angle. If the angle is perfectly
2848
// horizontal or vertical then we don't need to do this conversion.
2849
vmlAngle = ( angle % 90 ) ? Math.atan2( deltaX * w / h, deltaY ) / PI * 180 : ( angle + 90 );
2851
// VML angles are 180 degrees offset from CSS angles
2853
vmlAngle = vmlAngle % 360;
2855
// Add all the stops to the VML 'colors' list, including the first and last stops.
2856
// For each, we find its pixel offset along the gradient-line; if the offset of a stop is less
2857
// than that of its predecessor we increase it to be equal. We then map that pixel offset to a
2858
// percentage along the VML gradient-line, which runs from shape corner to corner.
2859
p = perpendicularIntersect( startCornerX, startCornerY, angle, endCornerX, endCornerY );
2860
vmlGradientLength = distance( startCornerX, startCornerY, p[0], p[1] );
2862
p = perpendicularIntersect( startX, startY, angle, startCornerX, startCornerY );
2863
vmlOffsetPct = distance( startX, startY, p[0], p[1] ) / vmlGradientLength * 100;
2865
// Find the pixel offsets along the CSS3 gradient-line for each stop.
2867
for( i = 0; i < stopCount; i++ ) {
2868
stopPx.push( stops[i].offset ? stops[i].offset.pixels( el, lineLength ) :
2869
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
2871
// Fill in gaps with evenly-spaced offsets
2872
for( i = 1; i < stopCount; i++ ) {
2873
if( stopPx[ i ] === null ) {
2874
before = stopPx[ i - 1 ];
2877
after = stopPx[ ++j ];
2878
} while( after === null );
2879
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
2881
// Make sure each stop's offset is no less than the one before it
2882
stopPx[ i ] = Math.max( stopPx[ i ], stopPx[ i - 1 ] );
2885
// Convert to percentage along the VML gradient line and add to the VML 'colors' value
2886
for( i = 0; i < stopCount; i++ ) {
2888
( vmlOffsetPct + ( stopPx[ i ] / vmlGradientLength * 100 ) ) + '% ' + stops[i].color.colorValue( el )
2892
// Now, finally, we're ready to render the gradient fill. Set the start and end colors to
2893
// the first and last stop colors; this just sets outer bounds for the gradient.
2894
fill['angle'] = vmlAngle;
2895
fill['type'] = 'gradient';
2896
fill['method'] = 'sigma';
2897
fill['color'] = stops[0].color.colorValue( el );
2898
fill['color2'] = stops[stopCount - 1].color.colorValue( el );
2899
if( fill['colors'] ) { //sometimes the colors object isn't initialized so we have to assign it directly (?)
2900
fill['colors'].value = vmlColors.join( ',' );
2902
fill['colors'] = vmlColors.join( ',' );
2908
* Hide the actual background image and color of the element.
2910
hideBackground: function() {
2911
var rs = this.targetElement.runtimeStyle;
2912
rs.backgroundImage = 'url(about:blank)'; //ensures the background area reacts to mouse events
2913
rs.backgroundColor = 'transparent';
2916
destroy: function() {
2917
PIE.RendererBase.destroy.call( this );
2918
var rs = this.targetElement.runtimeStyle;
2919
rs.backgroundImage = rs.backgroundColor = '';
2924
* Renderer for element borders.
2926
* @param {Element} el The target element
2927
* @param {Object} styleInfos The StyleInfo objects
2928
* @param {PIE.RootRenderer} parent
2930
PIE.BorderRenderer = PIE.RendererBase.newRenderer( {
2935
needsUpdate: function() {
2936
var si = this.styleInfos;
2937
return si.borderInfo.changed() || si.borderRadiusInfo.changed();
2940
isActive: function() {
2941
var si = this.styleInfos;
2942
return si.borderRadiusInfo.isActive() &&
2943
!si.borderImageInfo.isActive() &&
2944
si.borderInfo.isActive(); //check BorderStyleInfo last because it's the most expensive
2948
* Draw the border shape(s)
2951
var el = this.targetElement,
2952
props = this.styleInfos.borderInfo.getProps(),
2953
bounds = this.boundsInfo.getBounds(),
2957
segments, seg, i, len;
2962
segments = this.getBorderSegments( 2 );
2963
for( i = 0, len = segments.length; i < len; i++) {
2965
shape = this.getShape( 'borderPiece' + i, seg.stroke ? 'stroke' : 'fill', this.getBox() );
2966
shape.coordsize = w * 2 + ',' + h * 2;
2967
shape.coordorigin = '1,1';
2968
shape.path = seg.path;
2973
shape.filled = !!seg.fill;
2974
shape.stroked = !!seg.stroke;
2976
stroke = shape.stroke;
2977
stroke['weight'] = seg.weight + 'px';
2978
stroke.color = seg.color.colorValue( el );
2979
stroke['dashstyle'] = seg.stroke === 'dashed' ? '2 2' : seg.stroke === 'dotted' ? '1 1' : 'solid';
2980
stroke['linestyle'] = seg.stroke === 'double' && seg.weight > 2 ? 'ThinThin' : 'Single';
2982
shape.fill.color = seg.fill.colorValue( el );
2986
// remove any previously-created border shapes which didn't get used above
2987
while( this.deleteShape( 'borderPiece' + i++ ) ) {}
2993
* Get the VML path definitions for the border segment(s).
2994
* @param {number=} mult If specified, all coordinates will be multiplied by this number
2995
* @return {Array.<string>}
2997
getBorderSegments: function( mult ) {
2998
var el = this.targetElement,
3000
borderInfo = this.styleInfos.borderInfo,
3002
floor, ceil, wT, wR, wB, wL,
3004
borderProps, radiusInfo, radii, widths, styles, colors;
3006
if( borderInfo.isActive() ) {
3007
borderProps = borderInfo.getProps();
3009
widths = borderProps.widths;
3010
styles = borderProps.styles;
3011
colors = borderProps.colors;
3013
if( borderProps.widthsSame && borderProps.stylesSame && borderProps.colorsSame ) {
3014
if( colors['t'].alpha() > 0 ) {
3015
// shortcut for identical border on all sides - only need 1 stroked shape
3016
wT = widths['t'].pixels( el ); //thickness
3017
wR = wT / 2; //shrink
3019
path: this.getBoxPath( { t: wR, r: wR, b: wR, l: wR }, mult ),
3020
stroke: styles['t'],
3028
bounds = this.boundsInfo.getBounds();
3032
wT = round( widths['t'].pixels( el ) );
3033
wR = round( widths['r'].pixels( el ) );
3034
wB = round( widths['b'].pixels( el ) );
3035
wL = round( widths['l'].pixels( el ) );
3043
radiusInfo = this.styleInfos.borderRadiusInfo;
3044
if( radiusInfo.isActive() ) {
3045
radii = this.getRadiiPixels( radiusInfo.getProps() );
3051
function radius( xy, corner ) {
3052
return radii ? radii[ xy ][ corner ] : 0;
3055
function curve( corner, shrinkX, shrinkY, startAngle, ccw, doMove ) {
3056
var rx = radius( 'x', corner),
3057
ry = radius( 'y', corner),
3059
isRight = corner.charAt( 1 ) === 'r',
3060
isBottom = corner.charAt( 0 ) === 'b';
3061
return ( rx > 0 && ry > 0 ) ?
3062
( doMove ? 'al' : 'ae' ) +
3063
( isRight ? ceil( elW - rx ) : floor( rx ) ) * mult + ',' + // center x
3064
( isBottom ? ceil( elH - ry ) : floor( ry ) ) * mult + ',' + // center y
3065
( floor( rx ) - shrinkX ) * mult + ',' + // width
3066
( floor( ry ) - shrinkY ) * mult + ',' + // height
3067
( startAngle * deg ) + ',' + // start angle
3068
( 45 * deg * ( ccw ? 1 : -1 ) // angle change
3070
( doMove ? 'm' : 'l' ) +
3071
( isRight ? elW - shrinkX : shrinkX ) * mult + ',' +
3072
( isBottom ? elH - shrinkY : shrinkY ) * mult
3076
function line( side, shrink, ccw, doMove ) {
3080
floor( radius( 'x', 'tl') ) * mult + ',' + ceil( shrink ) * mult :
3082
ceil( elW - shrink ) * mult + ',' + floor( radius( 'y', 'tr') ) * mult :
3084
ceil( elW - radius( 'x', 'br') ) * mult + ',' + floor( elH - shrink ) * mult :
3086
floor( shrink ) * mult + ',' + ceil( elH - radius( 'y', 'bl') ) * mult
3090
ceil( elW - radius( 'x', 'tr') ) * mult + ',' + ceil( shrink ) * mult :
3092
ceil( elW - shrink ) * mult + ',' + ceil( elH - radius( 'y', 'br') ) * mult :
3094
floor( radius( 'x', 'bl') ) * mult + ',' + floor( elH - shrink ) * mult :
3096
floor( shrink ) * mult + ',' + floor( radius( 'y', 'tl') ) * mult
3098
return ccw ? ( doMove ? 'm' + end : '' ) + 'l' + start :
3099
( doMove ? 'm' + start : '' ) + 'l' + end;
3103
function addSide( side, sideBefore, sideAfter, cornerBefore, cornerAfter, baseAngle ) {
3104
var vert = side === 'l' || side === 'r',
3105
sideW = pxWidths[ side ],
3106
beforeX, beforeY, afterX, afterY;
3108
if( sideW > 0 && styles[ side ] !== 'none' && colors[ side ].alpha() > 0 ) {
3109
beforeX = pxWidths[ vert ? side : sideBefore ];
3110
beforeY = pxWidths[ vert ? sideBefore : side ];
3111
afterX = pxWidths[ vert ? side : sideAfter ];
3112
afterY = pxWidths[ vert ? sideAfter : side ];
3114
if( styles[ side ] === 'dashed' || styles[ side ] === 'dotted' ) {
3116
path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
3117
curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
3118
fill: colors[ side ]
3121
path: line( side, sideW / 2, 0, 1 ),
3122
stroke: styles[ side ],
3124
color: colors[ side ]
3127
path: curve( cornerAfter, afterX, afterY, baseAngle, 0, 1 ) +
3128
curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ),
3129
fill: colors[ side ]
3134
path: curve( cornerBefore, beforeX, beforeY, baseAngle + 45, 0, 1 ) +
3135
line( side, sideW, 0, 0 ) +
3136
curve( cornerAfter, afterX, afterY, baseAngle, 0, 0 ) +
3138
( styles[ side ] === 'double' && sideW > 2 ?
3139
curve( cornerAfter, afterX - floor( afterX / 3 ), afterY - floor( afterY / 3 ), baseAngle - 45, 1, 0 ) +
3140
line( side, ceil( sideW / 3 * 2 ), 1, 0 ) +
3141
curve( cornerBefore, beforeX - floor( beforeX / 3 ), beforeY - floor( beforeY / 3 ), baseAngle, 1, 0 ) +
3143
curve( cornerBefore, floor( beforeX / 3 ), floor( beforeY / 3 ), baseAngle + 45, 0, 1 ) +
3144
line( side, floor( sideW / 3 ), 1, 0 ) +
3145
curve( cornerAfter, floor( afterX / 3 ), floor( afterY / 3 ), baseAngle, 0, 0 )
3148
curve( cornerAfter, 0, 0, baseAngle - 45, 1, 0 ) +
3149
line( side, 0, 1, 0 ) +
3150
curve( cornerBefore, 0, 0, baseAngle, 1, 0 ),
3151
fill: colors[ side ]
3157
addSide( 't', 'l', 'r', 'tl', 'tr', 90 );
3158
addSide( 'r', 't', 'b', 'tr', 'br', 0 );
3159
addSide( 'b', 'r', 'l', 'br', 'bl', -90 );
3160
addSide( 'l', 'b', 't', 'bl', 'tl', -180 );
3167
destroy: function() {
3169
if (me.finalized || !me.styleInfos.borderImageInfo.isActive()) {
3170
me.targetElement.runtimeStyle.borderColor = '';
3172
PIE.RendererBase.destroy.call( me );
3178
* Renderer for border-image
3180
* @param {Element} el The target element
3181
* @param {Object} styleInfos The StyleInfo objects
3182
* @param {PIE.RootRenderer} parent
3184
PIE.BorderImageRenderer = PIE.RendererBase.newRenderer( {
3187
pieceNames: [ 't', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl', 'c' ],
3189
needsUpdate: function() {
3190
return this.styleInfos.borderImageInfo.changed();
3193
isActive: function() {
3194
return this.styleInfos.borderImageInfo.isActive();
3198
this.getBox(); //make sure pieces are created
3200
var props = this.styleInfos.borderImageInfo.getProps(),
3201
borderProps = this.styleInfos.borderInfo.getProps(),
3202
bounds = this.boundsInfo.getBounds(),
3203
el = this.targetElement,
3204
pieces = this.pieces;
3206
PIE.Util.withImageSize( props.src, function( imgSize ) {
3209
zero = PIE.getLength( '0' ),
3210
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
3211
widthT = widths['t'].pixels( el ),
3212
widthR = widths['r'].pixels( el ),
3213
widthB = widths['b'].pixels( el ),
3214
widthL = widths['l'].pixels( el ),
3215
slices = props.slice,
3216
sliceT = slices['t'].pixels( el ),
3217
sliceR = slices['r'].pixels( el ),
3218
sliceB = slices['b'].pixels( el ),
3219
sliceL = slices['l'].pixels( el );
3221
// Piece positions and sizes
3222
function setSizeAndPos( piece, w, h, x, y ) {
3223
var s = pieces[piece].style,
3225
s.width = max(w, 0);
3226
s.height = max(h, 0);
3230
setSizeAndPos( 'tl', widthL, widthT, 0, 0 );
3231
setSizeAndPos( 't', elW - widthL - widthR, widthT, widthL, 0 );
3232
setSizeAndPos( 'tr', widthR, widthT, elW - widthR, 0 );
3233
setSizeAndPos( 'r', widthR, elH - widthT - widthB, elW - widthR, widthT );
3234
setSizeAndPos( 'br', widthR, widthB, elW - widthR, elH - widthB );
3235
setSizeAndPos( 'b', elW - widthL - widthR, widthB, widthL, elH - widthB );
3236
setSizeAndPos( 'bl', widthL, widthB, 0, elH - widthB );
3237
setSizeAndPos( 'l', widthL, elH - widthT - widthB, 0, widthT );
3238
setSizeAndPos( 'c', elW - widthL - widthR, elH - widthT - widthB, widthL, widthT );
3242
function setCrops( sides, crop, val ) {
3243
for( var i=0, len=sides.length; i < len; i++ ) {
3244
pieces[ sides[i] ]['imagedata'][ crop ] = val;
3249
setCrops( [ 'tl', 't', 'tr' ], 'cropBottom', ( imgSize.h - sliceT ) / imgSize.h );
3250
setCrops( [ 'tl', 'l', 'bl' ], 'cropRight', ( imgSize.w - sliceL ) / imgSize.w );
3251
setCrops( [ 'bl', 'b', 'br' ], 'cropTop', ( imgSize.h - sliceB ) / imgSize.h );
3252
setCrops( [ 'tr', 'r', 'br' ], 'cropLeft', ( imgSize.w - sliceR ) / imgSize.w );
3255
// TODO right now this treats everything like 'stretch', need to support other schemes
3256
//if( props.repeat.v === 'stretch' ) {
3257
setCrops( [ 'l', 'r', 'c' ], 'cropTop', sliceT / imgSize.h );
3258
setCrops( [ 'l', 'r', 'c' ], 'cropBottom', sliceB / imgSize.h );
3260
//if( props.repeat.h === 'stretch' ) {
3261
setCrops( [ 't', 'b', 'c' ], 'cropLeft', sliceL / imgSize.w );
3262
setCrops( [ 't', 'b', 'c' ], 'cropRight', sliceR / imgSize.w );
3266
pieces['c'].style.display = props.fill ? '' : 'none';
3270
getBox: function() {
3271
var box = this.parent.getLayer( this.boxZIndex ),
3273
pieceNames = this.pieceNames,
3274
len = pieceNames.length;
3277
box = doc.createElement( 'border-image' );
3279
s.position = 'absolute';
3283
for( i = 0; i < len; i++ ) {
3284
piece = this.pieces[ pieceNames[i] ] = PIE.Util.createVmlElement( 'rect' );
3285
piece.appendChild( PIE.Util.createVmlElement( 'imagedata' ) );
3287
s['behavior'] = 'url(#default#VML)';
3288
s.position = "absolute";
3290
piece['imagedata'].src = this.styleInfos.borderImageInfo.getProps().src;
3291
piece.stroked = false;
3292
piece.filled = false;
3293
box.appendChild( piece );
3296
this.parent.addLayer( this.boxZIndex, box );
3302
prepareUpdate: function() {
3303
if (this.isActive()) {
3305
el = me.targetElement,
3306
rs = el.runtimeStyle,
3307
widths = me.styleInfos.borderImageInfo.getProps().widths;
3309
// Force border-style to solid so it doesn't collapse
3310
rs.borderStyle = 'solid';
3312
// If widths specified in border-image shorthand, override border-width
3313
// NOTE px units needed here as this gets used by the IE9 renderer too
3315
rs.borderTopWidth = widths['t'].pixels( el ) + 'px';
3316
rs.borderRightWidth = widths['r'].pixels( el ) + 'px';
3317
rs.borderBottomWidth = widths['b'].pixels( el ) + 'px';
3318
rs.borderLeftWidth = widths['l'].pixels( el ) + 'px';
3321
// Make the border transparent
3326
destroy: function() {
3328
rs = me.targetElement.runtimeStyle;
3329
rs.borderStyle = '';
3330
if (me.finalized || !me.styleInfos.borderInfo.isActive()) {
3331
rs.borderColor = rs.borderWidth = '';
3333
PIE.RendererBase.destroy.call( this );
3338
* Renderer for outset box-shadows
3340
* @param {Element} el The target element
3341
* @param {Object} styleInfos The StyleInfo objects
3342
* @param {PIE.RootRenderer} parent
3344
PIE.BoxShadowOutsetRenderer = PIE.RendererBase.newRenderer( {
3347
boxName: 'outset-box-shadow',
3349
needsUpdate: function() {
3350
var si = this.styleInfos;
3351
return si.boxShadowInfo.changed() || si.borderRadiusInfo.changed();
3354
isActive: function() {
3355
var boxShadowInfo = this.styleInfos.boxShadowInfo;
3356
return boxShadowInfo.isActive() && boxShadowInfo.getProps().outset[0];
3361
el = this.targetElement,
3362
box = this.getBox(),
3363
styleInfos = this.styleInfos,
3364
shadowInfos = styleInfos.boxShadowInfo.getProps().outset,
3365
radii = styleInfos.borderRadiusInfo.getProps(),
3366
len = shadowInfos.length,
3368
bounds = this.boundsInfo.getBounds(),
3371
clipAdjust = PIE.ieVersion === 8 ? 1 : 0, //workaround for IE8 bug where VML leaks out top/left of clip region by 1px
3372
corners = [ 'tl', 'tr', 'br', 'bl' ], corner,
3373
shadowInfo, shape, fill, ss, xOff, yOff, spread, blur, shrink, color, alpha, path,
3374
totalW, totalH, focusX, focusY, isBottom, isRight;
3377
function getShadowShape( index, corner, xOff, yOff, color, blur, path ) {
3378
var shape = me.getShape( 'shadow' + index + corner, 'fill', box, len - index ),
3381
// Position and size
3382
shape['coordsize'] = w * 2 + ',' + h * 2;
3383
shape['coordorigin'] = '1,1';
3385
// Color and opacity
3386
shape['stroked'] = false;
3387
shape['filled'] = true;
3388
fill.color = color.colorValue( el );
3390
fill['type'] = 'gradienttitle'; //makes the VML gradient follow the shape's outline - hooray for undocumented features?!?!
3391
fill['color2'] = fill.color;
3392
fill['opacity'] = 0;
3398
// This needs to go last for some reason, to prevent rendering at incorrect size
3410
shadowInfo = shadowInfos[ i ];
3411
xOff = shadowInfo.xOffset.pixels( el );
3412
yOff = shadowInfo.yOffset.pixels( el );
3413
spread = shadowInfo.spread.pixels( el );
3414
blur = shadowInfo.blur.pixels( el );
3415
color = shadowInfo.color;
3417
shrink = -spread - blur;
3418
if( !radii && blur ) {
3419
// If blurring, use a non-null border radius info object so that getBoxPath will
3420
// round the corners of the expanded shadow shape rather than squaring them off.
3421
radii = PIE.BorderRadiusStyleInfo.ALL_ZERO;
3423
path = this.getBoxPath( { t: shrink, r: shrink, b: shrink, l: shrink }, 2, radii );
3426
totalW = ( spread + blur ) * 2 + w;
3427
totalH = ( spread + blur ) * 2 + h;
3428
focusX = totalW ? blur * 2 / totalW : 0;
3429
focusY = totalH ? blur * 2 / totalH : 0;
3430
if( blur - spread > w / 2 || blur - spread > h / 2 ) {
3431
// If the blur is larger than half the element's narrowest dimension, we cannot do
3432
// this with a single shape gradient, because its focussize would have to be less than
3433
// zero which results in ugly artifacts. Instead we create four shapes, each with its
3434
// gradient focus past center, and then clip them so each only shows the quadrant
3435
// opposite the focus.
3436
for( j = 4; j--; ) {
3437
corner = corners[j];
3438
isBottom = corner.charAt( 0 ) === 'b';
3439
isRight = corner.charAt( 1 ) === 'r';
3440
shape = getShadowShape( i, corner, xOff, yOff, color, blur, path );
3442
fill['focusposition'] = ( isRight ? 1 - focusX : focusX ) + ',' +
3443
( isBottom ? 1 - focusY : focusY );
3444
fill['focussize'] = '0,0';
3446
// Clip to show only the appropriate quadrant. Add 1px to the top/left clip values
3447
// in IE8 to prevent a bug where IE8 displays one pixel outside the clip region.
3448
shape.style.clip = 'rect(' + ( ( isBottom ? totalH / 2 : 0 ) + clipAdjust ) + 'px,' +
3449
( isRight ? totalW : totalW / 2 ) + 'px,' +
3450
( isBottom ? totalH : totalH / 2 ) + 'px,' +
3451
( ( isRight ? totalW / 2 : 0 ) + clipAdjust ) + 'px)';
3454
// TODO delete old quadrant shapes if resizing expands past the barrier
3455
shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
3457
fill['focusposition'] = focusX + ',' + focusY;
3458
fill['focussize'] = ( 1 - focusX * 2 ) + ',' + ( 1 - focusY * 2 );
3461
shape = getShadowShape( i, '', xOff, yOff, color, blur, path );
3462
alpha = color.alpha();
3464
// shape.style.filter = 'alpha(opacity=' + ( alpha * 100 ) + ')';
3465
// ss.filter = 'progid:DXImageTransform.Microsoft.BasicImage(opacity=' + ( alpha ) + ')';
3466
shape.fill.opacity = alpha;
3474
* Renderer for re-rendering img elements using VML. Kicks in if the img has
3475
* a border-radius applied, or if the -pie-png-fix flag is set.
3477
* @param {Element} el The target element
3478
* @param {Object} styleInfos The StyleInfo objects
3479
* @param {PIE.RootRenderer} parent
3481
PIE.ImgRenderer = PIE.RendererBase.newRenderer( {
3486
needsUpdate: function() {
3487
var si = this.styleInfos;
3488
return this.targetElement.src !== this._lastSrc || si.borderRadiusInfo.changed();
3491
isActive: function() {
3492
var si = this.styleInfos;
3493
return si.borderRadiusInfo.isActive() || si.backgroundInfo.isPngFix();
3497
this._lastSrc = src;
3498
this.hideActualImg();
3500
var shape = this.getShape( 'img', 'fill', this.getBox() ),
3502
bounds = this.boundsInfo.getBounds(),
3505
borderProps = this.styleInfos.borderInfo.getProps(),
3506
borderWidths = borderProps && borderProps.widths,
3507
el = this.targetElement,
3510
cs = el.currentStyle,
3511
getLength = PIE.getLength,
3514
// In IE6, the BorderRenderer will have hidden the border by moving the border-width to
3515
// the padding; therefore we want to pretend the borders have no width so they aren't doubled
3516
// when adding in the current padding value below.
3517
if( !borderWidths || PIE.ieVersion < 7 ) {
3518
zero = PIE.getLength( '0' );
3519
borderWidths = { 't': zero, 'r': zero, 'b': zero, 'l': zero };
3522
shape.stroked = false;
3523
fill.type = 'frame';
3525
fill.position = (w ? 0.5 / w : 0) + ',' + (h ? 0.5 / h : 0);
3526
shape.coordsize = w * 2 + ',' + h * 2;
3527
shape.coordorigin = '1,1';
3528
shape.path = this.getBoxPath( {
3529
t: round( borderWidths['t'].pixels( el ) + getLength( cs.paddingTop ).pixels( el ) ),
3530
r: round( borderWidths['r'].pixels( el ) + getLength( cs.paddingRight ).pixels( el ) ),
3531
b: round( borderWidths['b'].pixels( el ) + getLength( cs.paddingBottom ).pixels( el ) ),
3532
l: round( borderWidths['l'].pixels( el ) + getLength( cs.paddingLeft ).pixels( el ) )
3539
hideActualImg: function() {
3540
this.targetElement.runtimeStyle.filter = 'alpha(opacity=0)';
3543
destroy: function() {
3544
PIE.RendererBase.destroy.call( this );
3545
this.targetElement.runtimeStyle.filter = '';
3550
* Root renderer for IE9; manages the rendering layers in the element's background
3551
* @param {Element} el The target element
3552
* @param {Object} styleInfos The StyleInfo objects
3554
PIE.IE9RootRenderer = PIE.RendererBase.newRenderer( {
3556
updatePos: PIE.emptyFn,
3557
updateSize: PIE.emptyFn,
3558
updateVisibility: PIE.emptyFn,
3559
updateProps: PIE.emptyFn,
3561
outerCommasRE: /^,+|,+$/g,
3562
innerCommasRE: /,+/g,
3564
setBackgroundLayer: function(zIndex, bg) {
3566
bgLayers = me._bgLayers || ( me._bgLayers = [] ),
3568
bgLayers[zIndex] = bg || undef;
3571
finishUpdate: function() {
3573
bgLayers = me._bgLayers,
3575
if( bgLayers && ( bg = bgLayers.join( ',' ).replace( me.outerCommasRE, '' ).replace( me.innerCommasRE, ',' ) ) !== me._lastBg ) {
3576
me._lastBg = me.targetElement.runtimeStyle.background = bg;
3580
destroy: function() {
3581
this.targetElement.runtimeStyle.background = '';
3582
delete this._bgLayers;
3587
* Renderer for element backgrounds, specific for IE9. Only handles translating CSS3 gradients
3588
* to an equivalent SVG data URI.
3590
* @param {Element} el The target element
3591
* @param {Object} styleInfos The StyleInfo objects
3593
PIE.IE9BackgroundRenderer = PIE.RendererBase.newRenderer( {
3597
needsUpdate: function() {
3598
var si = this.styleInfos;
3599
return si.backgroundInfo.changed();
3602
isActive: function() {
3603
var si = this.styleInfos;
3604
return si.backgroundInfo.isActive() || si.borderImageInfo.isActive();
3609
props = me.styleInfos.backgroundInfo.getProps(),
3610
bg, images, i = 0, img, bgAreaSize, bgSize;
3615
images = props.bgImages;
3617
while( img = images[ i++ ] ) {
3618
if (img.imgType === 'linear-gradient' ) {
3619
bgAreaSize = me.getBgAreaSize( img.bgOrigin );
3620
bgSize = ( img.bgSize || PIE.BgSize.DEFAULT ).pixels(
3621
me.targetElement, bgAreaSize.w, bgAreaSize.h, bgAreaSize.w, bgAreaSize.h
3624
'url(data:image/svg+xml,' + escape( me.getGradientSvg( img, bgSize.w, bgSize.h ) ) + ') ' +
3625
me.bgPositionToString( img.bgPosition ) + ' / ' + bgSize.w + 'px ' + bgSize.h + 'px ' +
3626
( img.bgAttachment || '' ) + ' ' + ( img.bgOrigin || '' ) + ' ' + ( img.bgClip || '' )
3629
bg.push( img.origString );
3634
if ( props.color ) {
3635
bg.push( props.color.val );
3638
me.parent.setBackgroundLayer(me.bgLayerZIndex, bg.join(','));
3642
bgPositionToString: function( bgPosition ) {
3643
return bgPosition ? bgPosition.tokens.map(function(token) {
3644
return token.tokenValue;
3645
}).join(' ') : '0 0';
3648
getBgAreaSize: function( bgOrigin ) {
3650
el = me.targetElement,
3651
bounds = me.boundsInfo.getBounds(),
3656
borders, getLength, cs;
3658
if( bgOrigin !== 'border-box' ) {
3659
borders = me.styleInfos.borderInfo.getProps();
3660
if( borders && ( borders = borders.widths ) ) {
3661
w -= borders[ 'l' ].pixels( el ) + borders[ 'l' ].pixels( el );
3662
h -= borders[ 't' ].pixels( el ) + borders[ 'b' ].pixels( el );
3666
if ( bgOrigin === 'content-box' ) {
3667
getLength = PIE.getLength;
3668
cs = el.currentStyle;
3669
w -= getLength( cs.paddingLeft ).pixels( el ) + getLength( cs.paddingRight ).pixels( el );
3670
h -= getLength( cs.paddingTop ).pixels( el ) + getLength( cs.paddingBottom ).pixels( el );
3673
return { w: w, h: h };
3676
getGradientSvg: function( info, bgWidth, bgHeight ) {
3677
var el = this.targetElement,
3678
stopsInfo = info.stops,
3679
stopCount = stopsInfo.length,
3680
metrics = PIE.GradientUtil.getGradientMetrics( el, bgWidth, bgHeight, info ),
3681
startX = metrics.startX,
3682
startY = metrics.startY,
3683
endX = metrics.endX,
3684
endY = metrics.endY,
3685
lineLength = metrics.lineLength,
3687
i, j, before, after,
3690
// Find the pixel offsets along the CSS3 gradient-line for each stop.
3692
for( i = 0; i < stopCount; i++ ) {
3693
stopPx.push( stopsInfo[i].offset ? stopsInfo[i].offset.pixels( el, lineLength ) :
3694
i === 0 ? 0 : i === stopCount - 1 ? lineLength : null );
3696
// Fill in gaps with evenly-spaced offsets
3697
for( i = 1; i < stopCount; i++ ) {
3698
if( stopPx[ i ] === null ) {
3699
before = stopPx[ i - 1 ];
3702
after = stopPx[ ++j ];
3703
} while( after === null );
3704
stopPx[ i ] = before + ( after - before ) / ( j - i + 1 );
3709
'<svg width="' + bgWidth + '" height="' + bgHeight + '" xmlns="http://www.w3.org/2000/svg">' +
3711
'<linearGradient id="g" gradientUnits="userSpaceOnUse"' +
3712
' x1="' + ( startX / bgWidth * 100 ) + '%" y1="' + ( startY / bgHeight * 100 ) + '%" x2="' + ( endX / bgWidth * 100 ) + '%" y2="' + ( endY / bgHeight * 100 ) + '%">'
3715
// Convert to percentage along the SVG gradient line and add to the stops list
3716
for( i = 0; i < stopCount; i++ ) {
3718
'<stop offset="' + ( stopPx[ i ] / lineLength ) +
3719
'" stop-color="' + stopsInfo[i].color.colorValue( el ) +
3720
'" stop-opacity="' + stopsInfo[i].color.alpha() + '"/>'
3725
'</linearGradient>' +
3727
'<rect width="100%" height="100%" fill="url(#g)"/>' +
3731
return svg.join( '' );
3734
destroy: function() {
3735
this.parent.setBackgroundLayer( this.bgLayerZIndex );
3740
* Renderer for border-image
3742
* @param {Element} el The target element
3743
* @param {Object} styleInfos The StyleInfo objects
3744
* @param {PIE.RootRenderer} parent
3746
PIE.IE9BorderImageRenderer = PIE.RendererBase.newRenderer( {
3754
needsUpdate: function() {
3755
return this.styleInfos.borderImageInfo.changed();
3758
isActive: function() {
3759
return this.styleInfos.borderImageInfo.isActive();
3764
props = me.styleInfos.borderImageInfo.getProps(),
3765
borderProps = me.styleInfos.borderInfo.getProps(),
3766
bounds = me.boundsInfo.getBounds(),
3767
repeat = props.repeat,
3770
el = me.targetElement,
3773
PIE.Util.withImageSize( props.src, function( imgSize ) {
3779
// The image cannot be referenced as a URL directly in the SVG because IE9 throws a strange
3780
// security exception (perhaps due to cross-origin policy within data URIs?) Therefore we
3781
// work around this by converting the image data into a data URI itself using a transient
3782
// canvas. This unfortunately requires the border-image src to be within the same domain,
3783
// which isn't a limitation in true border-image, so we need to try and find a better fix.
3784
imgSrc = me.imageToDataURI( props.src, imgW, imgH ),
3787
STRETCH = me.STRETCH,
3791
zero = PIE.getLength( '0' ),
3792
widths = props.widths || ( borderProps ? borderProps.widths : { 't': zero, 'r': zero, 'b': zero, 'l': zero } ),
3793
widthT = widths['t'].pixels( el ),
3794
widthR = widths['r'].pixels( el ),
3795
widthB = widths['b'].pixels( el ),
3796
widthL = widths['l'].pixels( el ),
3797
slices = props.slice,
3798
sliceT = slices['t'].pixels( el ),
3799
sliceR = slices['r'].pixels( el ),
3800
sliceB = slices['b'].pixels( el ),
3801
sliceL = slices['l'].pixels( el ),
3802
centerW = elW - widthL - widthR,
3803
middleH = elH - widthT - widthB,
3804
imgCenterW = imgW - sliceL - sliceR,
3805
imgMiddleH = imgH - sliceT - sliceB,
3807
// Determine the size of each tile - 'round' is handled below
3808
tileSizeT = repeatH === STRETCH ? centerW : imgCenterW * widthT / sliceT,
3809
tileSizeR = repeatV === STRETCH ? middleH : imgMiddleH * widthR / sliceR,
3810
tileSizeB = repeatH === STRETCH ? centerW : imgCenterW * widthB / sliceB,
3811
tileSizeL = repeatV === STRETCH ? middleH : imgMiddleH * widthL / sliceL,
3818
// For 'round', subtract from each tile's size enough so that they fill the space a whole number of times
3819
if (repeatH === ROUND) {
3820
tileSizeT -= (tileSizeT - (centerW % tileSizeT || tileSizeT)) / ceil(centerW / tileSizeT);
3821
tileSizeB -= (tileSizeB - (centerW % tileSizeB || tileSizeB)) / ceil(centerW / tileSizeB);
3823
if (repeatV === ROUND) {
3824
tileSizeR -= (tileSizeR - (middleH % tileSizeR || tileSizeR)) / ceil(middleH / tileSizeR);
3825
tileSizeL -= (tileSizeL - (middleH % tileSizeL || tileSizeL)) / ceil(middleH / tileSizeL);
3829
// Build the SVG for the border-image rendering. Add each piece as a pattern, which is then stretched
3830
// or repeated as the fill of a rect of appropriate size.
3832
'<svg width="' + elW + '" height="' + elH + '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">'
3835
function addImage( x, y, w, h, cropX, cropY, cropW, cropH, tileW, tileH ) {
3837
'<pattern patternUnits="userSpaceOnUse" id="pattern' + i + '" ' +
3838
'x="' + (repeatH === REPEAT ? x + w / 2 - tileW / 2 : x) + '" ' +
3839
'y="' + (repeatV === REPEAT ? y + h / 2 - tileH / 2 : y) + '" ' +
3840
'width="' + tileW + '" height="' + tileH + '">' +
3841
'<svg width="' + tileW + '" height="' + tileH + '" viewBox="' + cropX + ' ' + cropY + ' ' + cropW + ' ' + cropH + '" preserveAspectRatio="none">' +
3842
'<image xlink:href="' + imgSrc + '" x="0" y="0" width="' + imgW + '" height="' + imgH + '" />' +
3847
'<rect x="' + x + '" y="' + y + '" width="' + w + '" height="' + h + '" fill="url(#pattern' + i + ')" />'
3851
addImage( 0, 0, widthL, widthT, 0, 0, sliceL, sliceT, widthL, widthT ); // top left
3852
addImage( widthL, 0, centerW, widthT, sliceL, 0, imgCenterW, sliceT, tileSizeT, widthT ); // top center
3853
addImage( elW - widthR, 0, widthR, widthT, imgW - sliceR, 0, sliceR, sliceT, widthR, widthT ); // top right
3854
addImage( 0, widthT, widthL, middleH, 0, sliceT, sliceL, imgMiddleH, widthL, tileSizeL ); // middle left
3855
if ( props.fill ) { // center fill
3856
addImage( widthL, widthT, centerW, middleH, sliceL, sliceT, imgCenterW, imgMiddleH,
3857
tileSizeT || tileSizeB || imgCenterW, tileSizeL || tileSizeR || imgMiddleH );
3859
addImage( elW - widthR, widthT, widthR, middleH, imgW - sliceR, sliceT, sliceR, imgMiddleH, widthR, tileSizeR ); // middle right
3860
addImage( 0, elH - widthB, widthL, widthB, 0, imgH - sliceB, sliceL, sliceB, widthL, widthB ); // bottom left
3861
addImage( widthL, elH - widthB, centerW, widthB, sliceL, imgH - sliceB, imgCenterW, sliceB, tileSizeB, widthB ); // bottom center
3862
addImage( elW - widthR, elH - widthB, widthR, widthB, imgW - sliceR, imgH - sliceB, sliceR, sliceB, widthR, widthB ); // bottom right
3866
patterns.join('\n') +
3872
me.parent.setBackgroundLayer( me.bgLayerZIndex, 'url(data:image/svg+xml,' + escape( svg.join( '' ) ) + ') no-repeat border-box border-box' );
3874
// If the border-image's src wasn't immediately available, the SVG for its background layer
3875
// will have been created asynchronously after the main element's update has finished; we'll
3876
// therefore need to force the root renderer to sync to the final background once finished.
3878
me.parent.finishUpdate();
3886
* Convert a given image to a data URI
3888
imageToDataURI: (function() {
3890
return function( src, width, height ) {
3891
var uri = uris[ src ],
3894
image = new Image();
3895
canvas = doc.createElement( 'canvas' );
3897
canvas.width = width;
3898
canvas.height = height;
3899
canvas.getContext( '2d' ).drawImage( image, 0, 0 );
3900
uri = uris[ src ] = canvas.toDataURL();
3906
prepareUpdate: PIE.BorderImageRenderer.prototype.prepareUpdate,
3908
destroy: function() {
3910
rs = me.targetElement.runtimeStyle;
3911
me.parent.setBackgroundLayer( me.bgLayerZIndex );
3912
rs.borderColor = rs.borderStyle = rs.borderWidth = '';
3917
PIE.Element = (function() {
3920
lazyInitCssProp = PIE.CSS_PREFIX + 'lazy-init',
3921
pollCssProp = PIE.CSS_PREFIX + 'poll',
3922
trackActiveCssProp = PIE.CSS_PREFIX + 'track-active',
3923
trackHoverCssProp = PIE.CSS_PREFIX + 'track-hover',
3924
hoverClass = PIE.CLASS_PREFIX + 'hover',
3925
activeClass = PIE.CLASS_PREFIX + 'active',
3926
focusClass = PIE.CLASS_PREFIX + 'focus',
3927
firstChildClass = PIE.CLASS_PREFIX + 'first-child',
3928
ignorePropertyNames = { 'background':1, 'bgColor':1, 'display': 1 },
3929
classNameRegExes = {},
3933
function addClass( el, className ) {
3934
el.className += ' ' + className;
3937
function removeClass( el, className ) {
3938
var re = classNameRegExes[ className ] ||
3939
( classNameRegExes[ className ] = new RegExp( '\\b' + className + '\\b', 'g' ) );
3940
el.className = el.className.replace( re, '' );
3943
function delayAddClass( el, className /*, className2*/ ) {
3944
var classes = dummyArray.slice.call( arguments, 1 ),
3946
setTimeout( function() {
3949
addClass( el, classes[ i ] );
3955
function delayRemoveClass( el, className /*, className2*/ ) {
3956
var classes = dummyArray.slice.call( arguments, 1 ),
3958
setTimeout( function() {
3961
removeClass( el, classes[ i ] );
3969
function Element( el ) {
3972
boundsInfo = new PIE.BoundsInfo( el ),
3978
eventListeners = [],
3984
* Initialize PIE for this element.
3987
if( !initialized ) {
3990
ieDocMode = PIE.ieDocMode,
3991
cs = el.currentStyle,
3992
lazy = cs.getAttribute( lazyInitCssProp ) === 'true',
3993
trackActive = cs.getAttribute( trackActiveCssProp ) !== 'false',
3994
trackHover = cs.getAttribute( trackHoverCssProp ) !== 'false',
3997
// Polling for size/position changes: default to on in IE8, off otherwise, overridable by -pie-poll
3998
poll = cs.getAttribute( pollCssProp );
3999
poll = ieDocMode > 7 ? poll !== 'false' : poll === 'true';
4001
// Force layout so move/resize events will fire. Set this as soon as possible to avoid layout changes
4002
// after load, but make sure it only gets called the first time through to avoid recursive calls to init().
4003
if( !initializing ) {
4005
el.runtimeStyle.zoom = 1;
4006
initFirstChildPseudoClass();
4011
// If the -pie-lazy-init:true flag is set, check if the element is outside the viewport and if so, delay initialization
4012
if( lazy && ( bounds = boundsInfo.getBounds() ) && ( docEl = doc.documentElement || doc.body ) &&
4013
( bounds.y > docEl.clientHeight || bounds.x > docEl.clientWidth || bounds.y + bounds.h < 0 || bounds.x + bounds.w < 0 ) ) {
4016
PIE.OnScroll.observe( init );
4020
delayed = initializing = 0;
4021
PIE.OnScroll.unobserve( init );
4023
// Create the style infos and renderers
4024
if ( ieDocMode === 9 ) {
4026
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
4027
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
4028
borderInfo: new PIE.BorderStyleInfo( el )
4031
styleInfos.backgroundInfo,
4032
styleInfos.borderImageInfo
4034
rootRenderer = new PIE.IE9RootRenderer( el, boundsInfo, styleInfos );
4036
new PIE.IE9BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4037
new PIE.IE9BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
4042
backgroundInfo: new PIE.BackgroundStyleInfo( el ),
4043
borderInfo: new PIE.BorderStyleInfo( el ),
4044
borderImageInfo: new PIE.BorderImageStyleInfo( el ),
4045
borderRadiusInfo: new PIE.BorderRadiusStyleInfo( el ),
4046
boxShadowInfo: new PIE.BoxShadowStyleInfo( el ),
4047
visibilityInfo: new PIE.VisibilityStyleInfo( el )
4050
styleInfos.backgroundInfo,
4051
styleInfos.borderInfo,
4052
styleInfos.borderImageInfo,
4053
styleInfos.borderRadiusInfo,
4054
styleInfos.boxShadowInfo,
4055
styleInfos.visibilityInfo
4057
rootRenderer = new PIE.RootRenderer( el, boundsInfo, styleInfos );
4059
new PIE.BoxShadowOutsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4060
new PIE.BackgroundRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4061
//new PIE.BoxShadowInsetRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4062
new PIE.BorderRenderer( el, boundsInfo, styleInfos, rootRenderer ),
4063
new PIE.BorderImageRenderer( el, boundsInfo, styleInfos, rootRenderer )
4065
if( el.tagName === 'IMG' ) {
4066
childRenderers.push( new PIE.ImgRenderer( el, boundsInfo, styleInfos, rootRenderer ) );
4068
rootRenderer.childRenderers = childRenderers; // circular reference, can't pass in constructor; TODO is there a cleaner way?
4070
renderers = [ rootRenderer ].concat( childRenderers );
4072
// Add property change listeners to ancestors if requested
4073
initAncestorEventListeners();
4075
// Add to list of polled elements in IE8
4077
PIE.Heartbeat.observe( update );
4078
PIE.Heartbeat.run();
4081
// Trigger rendering
4085
if( !eventsAttached ) {
4087
if( ieDocMode < 9 ) {
4088
addListener( el, 'onmove', handleMoveOrResize );
4090
addListener( el, 'onresize', handleMoveOrResize );
4091
addListener( el, 'onpropertychange', propChanged );
4093
addListener( el, 'onmouseenter', mouseEntered );
4095
if( trackHover || trackActive ) {
4096
addListener( el, 'onmouseleave', mouseLeft );
4099
addListener( el, 'onmousedown', mousePressed );
4101
if( el.tagName in PIE.focusableElements ) {
4102
addListener( el, 'onfocus', focused );
4103
addListener( el, 'onblur', blurred );
4105
PIE.OnResize.observe( handleMoveOrResize );
4107
PIE.OnUnload.observe( removeEventListeners );
4110
boundsInfo.unlock();
4118
* Event handler for onmove and onresize events. Invokes update() only if the element's
4119
* bounds have previously been calculated, to prevent multiple runs during page load when
4120
* the element has no initial CSS3 properties.
4122
function handleMoveOrResize() {
4123
if( boundsInfo && boundsInfo.hasBeenQueried() ) {
4130
* Update position and/or size as necessary. Both move and resize events call
4131
* this rather than the updatePos/Size functions because sometimes, particularly
4132
* during page load, one will fire but the other won't.
4134
function update( force ) {
4137
var i, len = renderers.length;
4140
for( i = 0; i < len; i++ ) {
4141
renderers[i].prepareUpdate();
4143
if( force || boundsInfo.positionChanged() ) {
4144
/* TODO just using getBoundingClientRect (used internally by BoundsInfo) for detecting
4145
position changes may not always be accurate; it's possible that
4146
an element will actually move relative to its positioning parent, but its position
4147
relative to the viewport will stay the same. Need to come up with a better way to
4148
track movement. The most accurate would be the same logic used in RootRenderer.updatePos()
4149
but that is a more expensive operation since it does some DOM walking, and we want this
4150
check to be as fast as possible. */
4151
for( i = 0; i < len; i++ ) {
4152
renderers[i].updatePos();
4155
if( force || boundsInfo.sizeChanged() ) {
4156
for( i = 0; i < len; i++ ) {
4157
renderers[i].updateSize();
4160
rootRenderer.finishUpdate();
4163
else if( !initializing ) {
4170
* Handle property changes to trigger update when appropriate.
4172
function propChanged() {
4173
var i, len = renderers.length,
4177
// Some elements like <table> fire onpropertychange events for old-school background properties
4178
// ('background', 'bgColor') when runtimeStyle background properties are changed, which
4179
// results in an infinite loop; therefore we filter out those property names. Also, 'display'
4180
// is ignored because size calculations don't work correctly immediately when its onpropertychange
4181
// event fires, and because it will trigger an onresize event anyway.
4182
if( !destroyed && !( e && e.propertyName in ignorePropertyNames ) ) {
4185
for( i = 0; i < len; i++ ) {
4186
renderers[i].prepareUpdate();
4188
for( i = 0; i < len; i++ ) {
4189
renderer = renderers[i];
4190
// Make sure position is synced if the element hasn't already been rendered.
4191
// TODO this feels sloppy - look into merging propChanged and update functions
4192
if( !renderer.isPositioned ) {
4193
renderer.updatePos();
4195
if( renderer.needsUpdate() ) {
4196
renderer.updateProps();
4199
rootRenderer.finishUpdate();
4202
else if( !initializing ) {
4210
* Handle mouseenter events. Adds a custom class to the element to allow IE6 to add
4211
* hover styles to non-link elements, and to trigger a propertychange update.
4213
function mouseEntered() {
4214
//must delay this because the mouseenter event fires before the :hover styles are added.
4215
delayAddClass( el, hoverClass );
4219
* Handle mouseleave events
4221
function mouseLeft() {
4222
//must delay this because the mouseleave event fires before the :hover styles are removed.
4223
delayRemoveClass( el, hoverClass, activeClass );
4227
* Handle mousedown events. Adds a custom class to the element to allow IE6 to add
4228
* active styles to non-link elements, and to trigger a propertychange update.
4230
function mousePressed() {
4231
//must delay this because the mousedown event fires before the :active styles are added.
4232
delayAddClass( el, activeClass );
4234
// listen for mouseups on the document; can't just be on the element because the user might
4235
// have dragged out of the element while the mouse button was held down
4236
PIE.OnMouseup.observe( mouseReleased );
4240
* Handle mouseup events
4242
function mouseReleased() {
4243
//must delay this because the mouseup event fires before the :active styles are removed.
4244
delayRemoveClass( el, activeClass );
4246
PIE.OnMouseup.unobserve( mouseReleased );
4250
* Handle focus events. Adds a custom class to the element to trigger a propertychange update.
4252
function focused() {
4253
//must delay this because the focus event fires before the :focus styles are added.
4254
delayAddClass( el, focusClass );
4258
* Handle blur events
4260
function blurred() {
4261
//must delay this because the blur event fires before the :focus styles are removed.
4262
delayRemoveClass( el, focusClass );
4267
* Handle property changes on ancestors of the element; see initAncestorEventListeners()
4268
* which adds these listeners as requested with the -pie-watch-ancestors CSS property.
4270
function ancestorPropChanged() {
4271
var name = event.propertyName;
4272
if( name === 'className' || name === 'id' ) {
4277
function lockAll() {
4279
for( var i = styleInfosArr.length; i--; ) {
4280
styleInfosArr[i].lock();
4284
function unlockAll() {
4285
for( var i = styleInfosArr.length; i--; ) {
4286
styleInfosArr[i].unlock();
4288
boundsInfo.unlock();
4292
function addListener( targetEl, type, handler ) {
4293
targetEl.attachEvent( type, handler );
4294
eventListeners.push( [ targetEl, type, handler ] );
4298
* Remove all event listeners from the element and any monitored ancestors.
4300
function removeEventListeners() {
4301
if (eventsAttached) {
4302
var i = eventListeners.length,
4306
listener = eventListeners[ i ];
4307
listener[ 0 ].detachEvent( listener[ 1 ], listener[ 2 ] );
4310
PIE.OnUnload.unobserve( removeEventListeners );
4312
eventListeners = [];
4318
* Clean everything up when the behavior is removed from the element, or the element
4319
* is manually destroyed.
4321
function destroy() {
4325
removeEventListeners();
4329
// destroy any active renderers
4331
for( i = 0, len = renderers.length; i < len; i++ ) {
4332
renderers[i].finalized = 1;
4333
renderers[i].destroy();
4337
// Remove from list of polled elements in IE8
4339
PIE.Heartbeat.unobserve( update );
4341
// Stop onresize listening
4342
PIE.OnResize.unobserve( update );
4345
renderers = boundsInfo = styleInfos = styleInfosArr = el = null;
4351
* If requested via the custom -pie-watch-ancestors CSS property, add onpropertychange and
4352
* other event listeners to ancestor(s) of the element so we can pick up style changes
4353
* based on CSS rules using descendant selectors.
4355
function initAncestorEventListeners() {
4356
var watch = el.currentStyle.getAttribute( PIE.CSS_PREFIX + 'watch-ancestors' ),
4359
watch = parseInt( watch, 10 );
4362
while( a && ( watch === 'NaN' || i++ < watch ) ) {
4363
addListener( a, 'onpropertychange', ancestorPropChanged );
4364
addListener( a, 'onmouseenter', mouseEntered );
4365
addListener( a, 'onmouseleave', mouseLeft );
4366
addListener( a, 'onmousedown', mousePressed );
4367
if( a.tagName in PIE.focusableElements ) {
4368
addListener( a, 'onfocus', focused );
4369
addListener( a, 'onblur', blurred );
4378
* If the target element is a first child, add a pie_first-child class to it. This allows using
4379
* the added class as a workaround for the fact that PIE's rendering element breaks the :first-child
4380
* pseudo-class selector.
4382
function initFirstChildPseudoClass() {
4385
while( tmpEl = tmpEl.previousSibling ) {
4386
if( tmpEl.nodeType === 1 ) {
4392
addClass( el, firstChildClass );
4397
// These methods are all already bound to this instance so there's no need to wrap them
4398
// in a closure to maintain the 'this' scope object when calling them.
4400
this.update = update;
4401
this.destroy = destroy;
4405
Element.getInstance = function( el ) {
4406
var id = PIE.Util.getUID( el );
4407
return wrappers[ id ] || ( wrappers[ id ] = new Element( el ) );
4410
Element.destroy = function( el ) {
4411
var id = PIE.Util.getUID( el ),
4412
wrapper = wrappers[ id ];
4415
delete wrappers[ id ];
4419
Element.destroyAll = function() {
4420
var els = [], wrapper;
4422
for( var w in wrappers ) {
4423
if( wrappers.hasOwnProperty( w ) ) {
4424
wrapper = wrappers[ w ];
4425
els.push( wrapper.el );
4438
* This file exposes the public API for invoking PIE.
4443
* @property supportsVML
4444
* True if the current IE browser environment has a functioning VML engine. Should be true
4445
* in most IEs, but in rare cases may be false. If false, PIE will exit immediately when
4446
* attached to an element; this property may be used for debugging or by external scripts
4447
* to perform some special action when VML support is absent.
4450
PIE[ 'supportsVML' ] = PIE.supportsVML;
4454
* Programatically attach PIE to a single element.
4455
* @param {Element} el
4457
PIE[ 'attach' ] = function( el ) {
4458
if (PIE.ieDocMode < 10 && PIE.supportsVML) {
4459
PIE.Element.getInstance( el ).init();
4465
* Programatically detach PIE from a single element.
4466
* @param {Element} el
4468
PIE[ 'detach' ] = function( el ) {
4469
PIE.Element.destroy( el );
b'\\ No newline at end of file'