@flamingo-stack/openframe-frontend-core 0.0.176 → 0.0.177-snapshot.20260514141929
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-VY6SYM2L.js → chunk-AAX27BCR.js} +311 -467
- package/dist/chunk-AAX27BCR.js.map +1 -0
- package/dist/{chunk-WX7PT5C7.cjs → chunk-ALW3D72O.cjs} +61 -2
- package/dist/chunk-ALW3D72O.cjs.map +1 -0
- package/dist/{chunk-KB2N44BY.js → chunk-FMWHOUFE.js} +61 -2
- package/dist/chunk-FMWHOUFE.js.map +1 -0
- package/dist/{chunk-SVF4YOGM.cjs → chunk-L4T24AN4.cjs} +482 -638
- package/dist/chunk-L4T24AN4.cjs.map +1 -0
- package/dist/components/chat/chat-message-list.d.ts.map +1 -1
- package/dist/components/features/index.cjs +3 -5
- package/dist/components/features/index.cjs.map +1 -1
- package/dist/components/features/index.js +2 -4
- package/dist/components/features/video-player.d.ts +17 -20
- package/dist/components/features/video-player.d.ts.map +1 -1
- package/dist/components/features/youtube-embed.d.ts +18 -4
- package/dist/components/features/youtube-embed.d.ts.map +1 -1
- package/dist/components/index.cjs +3 -5
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.js +2 -4
- package/dist/components/navigation/index.cjs +3 -3
- package/dist/components/navigation/index.js +2 -2
- package/dist/components/ui/index.cjs +3 -3
- package/dist/components/ui/index.js +2 -2
- package/dist/hooks/index.cjs +4 -2
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/index.d.ts.map +1 -1
- package/dist/hooks/index.js +3 -1
- package/dist/hooks/use-near-viewport.d.ts +42 -0
- package/dist/hooks/use-near-viewport.d.ts.map +1 -0
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -4
- package/package.json +1 -1
- package/src/components/chat/chat-message-list.tsx +48 -27
- package/src/components/features/video-player.tsx +39 -176
- package/src/components/features/youtube-embed.tsx +107 -224
- package/src/hooks/index.ts +3 -0
- package/src/hooks/use-near-viewport.ts +118 -0
- package/dist/chunk-KB2N44BY.js.map +0 -1
- package/dist/chunk-SVF4YOGM.cjs.map +0 -1
- package/dist/chunk-VY6SYM2L.js.map +0 -1
- package/dist/chunk-WX7PT5C7.cjs.map +0 -1
- package/src/components/features/__tests__/video-player.test.tsx +0 -142
|
@@ -1,27 +1,17 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
|
|
3
|
-
import React, {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
)
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
<line x1="12" y1="2" x2="12" y2="6"/>
|
|
16
|
-
<line x1="12" y1="18" x2="12" y2="22"/>
|
|
17
|
-
<line x1="4.93" y1="4.93" x2="7.76" y2="7.76"/>
|
|
18
|
-
<line x1="16.24" y1="16.24" x2="19.07" y2="19.07"/>
|
|
19
|
-
<line x1="2" y1="12" x2="6" y2="12"/>
|
|
20
|
-
<line x1="18" y1="12" x2="22" y2="12"/>
|
|
21
|
-
<line x1="4.93" y1="19.07" x2="7.76" y2="16.24"/>
|
|
22
|
-
<line x1="16.24" y1="7.76" x2="19.07" y2="4.93"/>
|
|
23
|
-
</svg>
|
|
24
|
-
);
|
|
3
|
+
import React, { useRef, useState } from 'react';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* YouTube facade (lite-youtube-embed pattern). Renders poster + play
|
|
7
|
+
* button until clicked; on click, a real `<iframe>` is created via
|
|
8
|
+
* `document.createElement` synchronously so the user-activation chain
|
|
9
|
+
* holds and `autoplay=1` plays on Chrome / Safari / Firefox.
|
|
10
|
+
*
|
|
11
|
+
* Uses `youtube-nocookie.com` (GDPR-friendly) and `mqdefault` posters
|
|
12
|
+
* (`maxresdefault` returns a gray 200 placeholder when missing, which
|
|
13
|
+
* defeats `onError` fallback).
|
|
14
|
+
*/
|
|
25
15
|
|
|
26
16
|
interface YouTubeEmbedProps {
|
|
27
17
|
videoId: string;
|
|
@@ -30,198 +20,99 @@ interface YouTubeEmbedProps {
|
|
|
30
20
|
showTitle?: boolean;
|
|
31
21
|
showMeta?: boolean;
|
|
32
22
|
minimalControls?: boolean;
|
|
23
|
+
/** When true, the poster img gets `fetchpriority="high"` for LCP. Default false (below-the-fold). */
|
|
24
|
+
aboveTheFold?: boolean;
|
|
33
25
|
}
|
|
34
26
|
|
|
35
|
-
export const YouTubeEmbed: React.FC<YouTubeEmbedProps> = ({
|
|
36
|
-
videoId,
|
|
37
|
-
title =
|
|
38
|
-
className =
|
|
27
|
+
export const YouTubeEmbed: React.FC<YouTubeEmbedProps> = ({
|
|
28
|
+
videoId,
|
|
29
|
+
title = 'YouTube Video',
|
|
30
|
+
className = '',
|
|
39
31
|
showTitle = true,
|
|
40
32
|
showMeta = true,
|
|
41
|
-
minimalControls = false
|
|
33
|
+
minimalControls = false,
|
|
34
|
+
aboveTheFold = false,
|
|
42
35
|
}) => {
|
|
43
|
-
const [
|
|
44
|
-
const
|
|
45
|
-
const [isPlaying, setIsPlaying] = useState(false);
|
|
46
|
-
const [useIframe, setUseIframe] = useState(false);
|
|
47
|
-
const [mounted, setMounted] = useState(false);
|
|
48
|
-
|
|
49
|
-
useEffect(() => {
|
|
50
|
-
setMounted(true);
|
|
51
|
-
|
|
52
|
-
// Always use iframe to avoid CSP issues with ReactPlayer scripts
|
|
53
|
-
setUseIframe(true);
|
|
54
|
-
setIsLoading(false);
|
|
55
|
-
}, []);
|
|
56
|
-
|
|
57
|
-
const handleReady = () => {
|
|
58
|
-
setIsLoading(false);
|
|
59
|
-
};
|
|
36
|
+
const [activated, setActivated] = useState(false);
|
|
37
|
+
const iframeSlotRef = useRef<HTMLDivElement | null>(null);
|
|
60
38
|
|
|
61
|
-
const
|
|
62
|
-
setIsLoading(false);
|
|
63
|
-
setHasError(true);
|
|
64
|
-
// Fallback to iframe on error
|
|
65
|
-
setUseIframe(true);
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
const handlePlay = () => {
|
|
69
|
-
setIsPlaying(true);
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
const handlePause = () => {
|
|
73
|
-
setIsPlaying(false);
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
const videoUrl = `https://www.youtube.com/watch?v=${videoId}`;
|
|
77
|
-
|
|
78
|
-
// Build embed URL with conditional parameters
|
|
79
|
-
const embedParams = new URLSearchParams({
|
|
80
|
-
rel: '0',
|
|
81
|
-
modestbranding: '1',
|
|
82
|
-
playsinline: '1'
|
|
83
|
-
});
|
|
84
|
-
|
|
39
|
+
const embedParams = new URLSearchParams({ autoplay: '1', rel: '0', modestbranding: '1', playsinline: '1' });
|
|
85
40
|
if (minimalControls) {
|
|
86
|
-
embedParams.set('controls', '0');
|
|
87
|
-
embedParams.set('showinfo', '0');
|
|
88
|
-
embedParams.set('fs', '0');
|
|
89
|
-
embedParams.set('iv_load_policy', '3');
|
|
90
|
-
embedParams.set('cc_load_policy', '0');
|
|
91
|
-
embedParams.set('disablekb', '1');
|
|
92
|
-
embedParams.set('rel', '0'); // Hide related videos (already set above, but ensure it's enforced)
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const embedUrl = `https://www.youtube.com/embed/${videoId}?${embedParams.toString()}`;
|
|
96
|
-
|
|
97
|
-
// Don't render until mounted to prevent hydration mismatch
|
|
98
|
-
if (!mounted) {
|
|
99
|
-
return (
|
|
100
|
-
<div className={`youtube-embed-container my-6 ${className}`}>
|
|
101
|
-
<div className="video-wrapper relative w-full" style={{ paddingBottom: '56.25%' }}>
|
|
102
|
-
<div className="loading-overlay absolute inset-0 bg-ods-card border border-ods-border rounded-lg flex items-center justify-center">
|
|
103
|
-
<div className="loading-content flex flex-col items-center gap-3">
|
|
104
|
-
<Loader className="animate-spin text-ods-accent" size={32} />
|
|
105
|
-
<span className="font-sans text-sm text-ods-text-secondary">Loading video...</span>
|
|
106
|
-
</div>
|
|
107
|
-
</div>
|
|
108
|
-
</div>
|
|
109
|
-
</div>
|
|
110
|
-
);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
if (hasError) {
|
|
114
|
-
return (
|
|
115
|
-
<div className={`youtube-embed-error ${className}`}>
|
|
116
|
-
<div className="error-state bg-ods-card border border-ods-error rounded-lg p-6 text-center my-6">
|
|
117
|
-
<div className="error-icon flex justify-center mb-4">
|
|
118
|
-
<svg width="48" height="48" fill="currentColor" viewBox="0 0 24 24" className="text-ods-error">
|
|
119
|
-
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
|
|
120
|
-
</svg>
|
|
121
|
-
</div>
|
|
122
|
-
<div className="error-title font-sans font-semibold text-lg text-ods-error mb-2">
|
|
123
|
-
Video Unavailable
|
|
124
|
-
</div>
|
|
125
|
-
<div className="error-description font-sans text-sm text-ods-text-secondary mb-4">
|
|
126
|
-
Unable to load YouTube video. The video may be private or deleted.
|
|
127
|
-
</div>
|
|
128
|
-
<a
|
|
129
|
-
href={videoUrl}
|
|
130
|
-
target="_blank"
|
|
131
|
-
rel="noopener noreferrer"
|
|
132
|
-
className="error-retry-button bg-ods-error hover:bg-ods-error-hover text-ods-text-on-error border-none rounded px-4 py-2 font-sans font-medium text-sm cursor-pointer transition-colors duration-200"
|
|
133
|
-
>
|
|
134
|
-
Watch on YouTube
|
|
135
|
-
</a>
|
|
136
|
-
</div>
|
|
137
|
-
</div>
|
|
138
|
-
);
|
|
41
|
+
embedParams.set('controls', '0');
|
|
42
|
+
embedParams.set('showinfo', '0');
|
|
43
|
+
embedParams.set('fs', '0');
|
|
44
|
+
embedParams.set('iv_load_policy', '3');
|
|
45
|
+
embedParams.set('cc_load_policy', '0');
|
|
46
|
+
embedParams.set('disablekb', '1');
|
|
139
47
|
}
|
|
48
|
+
const embedUrl = `https://www.youtube-nocookie.com/embed/${videoId}?${embedParams.toString()}`;
|
|
49
|
+
const watchUrl = `https://www.youtube.com/watch?v=${videoId}`;
|
|
50
|
+
const posterJpg = `https://i.ytimg.com/vi/${videoId}/mqdefault.jpg`;
|
|
51
|
+
const posterWebp = `https://i.ytimg.com/vi_webp/${videoId}/mqdefault.webp`;
|
|
52
|
+
|
|
53
|
+
// `iframeSlotRef` is a JSX-empty div React owns but never reconciles
|
|
54
|
+
// children into; the `<button>` overlay is a SIBLING of that slot, not
|
|
55
|
+
// a child. Without that split, React would yank the button on
|
|
56
|
+
// re-render and trip `removeChild ... is not a child of this node`.
|
|
57
|
+
const handleActivate = () => {
|
|
58
|
+
const slot = iframeSlotRef.current;
|
|
59
|
+
if (!slot || activated) return;
|
|
60
|
+
const iframe = document.createElement('iframe');
|
|
61
|
+
iframe.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share');
|
|
62
|
+
iframe.setAttribute('allowfullscreen', '');
|
|
63
|
+
iframe.setAttribute('title', title);
|
|
64
|
+
iframe.className = 'absolute inset-0 w-full h-full border-0';
|
|
65
|
+
iframe.src = embedUrl;
|
|
66
|
+
slot.appendChild(iframe);
|
|
67
|
+
setActivated(true);
|
|
68
|
+
};
|
|
140
69
|
|
|
141
70
|
return (
|
|
142
71
|
<div className={`youtube-embed-container my-6 ${className}`}>
|
|
143
|
-
{/* Video Title */}
|
|
144
72
|
{title && showTitle && (
|
|
145
73
|
<div className="video-title font-sans text-lg font-medium text-ods-text-primary mb-3">
|
|
146
74
|
{title}
|
|
147
75
|
</div>
|
|
148
76
|
)}
|
|
149
77
|
|
|
150
|
-
{/* Video Container with 16:9 Aspect Ratio */}
|
|
151
78
|
<div className="video-wrapper relative w-full" style={{ paddingBottom: '56.25%' }}>
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
<
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
)}
|
|
161
|
-
|
|
162
|
-
{/* Video Player */}
|
|
163
|
-
<div className="video-player absolute inset-0 rounded-lg overflow-hidden border border-ods-border bg-ods-bg-inverse">
|
|
164
|
-
{useIframe ? (
|
|
165
|
-
// Iframe fallback for mobile and error cases
|
|
166
|
-
<iframe
|
|
167
|
-
src={embedUrl}
|
|
168
|
-
title={title}
|
|
169
|
-
className="w-full h-full border-0"
|
|
170
|
-
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
|
|
171
|
-
allowFullScreen
|
|
172
|
-
style={{ border: 'none' }}
|
|
173
|
-
/>
|
|
174
|
-
) : (
|
|
175
|
-
<ReactPlayer
|
|
176
|
-
url={videoUrl}
|
|
177
|
-
width="100%"
|
|
178
|
-
height="100%"
|
|
179
|
-
onReady={handleReady}
|
|
180
|
-
onError={handleError}
|
|
181
|
-
onPlay={handlePlay}
|
|
182
|
-
onPause={handlePause}
|
|
183
|
-
config={{
|
|
184
|
-
youtube: {
|
|
185
|
-
playerVars: {
|
|
186
|
-
autoplay: 0,
|
|
187
|
-
controls: 1,
|
|
188
|
-
rel: 0,
|
|
189
|
-
showinfo: 0,
|
|
190
|
-
modestbranding: 1,
|
|
191
|
-
iv_load_policy: 3,
|
|
192
|
-
cc_load_policy: 0,
|
|
193
|
-
playsinline: 1
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
} as any}
|
|
197
|
-
light={false} // Show video immediately
|
|
198
|
-
playing={false} // Don't autoplay
|
|
199
|
-
/>
|
|
200
|
-
)}
|
|
201
|
-
</div>
|
|
202
|
-
|
|
203
|
-
{/* Custom Play Button Overlay (optional enhancement) - only for ReactPlayer */}
|
|
204
|
-
{!useIframe && !isPlaying && !isLoading && (
|
|
205
|
-
<div className="play-overlay absolute inset-0 flex items-center justify-center bg-ods-bg-inverse bg-opacity-20 rounded-lg transition-opacity duration-300 hover:bg-opacity-30">
|
|
206
|
-
<button
|
|
207
|
-
onClick={() => setIsPlaying(true)}
|
|
208
|
-
className="play-button bg-ods-accent hover:bg-ods-accent-hover text-ods-text-on-accent w-16 h-16 rounded-full flex items-center justify-center transition-all duration-200 transform hover:scale-110 shadow-lg"
|
|
209
|
-
aria-label="Play video"
|
|
79
|
+
<div className="absolute inset-0 rounded-lg overflow-hidden border border-ods-border bg-ods-card">
|
|
80
|
+
<div ref={iframeSlotRef} className="absolute inset-0" aria-hidden={!activated} />
|
|
81
|
+
{!activated && (
|
|
82
|
+
<button
|
|
83
|
+
type="button"
|
|
84
|
+
aria-label={`Play: ${title}`}
|
|
85
|
+
onClick={handleActivate}
|
|
86
|
+
className="group absolute inset-0 p-0 m-0 border-0 cursor-pointer bg-transparent"
|
|
210
87
|
>
|
|
211
|
-
<
|
|
88
|
+
<picture>
|
|
89
|
+
<source type="image/webp" srcSet={posterWebp} />
|
|
90
|
+
<img
|
|
91
|
+
src={posterJpg}
|
|
92
|
+
alt={title}
|
|
93
|
+
loading="lazy"
|
|
94
|
+
fetchPriority={aboveTheFold ? 'high' : 'low'}
|
|
95
|
+
decoding={aboveTheFold ? 'sync' : 'async'}
|
|
96
|
+
className="absolute inset-0 w-full h-full object-cover"
|
|
97
|
+
/>
|
|
98
|
+
</picture>
|
|
99
|
+
<div className="absolute inset-0 flex items-center justify-center bg-ods-bg-inverse bg-opacity-20 transition-opacity duration-200 group-hover:bg-opacity-30">
|
|
100
|
+
<span className="flex items-center justify-center w-16 h-16 rounded-full bg-ods-accent text-ods-text-on-accent shadow-lg transition-transform duration-200 group-hover:scale-110">
|
|
101
|
+
<svg width={24} height={24} fill="currentColor" viewBox="0 0 24 24" className="ml-1">
|
|
102
|
+
<polygon points="5,3 19,12 5,21" />
|
|
103
|
+
</svg>
|
|
104
|
+
</span>
|
|
105
|
+
</div>
|
|
212
106
|
</button>
|
|
213
|
-
|
|
214
|
-
|
|
107
|
+
)}
|
|
108
|
+
</div>
|
|
215
109
|
</div>
|
|
216
110
|
|
|
217
|
-
{/* Video Meta Information */}
|
|
218
111
|
{showMeta && (
|
|
219
112
|
<div className="video-meta flex items-center justify-between mt-3 text-sm text-ods-text-secondary">
|
|
220
|
-
<div className="video-platform font-sans">
|
|
221
|
-
YouTube
|
|
222
|
-
</div>
|
|
113
|
+
<div className="video-platform font-sans">YouTube</div>
|
|
223
114
|
<a
|
|
224
|
-
href={
|
|
115
|
+
href={watchUrl}
|
|
225
116
|
target="_blank"
|
|
226
117
|
rel="noopener noreferrer"
|
|
227
118
|
className="video-link font-sans text-ods-accent hover:text-ods-accent-hover transition-colors duration-200"
|
|
@@ -234,42 +125,34 @@ export const YouTubeEmbed: React.FC<YouTubeEmbedProps> = ({
|
|
|
234
125
|
);
|
|
235
126
|
};
|
|
236
127
|
|
|
237
|
-
|
|
128
|
+
const YT_HOSTS = new Set([
|
|
129
|
+
'youtube.com', 'www.youtube.com', 'm.youtube.com',
|
|
130
|
+
'youtu.be',
|
|
131
|
+
'youtube-nocookie.com', 'www.youtube-nocookie.com',
|
|
132
|
+
]);
|
|
133
|
+
|
|
134
|
+
// `youtube.com/(embed|v|shorts)/<id>` — anchored, no `.*`, ReDoS-safe.
|
|
135
|
+
const YT_PATH_RE = /^\/(?:embed|v|shorts)\/([^/]+)\/?$/;
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Extract the YouTube video id from any common URL shape. Uses `URL`
|
|
139
|
+
* parsing + a strict, anchored pathname regex — NOT the previous
|
|
140
|
+
* `.*v=` pattern that CodeQL flagged for polynomial-time backtracking
|
|
141
|
+
* on adversarial input like `youtube.com/watch?` repeated N times.
|
|
142
|
+
*/
|
|
238
143
|
export const extractYouTubeId = (url: string): string | null => {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
for (const pattern of patterns) {
|
|
246
|
-
const match = url.match(pattern);
|
|
247
|
-
if (match) {
|
|
248
|
-
return match[1];
|
|
249
|
-
}
|
|
144
|
+
let u: URL;
|
|
145
|
+
try { u = new URL(url); } catch { return null; }
|
|
146
|
+
if (!YT_HOSTS.has(u.hostname.toLowerCase())) return null;
|
|
147
|
+
// `youtu.be/<id>` — id is the first path segment.
|
|
148
|
+
if (u.hostname.toLowerCase().endsWith('youtu.be')) {
|
|
149
|
+
return u.pathname.split('/').filter(Boolean)[0] ?? null;
|
|
250
150
|
}
|
|
251
|
-
|
|
252
|
-
|
|
151
|
+
// `youtube.com/watch?v=<id>` — query parameter.
|
|
152
|
+
const v = u.searchParams.get('v');
|
|
153
|
+
if (v) return v;
|
|
154
|
+
// `youtube.com/(embed|v|shorts)/<id>` — anchored pathname match.
|
|
155
|
+
const m = u.pathname.match(YT_PATH_RE);
|
|
156
|
+
return m ? m[1] : null;
|
|
253
157
|
};
|
|
254
158
|
|
|
255
|
-
// Component for parsing YouTube URLs in markdown
|
|
256
|
-
export const YouTubeLinkParser: React.FC<{ href: string; children: React.ReactNode }> = ({ href, children }) => {
|
|
257
|
-
const videoId = extractYouTubeId(href);
|
|
258
|
-
|
|
259
|
-
// If it's a YouTube URL, render the embed instead of a link
|
|
260
|
-
if (videoId) {
|
|
261
|
-
return <YouTubeEmbed videoId={videoId} title={typeof children === 'string' ? children : undefined} />;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
// Otherwise, render as a normal link
|
|
265
|
-
return (
|
|
266
|
-
<a
|
|
267
|
-
href={href}
|
|
268
|
-
target="_blank"
|
|
269
|
-
rel="noopener noreferrer"
|
|
270
|
-
className="text-ods-accent hover:text-ods-accent-hover transition-colors duration-200"
|
|
271
|
-
>
|
|
272
|
-
{children}
|
|
273
|
-
</a>
|
|
274
|
-
);
|
|
275
|
-
};
|
package/src/hooks/index.ts
CHANGED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* useNearViewport — module-level shared IntersectionObserver in hook form.
|
|
3
|
+
*
|
|
4
|
+
* Single IO instance per `rootMargin` value, shared across every component
|
|
5
|
+
* that mounts the hook. Reduces overhead vs. one IO per component on
|
|
6
|
+
* grid/list pages where many subscribers observe the viewport with the same
|
|
7
|
+
* margin. Promoted from the inline singleton at
|
|
8
|
+
* `multi-platform-hub/components/shared/video-bites-display.tsx:21-43`,
|
|
9
|
+
* which is the only IO pattern in either repo today.
|
|
10
|
+
*
|
|
11
|
+
* Usage:
|
|
12
|
+
* ```tsx
|
|
13
|
+
* function MyCard() {
|
|
14
|
+
* const { ref, isNear } = useNearViewport('500px');
|
|
15
|
+
* return <div ref={ref}>{isNear ? <HeavyChild /> : <Placeholder />}</div>;
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* StrictMode safety: cleanup uses an identity check on the registered
|
|
20
|
+
* callback so React's dev double-mount (mount → cleanup → re-mount) does
|
|
21
|
+
* not drop the second mount's freshly-set subscription. The IO callback
|
|
22
|
+
* also checks `subscribers.get(target)` before invoking so a fire that
|
|
23
|
+
* races with unmount cannot crash on a torn-down component.
|
|
24
|
+
*
|
|
25
|
+
* The hook fires once — on first intersection it sets `isNear=true` and
|
|
26
|
+
* unobserves the element. Callers that need re-observation should
|
|
27
|
+
* unmount and remount (or fork the hook for two-way behavior).
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { useEffect, useRef, useState, useCallback } from 'react';
|
|
31
|
+
|
|
32
|
+
// Per-rootMargin IO map. Multiple call sites with different margins each
|
|
33
|
+
// get their own singleton observer.
|
|
34
|
+
const observers = new Map<string, IntersectionObserver>();
|
|
35
|
+
const subscribers = new WeakMap<Element, () => void>();
|
|
36
|
+
|
|
37
|
+
function getObserverFor(rootMargin: string): IntersectionObserver {
|
|
38
|
+
const existing = observers.get(rootMargin);
|
|
39
|
+
if (existing) return existing;
|
|
40
|
+
|
|
41
|
+
const io = new IntersectionObserver(
|
|
42
|
+
(entries) => {
|
|
43
|
+
entries.forEach((entry) => {
|
|
44
|
+
if (!entry.isIntersecting) return;
|
|
45
|
+
// Race-safe: re-read the callback at fire time. A late IO firing
|
|
46
|
+
// after cleanup must not invoke a stale callback.
|
|
47
|
+
const cb = subscribers.get(entry.target);
|
|
48
|
+
if (cb) {
|
|
49
|
+
cb();
|
|
50
|
+
io.unobserve(entry.target);
|
|
51
|
+
subscribers.delete(entry.target);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
},
|
|
55
|
+
{ rootMargin }
|
|
56
|
+
);
|
|
57
|
+
observers.set(rootMargin, io);
|
|
58
|
+
return io;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface UseNearViewportResult<T extends Element = HTMLElement> {
|
|
62
|
+
/** Ref to attach to the element you want to gate on visibility. */
|
|
63
|
+
ref: (node: T | null) => void;
|
|
64
|
+
/** Flips to `true` once the element enters within `rootMargin` of the viewport. Never flips back. */
|
|
65
|
+
isNear: boolean;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param rootMargin Margin around the viewport (CSS-style string).
|
|
70
|
+
* '500px' = element starts mounting 500px before scroll-in.
|
|
71
|
+
* '1000px' = a full viewport's worth of lookahead.
|
|
72
|
+
* '0px' = strict on-screen detection.
|
|
73
|
+
*/
|
|
74
|
+
export function useNearViewport<T extends Element = HTMLElement>(
|
|
75
|
+
rootMargin: string = '500px'
|
|
76
|
+
): UseNearViewportResult<T> {
|
|
77
|
+
const [isNear, setIsNear] = useState(false);
|
|
78
|
+
const elRef = useRef<T | null>(null);
|
|
79
|
+
|
|
80
|
+
// Subscribe/unsubscribe on element change.
|
|
81
|
+
const ref = useCallback(
|
|
82
|
+
(node: T | null) => {
|
|
83
|
+
const prev = elRef.current;
|
|
84
|
+
|
|
85
|
+
// Unsubscribe previous, if any. Identity-check the callback so a
|
|
86
|
+
// StrictMode re-mount that has already re-registered keeps its sub.
|
|
87
|
+
if (prev) {
|
|
88
|
+
const stillOurs = subscribers.get(prev);
|
|
89
|
+
if (stillOurs) {
|
|
90
|
+
subscribers.delete(prev);
|
|
91
|
+
observers.get(rootMargin)?.unobserve(prev);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
elRef.current = node;
|
|
96
|
+
if (!node) return;
|
|
97
|
+
|
|
98
|
+
const cb = () => setIsNear(true);
|
|
99
|
+
subscribers.set(node, cb);
|
|
100
|
+
getObserverFor(rootMargin).observe(node);
|
|
101
|
+
},
|
|
102
|
+
[rootMargin]
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
// Unsubscribe on unmount. Identity check guards the StrictMode race.
|
|
106
|
+
useEffect(() => {
|
|
107
|
+
return () => {
|
|
108
|
+
const el = elRef.current;
|
|
109
|
+
if (!el) return;
|
|
110
|
+
if (subscribers.get(el)) {
|
|
111
|
+
subscribers.delete(el);
|
|
112
|
+
observers.get(rootMargin)?.unobserve(el);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}, [rootMargin]);
|
|
116
|
+
|
|
117
|
+
return { ref, isNear };
|
|
118
|
+
}
|