tachybase_todo/packages/core/utils/src/dom.ts
bai.zixv f0e51e1e89 feat: infinite scroll and linkable card items
Co-authored-by: sealday <zhanglin@daoyoucloud.com>
Reviewed-on: daoyoucloud/tachybase#997
Co-authored-by: bai.zixv <bai.zixv@foxmail.com>
Co-committed-by: bai.zixv <bai.zixv@foxmail.com>
2024-05-20 10:40:49 +08:00

36 lines
943 B
TypeScript

export const canUseDom = !!(
typeof window !== 'undefined' &&
typeof document !== 'undefined' &&
window.document &&
window.document.createElement
);
type ScrollElement = HTMLElement | Window;
const defaultRoot = canUseDom ? window : undefined;
const overflowStylePatterns = ['scroll', 'auto', 'overlay'];
function isElement(node: Element) {
const ELEMENT_NODE_TYPE = 1;
return node.nodeType === ELEMENT_NODE_TYPE;
}
export function getScrollParent(
el: Element,
root: ScrollElement | null | undefined = defaultRoot,
): Window | Element | null | undefined {
let node = el;
while (node && node !== root && isElement(node)) {
if (node === document.body) {
return root;
}
const { overflowY } = window.getComputedStyle(node);
if (overflowStylePatterns.includes(overflowY) && node.scrollHeight > node.clientHeight) {
return node;
}
node = node.parentNode as Element;
}
return root;
}