2022-07-26 16:12:36 +08:00
|
|
|
export function isWindow(obj: any): obj is Window {
|
2020-04-01 17:38:21 +08:00
|
|
|
return obj !== null && obj !== undefined && obj === obj.window;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default function getScroll(
|
|
|
|
target: HTMLElement | Window | Document | null,
|
|
|
|
top: boolean,
|
|
|
|
): number {
|
2016-09-29 18:00:23 +08:00
|
|
|
if (typeof window === 'undefined') {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
const method = top ? 'scrollTop' : 'scrollLeft';
|
2020-04-01 17:38:21 +08:00
|
|
|
let result = 0;
|
|
|
|
if (isWindow(target)) {
|
2022-07-26 16:12:36 +08:00
|
|
|
result = target[top ? 'pageYOffset' : 'pageXOffset'];
|
2020-04-01 17:38:21 +08:00
|
|
|
} else if (target instanceof Document) {
|
|
|
|
result = target.documentElement[method];
|
2022-07-26 16:12:36 +08:00
|
|
|
} else if (target instanceof HTMLElement) {
|
|
|
|
result = target[method];
|
2020-04-01 17:38:21 +08:00
|
|
|
} else if (target) {
|
2022-07-26 16:12:36 +08:00
|
|
|
// According to the type inference, the `target` is `never` type.
|
|
|
|
// Since we configured the loose mode type checking, and supports mocking the target with such shape below::
|
|
|
|
// `{ documentElement: { scrollLeft: 200, scrollTop: 400 } }`,
|
|
|
|
// the program may falls into this branch.
|
|
|
|
// Check the corresponding tests for details. Don't sure what is the real scenario this happens.
|
|
|
|
result = target[method];
|
2016-09-29 18:00:23 +08:00
|
|
|
}
|
2022-07-26 16:12:36 +08:00
|
|
|
|
2020-04-01 17:38:21 +08:00
|
|
|
if (target && !isWindow(target) && typeof result !== 'number') {
|
2022-07-26 16:12:36 +08:00
|
|
|
result = (target.ownerDocument ?? target).documentElement?.[method];
|
2020-04-01 17:38:21 +08:00
|
|
|
}
|
|
|
|
return result;
|
2016-09-29 18:00:23 +08:00
|
|
|
}
|