forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlazy-iframe.tsx
More file actions
86 lines (71 loc) · 2.45 KB
/
Copy pathlazy-iframe.tsx
File metadata and controls
86 lines (71 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"use client";
import { useRef, useState, useEffect } from "react";
interface LazyIframeProps {
src: string;
className?: string;
style?: React.CSSProperties;
}
function getScrollParent(el: HTMLElement | null): HTMLElement | null {
let node = el?.parentElement ?? null;
while (node) {
const { overflowY } = getComputedStyle(node);
if (overflowY === "auto" || overflowY === "scroll") return node;
node = node.parentElement;
}
return null;
}
export function LazyIframe({ src, className, style }: LazyIframeProps) {
const ref = useRef<HTMLIFrameElement>(null);
const [loadedSrc, setLoadedSrc] = useState<string | undefined>(undefined);
const scrollLocked = useRef(false);
const savedScrollTop = useRef(0);
// Lazy-load: only set src when the iframe is near the scroll viewport
useEffect(() => {
const el = ref.current;
if (!el) return;
const container = getScrollParent(el);
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
const target = container ?? document.documentElement;
savedScrollTop.current = target.scrollTop;
scrollLocked.current = true;
setLoadedSrc(src);
observer.disconnect();
}
},
{ root: container, rootMargin: "400px" },
);
observer.observe(el);
return () => observer.disconnect();
}, [src]);
// Lock scroll position until user interacts, preventing focus-triggered scroll
useEffect(() => {
const el = ref.current;
if (!el) return;
const container = getScrollParent(el);
const target = container ?? document.documentElement;
const onScroll = () => {
if (scrollLocked.current) {
target.scrollTop = savedScrollTop.current;
}
};
// Any user gesture means they want to scroll — unlock
const unlock = () => {
scrollLocked.current = false;
};
target.addEventListener("scroll", onScroll);
window.addEventListener("wheel", unlock, { once: true });
window.addEventListener("touchstart", unlock, { once: true });
window.addEventListener("keydown", unlock, { once: true });
return () => {
target.removeEventListener("scroll", onScroll);
window.removeEventListener("wheel", unlock);
window.removeEventListener("touchstart", unlock);
window.removeEventListener("keydown", unlock);
};
}, []);
return (
<iframe ref={ref} src={loadedSrc} className={className} style={style} />
);
}