UNPKG

2.4 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4Object.defineProperty(exports, "__esModule", {
5 value: true
6});
7exports["default"] = void 0;
8var _tslib = require("tslib");
9var _useRafState = _interopRequireDefault(require("../useRafState"));
10var _useLatest = _interopRequireDefault(require("../useLatest"));
11var _domTarget = require("../utils/domTarget");
12var _useEffectWithTarget = _interopRequireDefault(require("../utils/useEffectWithTarget"));
13function useScroll(target, shouldUpdate) {
14 if (shouldUpdate === void 0) {
15 shouldUpdate = function shouldUpdate() {
16 return true;
17 };
18 }
19 var _a = (0, _tslib.__read)((0, _useRafState["default"])(), 2),
20 position = _a[0],
21 setPosition = _a[1];
22 var shouldUpdateRef = (0, _useLatest["default"])(shouldUpdate);
23 (0, _useEffectWithTarget["default"])(function () {
24 var el = (0, _domTarget.getTargetElement)(target, document);
25 if (!el) {
26 return;
27 }
28 var updatePosition = function updatePosition() {
29 var newPosition;
30 if (el === document) {
31 if (document.scrollingElement) {
32 newPosition = {
33 left: document.scrollingElement.scrollLeft,
34 top: document.scrollingElement.scrollTop
35 };
36 } else {
37 // When in quirks mode, the scrollingElement attribute returns the HTML body element if it exists and is potentially scrollable, otherwise it returns null.
38 // https://developer.mozilla.org/zh-CN/docs/Web/API/Document/scrollingElement
39 // https://stackoverflow.com/questions/28633221/document-body-scrolltop-firefox-returns-0-only-js
40 newPosition = {
41 left: Math.max(window.pageXOffset, document.documentElement.scrollLeft, document.body.scrollLeft),
42 top: Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop)
43 };
44 }
45 } else {
46 newPosition = {
47 left: el.scrollLeft,
48 top: el.scrollTop
49 };
50 }
51 if (shouldUpdateRef.current(newPosition)) {
52 setPosition(newPosition);
53 }
54 };
55 updatePosition();
56 el.addEventListener('scroll', updatePosition);
57 return function () {
58 el.removeEventListener('scroll', updatePosition);
59 };
60 }, [], target);
61 return position;
62}
63var _default = useScroll;
64exports["default"] = _default;
\No newline at end of file