source: branches/rel/html/test/kakinaka/js/dom/dom-debug.js @ 12157

Revision 12157, 34.3 KB checked in by uehara, 17 years ago (diff)
Line 
1/*
2Copyright (c) 2006, Yahoo! Inc. All rights reserved.
3Code licensed under the BSD License:
4http://developer.yahoo.net/yui/license.txt
5Version: 0.11.3
6*/
7
8/**
9 * @class Provides helper methods for DOM elements.
10 */
11YAHOO.util.Dom = function() {
12   var ua = navigator.userAgent.toLowerCase();
13   var isOpera = (ua.indexOf('opera') > -1);
14   var isSafari = (ua.indexOf('safari') > -1);
15   var isIE = (window.ActiveXObject);
16
17   var id_counter = 0;
18   var util = YAHOO.util; // internal shorthand
19   var property_cache = {}; // to cache case conversion for set/getStyle
20   var logger = {};
21   logger.log = function() {YAHOO.log.apply(window, arguments)};
22
23   var toCamel = function(property) {
24      var convert = function(prop) {
25         var test = /(-[a-z])/i.exec(prop);
26         return prop.replace(RegExp.$1, RegExp.$1.substr(1).toUpperCase());
27      };
28
29      while(property.indexOf('-') > -1) {
30         property = convert(property);
31      }
32
33      return property;
34      //return property.replace(/-([a-z])/gi, function(m0, m1) {return m1.toUpperCase()}) // cant use function as 2nd arg yet due to safari bug
35   };
36
37   var toHyphen = function(property) {
38      if (property.indexOf('-') > -1) { // assume hyphen
39         return property;
40      }
41
42      var converted = '';
43      for (var i = 0, len = property.length;i < len; ++i) {
44         if (property.charAt(i) == property.charAt(i).toUpperCase()) {
45            converted = converted + '-' + property.charAt(i).toLowerCase();
46         } else {
47            converted = converted + property.charAt(i);
48         }
49      }
50
51      return converted;
52      //return property.replace(/([a-z])([A-Z]+)/g, function(m0, m1, m2) {return (m1 + '-' + m2.toLowerCase())});
53   };
54
55   // improve performance by only looking up once
56   var cacheConvertedProperties = function(property) {
57      property_cache[property] = {
58         camel: toCamel(property),
59         hyphen: toHyphen(property)
60      };
61   };
62
63   return {
64      /**
65       * Returns an HTMLElement reference
66       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID for getting a DOM reference, an actual DOM reference, or an Array of IDs and/or HTMLElements.
67       * @return {HTMLElement/Array} A DOM reference to an HTML element or an array of HTMLElements.
68       */
69      get: function(el) {
70         if (!el) { return null; } // nothing to work with
71
72         if (typeof el != 'string' && !(el instanceof Array) ) { // assuming HTMLElement or HTMLCollection, so pass back as is
73            logger.log('get(' + el + ') returning ' + el, 'info', 'Dom');
74            return el;
75         }
76
77         if (typeof el == 'string') { // ID
78            logger.log('get("' + el + '") returning ' + document.getElementById(el), 'info', 'Dom');
79            return document.getElementById(el);
80         }
81         else { // array of ID's and/or elements
82            var collection = [];
83            for (var i = 0, len = el.length; i < len; ++i) {
84               collection[collection.length] = util.Dom.get(el[i]);
85            }
86
87            logger.log('get("' + el + '") returning ' + collection, 'info', 'Dom');
88            return collection;
89         }
90
91         logger.log('element ' + el + ' not found', 'error', 'Dom');
92         return null; // safety, should never happen
93      },
94
95      /**
96       * Normalizes currentStyle and ComputedStyle.
97       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
98       * @param {String} property The style property whose value is returned.
99       * @return {String/Array} The current value of the style property for the element(s).
100       */
101      getStyle: function(el, property) {
102         var f = function(el) {
103            var value = null;
104            var dv = document.defaultView;
105
106            if (!property_cache[property]) {
107               cacheConvertedProperties(property);
108            }
109
110            var camel = property_cache[property]['camel'];
111            var hyphen = property_cache[property]['hyphen'];
112
113            if (property == 'opacity' && el.filters) {// IE opacity
114               value = 1;
115               try {
116                  value = el.filters.item('DXImageTransform.Microsoft.Alpha').opacity / 100;
117               } catch(e) {
118                  try {
119                     value = el.filters.item('alpha').opacity / 100;
120                  } catch(e) {}
121               }
122            } else if (el.style[camel]) { // camelCase for valid styles
123               value = el.style[camel];
124            }
125            else if (isIE && el.currentStyle && el.currentStyle[camel]) { // camelCase for currentStyle; isIE to workaround broken Opera 9 currentStyle
126               value = el.currentStyle[camel];
127            }
128            else if ( dv && dv.getComputedStyle ) { // hyphen-case for computedStyle
129               var computed = dv.getComputedStyle(el, '');
130
131               if (computed && computed.getPropertyValue(hyphen)) {
132                  value = computed.getPropertyValue(hyphen);
133               }
134            }
135
136            logger.log('getStyle ' + property + ' returning ' + value, 'info', 'Dom');
137            return value;
138         };
139
140         return util.Dom.batch(el, f, util.Dom, true);
141      },
142
143      /**
144       * Wrapper for setting style properties of HTMLElements.  Normalizes "opacity" across modern browsers.
145       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
146       * @param {String} property The style property to be set.
147       * @param {String} val The value to apply to the given property.
148       */
149      setStyle: function(el, property, val) {
150         if (!property_cache[property]) {
151            cacheConvertedProperties(property);
152         }
153
154         var camel = property_cache[property]['camel'];
155
156         var f = function(el) {
157            switch(property) {
158               case 'opacity' :
159                  if (isIE && typeof el.style.filter == 'string') { // in case not appended
160                     el.style.filter = 'alpha(opacity=' + val * 100 + ')';
161
162                     if (!el.currentStyle || !el.currentStyle.hasLayout) {
163                        el.style.zoom = 1; // when no layout or cant tell
164                     }
165                  } else {
166                     el.style.opacity = val;
167                     el.style['-moz-opacity'] = val;
168                     el.style['-khtml-opacity'] = val;
169                  }
170
171                  break;
172               default :
173                  el.style[camel] = val;
174            }
175
176            logger.log('setStyle setting ' + property + ' to ' + val, 'info', 'Dom');
177
178         };
179
180         util.Dom.batch(el, f, util.Dom, true);
181      },
182
183      /**
184       * Gets the current position of an element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
185       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
186       @ return {Array} The XY position of the element(s)
187       */
188      getXY: function(el) {
189         var f = function(el) {
190
191         // has to be part of document to have pageXY
192            if (el.offsetParent === null || this.getStyle(el, 'display') == 'none') {
193               logger.log('getXY failed: element not available', 'error', 'Dom');
194               return false;
195            }
196
197            var parentNode = null;
198            var pos = [];
199            var box;
200
201            if (el.getBoundingClientRect) { // IE
202               box = el.getBoundingClientRect();
203               var doc = document;
204               if ( !this.inDocument(el) && parent.document != document) {// might be in a frame, need to get its scroll
205                  doc = parent.document;
206
207                  if ( !this.isAncestor(doc.documentElement, el) ) {
208                     logger.log('getXY failed: element not available', 'error', 'Dom');
209                     return false;
210                  }
211
212               }
213
214               var scrollTop = Math.max(doc.documentElement.scrollTop, doc.body.scrollTop);
215               var scrollLeft = Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft);
216
217               return [box.left + scrollLeft, box.top + scrollTop];
218            }
219            else { // safari, opera, & gecko
220               pos = [el.offsetLeft, el.offsetTop];
221               parentNode = el.offsetParent;
222               if (parentNode != el) {
223                  while (parentNode) {
224                     pos[0] += parentNode.offsetLeft;
225                     pos[1] += parentNode.offsetTop;
226                     parentNode = parentNode.offsetParent;
227                  }
228               }
229               if (isSafari && this.getStyle(el, 'position') == 'absolute' ) { // safari doubles in some cases
230                  pos[0] -= document.body.offsetLeft;
231                  pos[1] -= document.body.offsetTop;
232               }
233            }
234
235            if (el.parentNode) { parentNode = el.parentNode; }
236            else { parentNode = null; }
237
238            while (parentNode && parentNode.tagName.toUpperCase() != 'BODY' && parentNode.tagName.toUpperCase() != 'HTML')
239            { // account for any scrolled ancestors
240               if (util.Dom.getStyle(parentNode, 'display') != 'inline') { // work around opera inline scrollLeft/Top bug
241                  pos[0] -= parentNode.scrollLeft;
242                  pos[1] -= parentNode.scrollTop;
243               }
244
245               if (parentNode.parentNode) { parentNode = parentNode.parentNode; }
246               else { parentNode = null; }
247            }
248
249            logger.log('getXY returning ' + pos, 'info', 'Dom');
250
251            return pos;
252         };
253
254         return util.Dom.batch(el, f, util.Dom, true);
255      },
256
257      /**
258       * Gets the current X position of an element based on page coordinates.  The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
259       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
260       * @return {String/Array} The X position of the element(s)
261       */
262      getX: function(el) {
263         var f = function(el) {
264            return util.Dom.getXY(el)[0];
265         };
266
267         return util.Dom.batch(el, f, util.Dom, true);
268      },
269
270      /**
271       * Gets the current Y position of an element based on page coordinates.  Element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
272       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
273       * @return {String/Array} The Y position of the element(s)
274       */
275      getY: function(el) {
276         var f = function(el) {
277            return util.Dom.getXY(el)[1];
278         };
279
280         return util.Dom.batch(el, f, util.Dom, true);
281      },
282
283      /**
284       * Set the position of an html element in page coordinates, regardless of how the element is positioned.
285       * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
286       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements
287       * @param {Array} pos Contains X & Y values for new position (coordinates are page-based)
288       * @param {Boolean} noRetry By default we try and set the position a second time if the first fails
289       */
290      setXY: function(el, pos, noRetry) {
291         var f = function(el) {
292            var style_pos = this.getStyle(el, 'position');
293            if (style_pos == 'static') { // default to relative
294               this.setStyle(el, 'position', 'relative');
295               style_pos = 'relative';
296            }
297
298            var pageXY = this.getXY(el);
299            if (pageXY === false) { // has to be part of doc to have pageXY
300               logger.log('setXY failed: element not available', 'error', 'Dom');
301               return false;
302            }
303
304            var delta = [ // assuming pixels; if not we will have to retry
305               parseInt( this.getStyle(el, 'left'), 10 ),
306               parseInt( this.getStyle(el, 'top'), 10 )
307            ];
308
309            if ( isNaN(delta[0]) ) {// in case of 'auto'
310               delta[0] = (style_pos == 'relative') ? 0 : el.offsetLeft;
311            }
312            if ( isNaN(delta[1]) ) { // in case of 'auto'
313               delta[1] = (style_pos == 'relative') ? 0 : el.offsetTop;
314            }
315
316            if (pos[0] !== null) { el.style.left = pos[0] - pageXY[0] + delta[0] + 'px'; }
317            if (pos[1] !== null) { el.style.top = pos[1] - pageXY[1] + delta[1] + 'px'; }
318
319            var newXY = this.getXY(el);
320
321            // if retry is true, try one more time if we miss
322            if (!noRetry && (newXY[0] != pos[0] || newXY[1] != pos[1]) ) {
323               this.setXY(el, pos, true);
324            }
325
326            logger.log('setXY setting position to ' + pos, 'info', 'Dom');
327         };
328
329         util.Dom.batch(el, f, util.Dom, true);
330      },
331
332      /**
333       * Set the X position of an html element in page coordinates, regardless of how the element is positioned.
334       * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
335       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
336       * @param {Int} x to use as the X coordinate for the element(s).
337       */
338      setX: function(el, x) {
339         util.Dom.setXY(el, [x, null]);
340      },
341
342      /**
343       * Set the Y position of an html element in page coordinates, regardless of how the element is positioned.
344       * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false).
345       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
346       * @param {Int} x to use as the Y coordinate for the element(s).
347       */
348      setY: function(el, y) {
349         util.Dom.setXY(el, [null, y]);
350      },
351
352      /**
353       * Returns the region position of the given element.
354       * The element must be part of the DOM tree to have a region (display:none or elements not appended return false).
355       * @param {String/HTMLElement/Array} el Accepts a string to use as an ID, an actual DOM reference, or an Array of IDs and/or HTMLElements.
356       * @return {Region/Array} A Region or array of Region instances containing "top, left, bottom, right" member data.
357       */
358      getRegion: function(el) {
359         var f = function(el) {
360            var region = new YAHOO.util.Region.getRegion(el);
361            logger.log('getRegion returning ' + region, 'info', 'Dom');
362            return region;
363         };
364
365         return util.Dom.batch(el, f, util.Dom, true);
366      },
367
368      /**
369       * Returns the width of the client (viewport).
370       * Now using getViewportWidth.  This interface left intact for back compat.
371       * @return {Int} The width of the viewable area of the page.
372       */
373      getClientWidth: function() {
374         return util.Dom.getViewportWidth();
375      },
376
377      /**
378       * Returns the height of the client (viewport).
379       * Now using getViewportHeight.  This interface left intact for back compat.
380       * @return {Int} The height of the viewable area of the page.
381       */
382      getClientHeight: function() {
383         return util.Dom.getViewportHeight();
384      },
385
386      /**
387       * Returns a array of HTMLElements with the given class
388       * For optimized performance, include a tag and/or root node if possible
389       * @param {String} className The class name to match against
390       * @param {String} tag (optional) The tag name of the elements being collected
391       * @param {String/HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
392       * @return {Array} An array of elements that have the given class name
393       */
394      getElementsByClassName: function(className, tag, root) {
395         var method = function(el) { return util.Dom.hasClass(el, className) };
396         return util.Dom.getElementsBy(method, tag, root);
397      },
398
399      /**
400       * Determines whether an HTMLElement has the given className
401       * @param {String/HTMLElement/Array} el The element or collection to test
402       * @param {String} className the class name to search for
403       * @return {Boolean/Array} A boolean value or array of boolean values
404       */
405      hasClass: function(el, className) {
406         var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
407
408         var f = function(el) {
409            logger.log('hasClass returning ' + re.test(el['className']), 'info', 'Dom');
410            return re.test(el['className']);
411         };
412
413         return util.Dom.batch(el, f, util.Dom, true);
414      },
415
416      /**
417       * Adds a class name to a given element or collection of elements
418       * @param {String/HTMLElement/Array} el The element or collection to add the class to
419       * @param {String} className the class name to add to the class attribute
420       */
421      addClass: function(el, className) {
422         var f = function(el) {
423            if (this.hasClass(el, className)) { return; } // already present
424
425            logger.log('addClass adding ' + className, 'info', 'Dom');
426
427            el['className'] = [el['className'], className].join(' ');
428         };
429
430         util.Dom.batch(el, f, util.Dom, true);
431      },
432
433      /**
434       * Removes a class name from a given element or collection of elements
435       * @param {String/HTMLElement/Array} el The element or collection to remove the class from
436       * @param {String} className the class name to remove from the class attribute
437       */
438      removeClass: function(el, className) {
439         var re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', 'g');
440
441         var f = function(el) {
442            if (!this.hasClass(el, className)) { return; } // not present
443
444            logger.log('removeClass removing ' + className, 'info', 'Dom');
445
446            var c = el['className'];
447            el['className'] = c.replace(re, ' ');
448            if ( this.hasClass(el, className) ) { // in case of multiple adjacent
449               this.removeClass(el, className);
450            }
451
452         };
453
454         util.Dom.batch(el, f, util.Dom, true);
455      },
456
457      /**
458       * Replace a class with another class for a given element or collection of elements.
459       * If no oldClassName is present, the newClassName is simply added.
460       * @param {String/HTMLElement/Array} el The element or collection to remove the class from
461       * @param {String} oldClassName the class name to be replaced
462       * @param {String} newClassName the class name that will be replacing the old class name
463       */
464      replaceClass: function(el, oldClassName, newClassName) {
465         if (oldClassName === newClassName) { // avoid infinite loop
466            return false;
467         };
468
469         var re = new RegExp('(?:^|\\s+)' + oldClassName + '(?:\\s+|$)', 'g');
470
471         var f = function(el) {
472            logger.log('replaceClass replacing ' + oldClassName + ' with ' + newClassName, 'info', 'Dom');
473
474            if ( !this.hasClass(el, oldClassName) ) {
475               this.addClass(el, newClassName); // just add it if nothing to replace
476               return; // note return
477            }
478
479            el['className'] = el['className'].replace(re, ' ' + newClassName + ' ');
480
481            if ( this.hasClass(el, oldClassName) ) { // in case of multiple adjacent
482               this.replaceClass(el, oldClassName, newClassName);
483            }
484         };
485
486         util.Dom.batch(el, f, util.Dom, true);
487      },
488
489      /**
490       * Generates a unique ID
491       * @param {String/HTMLElement/Array} el (optional) An optional element array of elements to add an ID to (no ID is added if one is already present)
492       * @param {String} prefix (optional) an optional prefix to use (defaults to "yui-gen")
493       * @return {String/Array} The generated ID, or array of generated IDs (or original ID if already present on an element)
494       */
495      generateId: function(el, prefix) {
496         prefix = prefix || 'yui-gen';
497         el = el || {};
498
499         var f = function(el) {
500            if (el) {
501               el = util.Dom.get(el);
502            } else {
503               el = {}; // just generating ID in this case
504            }
505
506            if (!el.id) {
507               el.id = prefix + id_counter++;
508               logger.log('generateId generating ' + el.id, 'info', 'Dom');
509            } // dont override existing
510
511            logger.log('generateId returning ' + el.id, 'info', 'Dom');
512
513            return el.id;
514         };
515
516         return util.Dom.batch(el, f, util.Dom, true);
517      },
518
519      /**
520       * Determines whether an HTMLElement is an ancestor of another HTML element in the DOM hierarchy
521       * @param {String/HTMLElement} haystack The possible ancestor
522       * @param {String/HTMLElement} needle The possible descendent
523       * @return {Boolean} Whether or not the haystack is an ancestor of needle
524       */
525      isAncestor: function(haystack, needle) {
526         haystack = util.Dom.get(haystack);
527         if (!haystack || !needle) { return false; }
528
529         var f = function(needle) {
530            if (haystack.contains && !isSafari) { // safari "contains" is broken
531               logger.log('isAncestor returning ' + haystack.contains(needle), 'info', 'Dom');
532               return haystack.contains(needle);
533            }
534            else if ( haystack.compareDocumentPosition ) {
535               logger.log('isAncestor returning ' + !!(haystack.compareDocumentPosition(needle) & 16), 'info', 'Dom');
536               return !!(haystack.compareDocumentPosition(needle) & 16);
537            }
538            else { // loop up and test each parent
539               var parent = needle.parentNode;
540
541               while (parent) {
542                  if (parent == haystack) {
543                     logger.log('isAncestor returning true', 'info', 'Dom');
544                     return true;
545                  }
546                  else if (!parent.tagName || parent.tagName.toUpperCase() == 'HTML') {
547                     logger.log('isAncestor returning false', 'info', 'Dom');
548                     return false;
549                  }
550
551                  parent = parent.parentNode;
552               }
553               logger.log('isAncestor returning false', 'info', 'Dom');
554               return false;
555            }
556         };
557
558         return util.Dom.batch(needle, f, util.Dom, true);
559      },
560
561      /**
562       * Determines whether an HTMLElement is present in the current document
563       * @param {String/HTMLElement} el The element to search for
564       * @return {Boolean} Whether or not the element is present in the current document
565       */
566      inDocument: function(el) {
567         var f = function(el) {
568            return this.isAncestor(document.documentElement, el);
569         };
570
571         return util.Dom.batch(el, f, util.Dom, true);
572      },
573
574      /**
575       * Returns a array of HTMLElements that pass the test applied by supplied boolean method
576       * For optimized performance, include a tag and/or root node if possible
577       * @param {Function} method A boolean method to test elements with
578       * @param {String} tag (optional) The tag name of the elements being collected
579       * @param {String/HTMLElement} root (optional) The HTMLElement or an ID to use as the starting point
580       */
581      getElementsBy: function(method, tag, root) {
582         tag = tag || '*';
583         root = util.Dom.get(root) || document;
584
585         var nodes = [];
586         var elements = root.getElementsByTagName(tag);
587
588         if ( !elements.length && (tag == '*' && root.all) ) {
589            elements = root.all; // IE < 6
590         }
591
592         for (var i = 0, len = elements.length; i < len; ++i)
593         {
594            if ( method(elements[i]) ) { nodes[nodes.length] = elements[i]; }
595         }
596
597         logger.log('getElementsBy returning ' + nodes, 'info', 'Dom');
598
599         return nodes;
600      },
601
602      /**
603       * Returns an array of elements that have had the supplied method applied.
604       * The method is called with the element(s) as the first arg, and the optional param as the second ( method(el, o) )
605       * @param {String/HTMLElement/Array} el (optional) An element or array of elements to apply the method to
606       * @param {Function} method The method to apply to the element(s)
607       * @param {Generic} (optional) o An optional arg that is passed to the supplied method
608       * @param {Boolean} (optional) override Whether or not to override the scope of "method" with "o"
609       * @return {HTMLElement/Array} The element(s) with the method applied
610       */
611      batch: function(el, method, o, override) {
612         var id = el;
613         el = util.Dom.get(el);
614
615         var scope = (override) ? o : window;
616
617         if (!el || el.tagName || !el.length) { // is null or not a collection (tagName for SELECT and others that can be both an element and a collection)
618            if (!el) {
619               logger.log(id + ' not available', 'error', 'Dom');
620               return false;
621            }
622            return method.call(scope, el, o);
623         }
624
625         var collection = [];
626
627         for (var i = 0, len = el.length; i < len; ++i) {
628            if (!el[i]) {
629               id = id[i];
630               logger.log(id + ' not available', 'error', 'Dom');
631            }
632            collection[collection.length] = method.call(scope, el[i], o);
633         }
634
635         return collection;
636      },
637
638      /**
639       * Returns the height of the document.
640       * @return {Int} The height of the actual document (which includes the body and its margin).
641       */
642      getDocumentHeight: function() {
643         var scrollHeight=-1,windowHeight=-1,bodyHeight=-1;
644         var marginTop = parseInt(util.Dom.getStyle(document.body, 'marginTop'), 10);
645         var marginBottom = parseInt(util.Dom.getStyle(document.body, 'marginBottom'), 10);
646
647         var mode = document.compatMode;
648
649         if ( (mode || isIE) && !isOpera ) { // (IE, Gecko)
650            switch (mode) {
651               case 'CSS1Compat': // Standards mode
652                  scrollHeight = ((window.innerHeight && window.scrollMaxY) ?  window.innerHeight+window.scrollMaxY : -1);
653                  windowHeight = [document.documentElement.clientHeight,self.innerHeight||-1].sort(function(a, b){return(a-b);})[1];
654                  bodyHeight = document.body.offsetHeight + marginTop + marginBottom;
655                  break;
656
657               default: // Quirks
658                  scrollHeight = document.body.scrollHeight;
659                  bodyHeight = document.body.clientHeight;
660            }
661         } else { // Safari & Opera
662            scrollHeight = document.documentElement.scrollHeight;
663            windowHeight = self.innerHeight;
664            bodyHeight = document.documentElement.clientHeight;
665         }
666
667         var h = [scrollHeight,windowHeight,bodyHeight].sort(function(a, b){return(a-b);});
668         logger.log('getDocumentHeight returning ' + h[2], 'info', 'Dom');
669         return h[2];
670      },
671
672      /**
673       * Returns the width of the document.
674       * @return {Int} The width of the actual document (which includes the body and its margin).
675       */
676      getDocumentWidth: function() {
677         var docWidth=-1,bodyWidth=-1,winWidth=-1;
678         var marginRight = parseInt(util.Dom.getStyle(document.body, 'marginRight'), 10);
679         var marginLeft = parseInt(util.Dom.getStyle(document.body, 'marginLeft'), 10);
680
681         var mode = document.compatMode;
682
683         if (mode || isIE) { // (IE, Gecko, Opera)
684            switch (mode) {
685               case 'CSS1Compat': // Standards mode
686                  docWidth = document.documentElement.clientWidth;
687                  bodyWidth = document.body.offsetWidth + marginLeft + marginRight;
688                  break;
689
690               default: // Quirks
691                  bodyWidth = document.body.clientWidth;
692                  docWidth = document.body.scrollWidth;
693                  break;
694            }
695         } else { // Safari
696            docWidth = document.documentElement.clientWidth;
697            bodyWidth = document.body.offsetWidth + marginLeft + marginRight;
698         }
699
700         var w = Math.max(docWidth, bodyWidth);
701         logger.log('getDocumentWidth returning ' + w[2], 'info', 'Dom');
702         return w;
703      },
704
705      /**
706       * Returns the current height of the viewport.
707       * @return {Int} The height of the viewable area of the page (excludes scrollbars).
708       */
709      getViewportHeight: function() {
710         var height = -1;
711         var mode = document.compatMode;
712
713         if ( (mode || isIE) && !isOpera ) {
714            switch (mode) { // (IE, Gecko)
715               case 'CSS1Compat': // Standards mode
716                  height = document.documentElement.clientHeight;
717                  break;
718
719               default: // Quirks
720                  height = document.body.clientHeight;
721            }
722         } else { // Safari, Opera
723            height = self.innerHeight;
724         }
725
726         logger.log('getViewportHeight returning ' + height, 'info', 'Dom');
727         return height;
728      },
729
730      /**
731       * Returns the current width of the viewport.
732       * @return {Int} The width of the viewable area of the page (excludes scrollbars).
733       */
734
735      getViewportWidth: function() {
736         var width = -1;
737         var mode = document.compatMode;
738
739         if (mode || isIE) { // (IE, Gecko, Opera)
740            switch (mode) {
741            case 'CSS1Compat': // Standards mode
742               width = document.documentElement.clientWidth;
743               break;
744
745            default: // Quirks
746               width = document.body.clientWidth;
747            }
748         } else { // Safari
749            width = self.innerWidth;
750         }
751         logger.log('getViewportWidth returning ' + width, 'info', 'Dom');
752         return width;
753      }
754   };
755}();
756
757/**
758 * @class A region is a representation of an object on a grid.  It is defined
759 * by the top, right, bottom, left extents, so is rectangular by default.  If
760 * other shapes are required, this class could be extended to support it.
761 *
762 * @param {int} t the top extent
763 * @param {int} r the right extent
764 * @param {int} b the bottom extent
765 * @param {int} l the left extent
766 * @constructor
767 */
768YAHOO.util.Region = function(t, r, b, l) {
769
770    /**
771     * The region's top extent
772     * @type int
773     */
774    this.top = t;
775
776    /**
777     * The region's top extent as index, for symmetry with set/getXY
778     * @type int
779     */
780    this[1] = t;
781
782    /**
783     * The region's right extent
784     * @type int
785     */
786    this.right = r;
787
788    /**
789     * The region's bottom extent
790     * @type int
791     */
792    this.bottom = b;
793
794    /**
795     * The region's left extent
796     * @type int
797     */
798    this.left = l;
799
800    /**
801     * The region's left extent as index, for symmetry with set/getXY
802     * @type int
803     */
804    this[0] = l;
805};
806
807/**
808 * Returns true if this region contains the region passed in
809 *
810 * @param  {Region}  region The region to evaluate
811 * @return {boolean}        True if the region is contained with this region,
812 *                          else false
813 */
814YAHOO.util.Region.prototype.contains = function(region) {
815    return ( region.left   >= this.left   &&
816             region.right  <= this.right  &&
817             region.top    >= this.top    &&
818             region.bottom <= this.bottom    );
819
820    // this.logger.debug("does " + this + " contain " + region + " ... " + ret);
821};
822
823/**
824 * Returns the area of the region
825 *
826 * @return {int} the region's area
827 */
828YAHOO.util.Region.prototype.getArea = function() {
829    return ( (this.bottom - this.top) * (this.right - this.left) );
830};
831
832/**
833 * Returns the region where the passed in region overlaps with this one
834 *
835 * @param  {Region} region The region that intersects
836 * @return {Region}        The overlap region, or null if there is no overlap
837 */
838YAHOO.util.Region.prototype.intersect = function(region) {
839    var t = Math.max( this.top,    region.top    );
840    var r = Math.min( this.right,  region.right  );
841    var b = Math.min( this.bottom, region.bottom );
842    var l = Math.max( this.left,   region.left   );
843
844    if (b >= t && r >= l) {
845        return new YAHOO.util.Region(t, r, b, l);
846    } else {
847        return null;
848    }
849};
850
851/**
852 * Returns the region representing the smallest region that can contain both
853 * the passed in region and this region.
854 *
855 * @param  {Region} region The region that to create the union with
856 * @return {Region}        The union region
857 */
858YAHOO.util.Region.prototype.union = function(region) {
859    var t = Math.min( this.top,    region.top    );
860    var r = Math.max( this.right,  region.right  );
861    var b = Math.max( this.bottom, region.bottom );
862    var l = Math.min( this.left,   region.left   );
863
864    return new YAHOO.util.Region(t, r, b, l);
865};
866
867/**
868 * toString
869 * @return string the region properties
870 */
871YAHOO.util.Region.prototype.toString = function() {
872    return ( "Region {"    +
873             "top: "       + this.top    +
874             ", right: "   + this.right  +
875             ", bottom: "  + this.bottom +
876             ", left: "    + this.left   +
877             "}" );
878};
879
880/**
881 * Returns a region that is occupied by the DOM element
882 *
883 * @param  {HTMLElement} el The element
884 * @return {Region}         The region that the element occupies
885 * @static
886 */
887YAHOO.util.Region.getRegion = function(el) {
888    var p = YAHOO.util.Dom.getXY(el);
889
890    var t = p[1];
891    var r = p[0] + el.offsetWidth;
892    var b = p[1] + el.offsetHeight;
893    var l = p[0];
894
895    return new YAHOO.util.Region(t, r, b, l);
896};
897
898/////////////////////////////////////////////////////////////////////////////
899
900
901/**
902 * @class
903 *
904 * A point is a region that is special in that it represents a single point on
905 * the grid.
906 *
907 * @param {int} x The X position of the point
908 * @param {int} y The Y position of the point
909 * @constructor
910 * @extends Region
911 */
912YAHOO.util.Point = function(x, y) {
913   if (x instanceof Array) { // accept output from Dom.getXY
914      y = x[1];
915      x = x[0];
916   }
917
918    /**
919     * The X position of the point, which is also the right, left and index zero (for Dom.getXY symmetry)
920     * @type int
921     */
922
923    this.x = this.right = this.left = this[0] = x;
924
925    /**
926     * The Y position of the point, which is also the top, bottom and index one (for Dom.getXY symmetry)
927     * @type int
928     */
929    this.y = this.top = this.bottom = this[1] = y;
930};
931
932YAHOO.util.Point.prototype = new YAHOO.util.Region();
933
Note: See TracBrowser for help on using the repository browser.