getScrollPosition.js.flow 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule getScrollPosition
  8. * @typechecks
  9. */
  10. 'use strict';
  11. const getDocumentScrollElement = require('./getDocumentScrollElement');
  12. const getUnboundedScrollPosition = require('./getUnboundedScrollPosition');
  13. /**
  14. * Gets the scroll position of the supplied element or window.
  15. *
  16. * The return values are bounded. This means that if the scroll position is
  17. * negative or exceeds the element boundaries (which is possible using inertial
  18. * scrolling), you will get zero or the maximum scroll position, respectively.
  19. *
  20. * If you need the unbound scroll position, use `getUnboundedScrollPosition`.
  21. *
  22. * @param {DOMWindow|DOMElement} scrollable
  23. * @return {object} Map with `x` and `y` keys.
  24. */
  25. function getScrollPosition(scrollable) {
  26. const documentScrollElement = getDocumentScrollElement(scrollable.ownerDocument || scrollable.document);
  27. if (scrollable.Window && scrollable instanceof scrollable.Window) {
  28. scrollable = documentScrollElement;
  29. }
  30. const scrollPosition = getUnboundedScrollPosition(scrollable);
  31. const viewport = scrollable === documentScrollElement ? scrollable.ownerDocument.documentElement : scrollable;
  32. const xMax = scrollable.scrollWidth - viewport.clientWidth;
  33. const yMax = scrollable.scrollHeight - viewport.clientHeight;
  34. scrollPosition.x = Math.max(0, Math.min(scrollPosition.x, xMax));
  35. scrollPosition.y = Math.max(0, Math.min(scrollPosition.y, yMax));
  36. return scrollPosition;
  37. }
  38. module.exports = getScrollPosition;