Debian Codegraph @

closure-library/closure/goog/ui/scrollfloater.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Class for making an element detach and float to remain visible
17 * even when the viewport has been scrolled.
18 * <p>
19 * The element remains at its normal position in the layout until scrolling
20 * would cause its top edge to scroll off the top of the viewport; at that
21 * point, the element is replaced with an invisible placeholder (to keep the
22 * layout stable), reattached in the dom tree to a new parent (the body element
23 * by default), and set to "fixed" positioning (emulated for IE < 7) so that it
24 * remains at its original X position while staying fixed to the top of the
25 * viewport in the Y dimension.
26 * <p>
27 * When the window is scrolled up past the point where the original element
28 * would be fully visible again, the element snaps back into place, replacing
29 * the placeholder.
30 *
31 * @see ../demos/scrollfloater.html
32 *
33 * Adapted from http://go/elementfloater.js
34 */
35
36
37 goog.provide('goog.ui.ScrollFloater');
38 goog.provide('goog.ui.ScrollFloater.EventType');
39
40 goog.require('goog.array');
41 goog.require('goog.asserts');
42 goog.require('goog.dom');
43 goog.require('goog.dom.TagName');
44 goog.require('goog.dom.classlist');
45 goog.require('goog.events.EventType');
46 goog.require('goog.style');
47 goog.require('goog.ui.Component');
48 goog.require('goog.userAgent');
49
50
51
52 /**
53 * Creates a ScrollFloater; see file overview for details.
54 *
55 * @param {Element=} opt_parentElement Where to attach the element when it's
56 * floating. Default is the document body. If the floating element
57 * contains form inputs, it will be necessary to attach it to the
58 * corresponding form element, or to an element in the DOM subtree under
59 * the form element.
60 * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
61 * @constructor
62 * @extends {goog.ui.Component}
63 */
64 goog.ui.ScrollFloater = function(opt_parentElement, opt_domHelper) {
65 // If a parentElement is supplied, we want to use its domHelper,
66 // ignoring the caller-supplied one.
67 var domHelper = opt_parentElement ? goog.dom.getDomHelper(opt_parentElement) :
68 opt_domHelper;
69
70 goog.ui.ScrollFloater.base(this, 'constructor', domHelper);
71
72 /**
73 * The element to which the scroll-floated element will be attached
74 * when it is floating.
75 * @type {Element}
76 * @private
77 */
78 this.parentElement_ =
79 opt_parentElement || this.getDomHelper().getDocument().body;
80
81 /**
82 * The original styles applied to the element before it began floating;
83 * used to restore those styles when the element stops floating.
84 * @type {Object}
85 * @private
86 */
87 this.originalStyles_ = {};
88
89 /**
90 * A vertical offset from which to start floating the element. This is
91 * useful in cases when there are 'position:fixed' elements covering up
92 * part of the viewport.
93 * @type {number}
94 * @private
95 */
96 this.viewportTopOffset_ = 0;
97
98 /**
99 * An element used to define the boundaries within which the floater can
100 * be positioned.
101 * @type {Element}
102 * @private
103 */
104 this.containerElement_ = null;
105
106 /**
107 * Container element's bounding rectangle.
108 * @type {goog.math.Rect}
109 * @private
110 */
111 this.containerBounds_ = null;
112
113 /**
114 * Element's original bounding rectangle.
115 * @type {goog.math.Rect}
116 * @private
117 */
118 this.originalBounds_ = null;
119
120 /**
121 * Element's top offset when it's not floated or pinned.
122 * @type {number}
123 * @private
124 */
125 this.originalTopOffset_ = 0;
126
127 /**
128 * Element's left offset when it's not floated or pinned.
129 * @type {number}
130 * @private
131 */
132 this.originalLeftOffset_ = 0;
133
134 /**
135 * The placeholder element dropped in to hold the layout for
136 * the floated element.
137 * @type {Element}
138 * @private
139 */
140 this.placeholder_ = null;
141
142 /**
143 * Whether scrolling is enabled for this element; true by default.
144 * The {@link #setScrollingEnabled} method can be used to change this value.
145 * @type {boolean}
146 * @private
147 */
148 this.scrollingEnabled_ = true;
149
150 /**
151 * A flag indicating whether this instance is currently pinned to the bottom
152 * of the container element.
153 * @type {boolean}
154 * @private
155 */
156 this.pinned_ = false;
157
158 /**
159 * A flag indicating whether this instance is currently floating.
160 * @type {boolean}
161 * @private
162 */
163 this.floating_ = false;
164 };
165 goog.inherits(goog.ui.ScrollFloater, goog.ui.Component);
166
167
168 /**
169 * Events dispatched by this component.
170 * @enum {string}
171 */
172 goog.ui.ScrollFloater.EventType = {
173 /**
174 * Dispatched when the component starts floating. The event is
175 * cancellable.
176 */
177 FLOAT: 'float',
178
179 /**
180 * Dispatched when the component returns to its original state.
181 * The event is cancellable.
182 */
183 DOCK: 'dock',
184
185 /**
186 * Dispatched when the component gets pinned to the bottom of the
187 * container element. This event is cancellable.
188 */
189 PIN: 'pin'
190 };
191
192
193 /**
194 * The element can float at different positions on the page.
195 * @enum {number}
196 * @private
197 */
198 goog.ui.ScrollFloater.FloatMode_ = {
199 TOP: 0,
200 BOTTOM: 1
201 };
202
203
204 /**
205 * The style properties which are stored when we float an element, so they
206 * can be restored when it 'docks' again.
207 * @type {Array<string>}
208 * @private
209 */
210 goog.ui.ScrollFloater.STORED_STYLE_PROPS_ =
211 ['position', 'top', 'left', 'width', 'cssFloat'];
212
213
214 /**
215 * The style elements managed for the placeholder object.
216 * @type {Array<string>}
217 * @private
218 */
219 goog.ui.ScrollFloater.PLACEHOLDER_STYLE_PROPS_ = [
220 'position', 'top', 'left', 'display', 'cssFloat', 'marginTop', 'marginLeft',
221 'marginRight', 'marginBottom'
222 ];
223
224
225 /**
226 * The class name applied to the floating element.
227 * @type {string}
228 * @private
229 */
230 goog.ui.ScrollFloater.CSS_CLASS_ = goog.getCssName('goog-scrollfloater');
231
232
233 /**
234 * Delegates dom creation to superclass, then constructs and
235 * decorates required DOM elements.
236 * @override
237 */
238 goog.ui.ScrollFloater.prototype.createDom = function() {
239 goog.ui.ScrollFloater.base(this, 'createDom');
240
241 this.decorateInternal(this.getElement());
242 };
243
244
245 /**
246 * Decorates the floated element with the standard ScrollFloater CSS class.
247 * @param {Element} element The element to decorate.
248 * @override
249 */
250 goog.ui.ScrollFloater.prototype.decorateInternal = function(element) {
251 goog.ui.ScrollFloater.base(this, 'decorateInternal', element);
252 goog.asserts.assert(element);
253 goog.dom.classlist.add(element, goog.ui.ScrollFloater.CSS_CLASS_);
254 };
255
256
257 /** @override */
258 goog.ui.ScrollFloater.prototype.enterDocument = function() {
259 goog.ui.ScrollFloater.base(this, 'enterDocument');
260
261 if (!this.placeholder_) {
262 this.placeholder_ = this.getDomHelper().createDom(
263 goog.dom.TagName.DIV, {'style': 'visibility:hidden'});
264 }
265
266 this.update();
267
268 this.setScrollingEnabled(this.scrollingEnabled_);
269 var win = this.getDomHelper().getWindow();
270 this.getHandler()
271 .listen(win, goog.events.EventType.SCROLL, this.handleScroll_)
272 .listen(win, goog.events.EventType.RESIZE, this.update);
273 };
274
275
276 /**
277 * Forces the component to update the cached element positions and sizes and
278 * to re-evaluate whether the the component should be docked, floated or
279 * pinned.
280 */
281 goog.ui.ScrollFloater.prototype.update = function() {
282 if (!this.isInDocument()) {
283 return;
284 }
285
286 // These values can only be calculated when the element is in its original
287 // state, so we dock first, and then re-evaluate.
288 this.dock_();
289 if (this.containerElement_) {
290 this.containerBounds_ = goog.style.getBounds(this.containerElement_);
291 }
292 var pageOffset_ = goog.style.getPageOffset(this.getElement());
293 this.originalBounds_ = goog.style.getBounds(this.getElement());
294 this.originalTopOffset_ = pageOffset_.y;
295 this.originalLeftOffset_ = pageOffset_.x;
296 this.handleScroll_();
297 };
298
299
300 /** @override */
301 goog.ui.ScrollFloater.prototype.disposeInternal = function() {
302 goog.ui.ScrollFloater.base(this, 'disposeInternal');
303
304 this.placeholder_ = null;
305 };
306
307
308 /**
309 * Sets whether the element should be floated if it scrolls out of view.
310 * @param {boolean} enable Whether floating is enabled for this element.
311 */
312 goog.ui.ScrollFloater.prototype.setScrollingEnabled = function(enable) {
313 this.scrollingEnabled_ = enable;
314
315 if (enable) {
316 this.applyIeBgHack_();
317 this.handleScroll_();
318 } else {
319 this.dock_();
320 }
321 };
322
323
324 /**
325 * @return {boolean} Whether the component is enabled for scroll-floating.
326 */
327 goog.ui.ScrollFloater.prototype.isScrollingEnabled = function() {
328 return this.scrollingEnabled_;
329 };
330
331
332 /**
333 * @return {boolean} Whether the component is currently scroll-floating.
334 */
335 goog.ui.ScrollFloater.prototype.isFloating = function() {
336 return this.floating_;
337 };
338
339
340 /**
341 * @return {boolean} Whether the component is currently pinned to the bottom
342 * of the container.
343 */
344 goog.ui.ScrollFloater.prototype.isPinned = function() {
345 return this.pinned_;
346 };
347
348
349 /**
350 * @param {number} offset A vertical offset from the top of the viewport, from
351 * which to start floating the element. Default is 0. This is useful in cases
352 * when there are 'position:fixed' elements covering up part of the viewport.
353 */
354 goog.ui.ScrollFloater.prototype.setViewportTopOffset = function(offset) {
355 this.viewportTopOffset_ = offset;
356 this.update();
357 };
358
359
360 /**
361 * @param {Element} container An element used to define the boundaries within
362 * which the floater can be positioned. If not specified, scrolling the page
363 * down far enough may result in the floated element extending past the
364 * containing element as it is being scrolled out of the viewport. In some
365 * cases, such as a list with a sticky header, this may be undesirable. If
366 * the container element is specified and the floated element extends past
367 * the bottom of the container, the element will be pinned to the bottom of
368 * the container.
369 */
370 goog.ui.ScrollFloater.prototype.setContainerElement = function(container) {
371 this.containerElement_ = container;
372 this.update();
373 };
374
375
376 /**
377 * When a scroll event occurs, compares the element's position to the current
378 * document scroll position, and stops or starts floating behavior if needed.
379 * @param {goog.events.Event=} opt_e The event, which is ignored.
380 * @private
381 */
382 goog.ui.ScrollFloater.prototype.handleScroll_ = function(opt_e) {
383 if (this.scrollingEnabled_) {
384 var scrollTop = this.getDomHelper().getDocumentScroll().y;
385
386 if (this.originalBounds_.top - scrollTop >= this.viewportTopOffset_) {
387 this.dock_();
388 return;
389 }
390
391 var effectiveElementHeight =
392 this.originalBounds_.height + this.viewportTopOffset_;
393
394 // If the element extends past the container, we need to pin it instead.
395 if (this.containerElement_) {
396 var containerBottom =
397 this.containerBounds_.top + this.containerBounds_.height;
398
399 if (scrollTop > containerBottom - effectiveElementHeight) {
400 this.pin_();
401 return;
402 }
403 }
404
405 var windowHeight = this.getDomHelper().getViewportSize().height;
406
407 // If the element is shorter than the window or the user uses IE < 7,
408 // float it at the top.
409 if (this.needsIePositionHack_() || effectiveElementHeight < windowHeight) {
410 this.float_(goog.ui.ScrollFloater.FloatMode_.TOP);
411 return;
412 }
413
414 // If the element is taller than the window and is extending past the
415 // bottom, allow it scroll with the page until the bottom of the element is
416 // fully visible.
417 if (this.originalBounds_.height + this.originalTopOffset_ >
418 windowHeight + scrollTop) {
419 this.dock_();
420 } else {
421 // Pin the element to the bottom of the page since the user has scrolled
422 // past it.
423 this.float_(goog.ui.ScrollFloater.FloatMode_.BOTTOM);
424 }
425 }
426 };
427
428
429 /**
430 * Pins the element to the bottom of the container, making as much of the
431 * element visible as possible without extending past it.
432 * @private
433 */
434 goog.ui.ScrollFloater.prototype.pin_ = function() {
435 if (this.floating_ && !this.dock_()) {
436 return;
437 }
438
439 // Ignore if the component is pinned or the PIN event is cancelled.
440 if (this.pinned_ ||
441 !this.dispatchEvent(goog.ui.ScrollFloater.EventType.PIN)) {
442 return;
443 }
444
445 var elem = this.getElement();
446
447 this.storeOriginalStyles_();
448
449 elem.style.position = 'relative';
450 elem.style.top = this.containerBounds_.height - this.originalBounds_.height -
451 this.originalBounds_.top + this.containerBounds_.top + 'px';
452
453 this.pinned_ = true;
454 };
455
456
457 /**
458 * Begins floating behavior, making the element position:fixed (or IE hacked
459 * equivalent) and inserting a placeholder where it used to be to keep the
460 * layout from shifting around. For IE < 7 users, we only support floating at
461 * the top.
462 * @param {goog.ui.ScrollFloater.FloatMode_} floatMode The position at which we
463 * should float.
464 * @private
465 */
466 goog.ui.ScrollFloater.prototype.float_ = function(floatMode) {
467 var isTop = floatMode == goog.ui.ScrollFloater.FloatMode_.TOP;
468 if (this.pinned_ && !this.dock_()) {
469 return;
470 }
471
472 // Ignore if the FLOAT event is cancelled.
473 if (!this.dispatchEvent(goog.ui.ScrollFloater.EventType.FLOAT)) {
474 return;
475 }
476
477 // If the component is already floating, only update the left position.
478 var newWindowLeftOffset_ = goog.dom.getDocumentScroll().x;
479 if (this.floating_) {
480 this.updateFloatingLeftPosition_();
481 return;
482 }
483
484 var elem = /** @type {!HTMLElement} */ (this.getElement());
485
486 // Read properties of element before modifying it.
487 var originalLeft_ = goog.style.getPageOffsetLeft(elem);
488 var originalWidth_ = goog.style.getContentBoxSize(elem).width;
489
490 this.storeOriginalStyles_();
491
492 goog.style.setSize(this.placeholder_, elem.offsetWidth, elem.offsetHeight);
493
494 // Make element float.
495 goog.style.setStyle(elem, {
496 'left': (originalLeft_ - newWindowLeftOffset_) + 'px',
497 'width': originalWidth_ + 'px',
498 'cssFloat': 'none'
499 });
500
501 // If parents are the same, avoid detaching and reattaching elem.
502 // This prevents Flash embeds from being reloaded, for example.
503 if (elem.parentNode == this.parentElement_) {
504 elem.parentNode.insertBefore(this.placeholder_, elem);
505 } else {
506 elem.parentNode.replaceChild(this.placeholder_, elem);
507 this.parentElement_.appendChild(elem);
508 }
509
510 // Versions of IE below 7-in-standards-mode don't handle 'position: fixed',
511 // so we must emulate it using an IE-specific idiom for JS-based calculated
512 // style values. These users will only ever float at the top (bottom floating
513 // not supported.) Also checked in handleScroll_.
514 if (this.needsIePositionHack_()) {
515 elem.style.position = 'absolute';
516 elem.style.setExpression(
517 'top', 'document.compatMode=="CSS1Compat"?' +
518 'documentElement.scrollTop:document.body.scrollTop');
519 } else {
520 elem.style.position = 'fixed';
521 if (isTop) {
522 elem.style.top = this.viewportTopOffset_ + 'px';
523 elem.style.bottom = 'auto';
524 } else {
525 elem.style.top = 'auto';
526 elem.style.bottom = '0';
527 }
528 }
529
530 this.floating_ = true;
531 };
532
533
534 /**
535 * Stops floating behavior, returning element to its original state.
536 * @return {boolean} True if the the element has been docked. False if the
537 * element is already docked or the event was cancelled.
538 * @private
539 */
540 goog.ui.ScrollFloater.prototype.dock_ = function() {
541 // Ignore if the component is docked or the DOCK event is cancelled.
542 if (!(this.floating_ || this.pinned_) ||
543 !this.dispatchEvent(goog.ui.ScrollFloater.EventType.DOCK)) {
544 return false;
545 }
546
547 var elem = this.getElement();
548
549 if (this.floating_) {
550 this.restoreOriginalStyles_();
551
552 if (this.needsIePositionHack_()) {
553 elem.style.removeExpression('top');
554 }
555
556 // If placeholder_ was inserted and didn't replace elem then elem has
557 // the right parent already, no need to replace (which removes elem before
558 // inserting it).
559 if (this.placeholder_.parentNode == this.parentElement_) {
560 this.placeholder_.parentNode.removeChild(this.placeholder_);
561 } else {
562 this.placeholder_.parentNode.replaceChild(elem, this.placeholder_);
563 }
564 }
565
566 if (this.pinned_) {
567 this.restoreOriginalStyles_();
568 }
569
570 this.floating_ = this.pinned_ = false;
571
572 return true;
573 };
574
575
576 /**
577 * Handle horizontal scroll events by updating the left offset position. This
578 * cannot change the floating or docked state and is only valid while the
579 * element is floating.
580 * @private
581 */
582 goog.ui.ScrollFloater.prototype.updateFloatingLeftPosition_ = function() {
583 goog.asserts.assert(this.floating_);
584
585 var newWindowLeftOffset_ = goog.dom.getDocumentScroll().x;
586
587 goog.style.setStyle(
588 this.getElement(),
589 {'left': (this.originalLeftOffset_ - newWindowLeftOffset_) + 'px'});
590 };
591
592
593 /**
594 * @private
595 */
596 goog.ui.ScrollFloater.prototype.storeOriginalStyles_ = function() {
597 var elem = this.getElement();
598 this.originalStyles_ = {};
599
600 // Store styles while not floating so we can restore them when the
601 // element stops floating.
602 goog.array.forEach(
603 goog.ui.ScrollFloater.STORED_STYLE_PROPS_, function(property) {
604 this.originalStyles_[property] = elem.style[property];
605 }, this);
606
607 // Copy relevant styles to placeholder so it will be laid out the same
608 // as the element that's about to be floated.
609 goog.array.forEach(
610 goog.ui.ScrollFloater.PLACEHOLDER_STYLE_PROPS_, function(property) {
611 this.placeholder_.style[property] = elem.style[property] ||
612 goog.style.getCascadedStyle(elem, property) ||
613 goog.style.getComputedStyle(elem, property);
614 }, this);
615 };
616
617
618 /**
619 * @private
620 */
621 goog.ui.ScrollFloater.prototype.restoreOriginalStyles_ = function() {
622 var elem = this.getElement();
623 for (var prop in this.originalStyles_) {
624 elem.style[prop] = this.originalStyles_[prop];
625 }
626 };
627
628
629 /**
630 * Determines whether we need to apply the position hack to emulated position:
631 * fixed on this browser.
632 * @return {boolean} Whether the current browser needs the position hack.
633 * @private
634 */
635 goog.ui.ScrollFloater.prototype.needsIePositionHack_ = function() {
636 return goog.userAgent.IE &&
637 !(goog.userAgent.isVersionOrHigher('7') &&
638 this.getDomHelper().isCss1CompatMode());
639 };
640
641
642 /**
643 * Sets some magic CSS properties that make float-scrolling work smoothly
644 * in IE6 (and IE7 in quirks mode). Without this hack, the floating element
645 * will appear jumpy when you scroll the document. This involves modifying
646 * the background of the HTML element (or BODY in quirks mode). If there's
647 * already a background image in use this is not required.
648 * For further reading, see
649 * http://annevankesteren.nl/2005/01/position-fixed-in-ie
650 * @private
651 */
652 goog.ui.ScrollFloater.prototype.applyIeBgHack_ = function() {
653 if (this.needsIePositionHack_()) {
654 var doc = this.getDomHelper().getDocument();
655 var topLevelElement = goog.style.getClientViewportElement(doc);
656
657 if (topLevelElement.currentStyle.backgroundImage == 'none') {
658 // Using an https URL if the current windowbp is https avoids an IE
659 // "This page contains a mix of secure and nonsecure items" warning.
660 topLevelElement.style.backgroundImage =
661 this.getDomHelper().getWindow().location.protocol == 'https:' ?
662 'url(https:///)' :
663 'url(about:blank)';
664 topLevelElement.style.backgroundAttachment = 'fixed';
665 }
666 }
667 };