blob: 9be4d9b318a7f2d430727feb63766140ee30ac35 (
plain) (
blame)
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
|
import type { ClientDirective, ClientVisibleOptions } from '../../@types/astro.js';
/**
* Hydrate this component when one of it's children becomes visible
* We target the children because `astro-island` is set to `display: contents`
* which doesn't work with IntersectionObserver
*/
const visibleDirective: ClientDirective = (load, options, el) => {
const cb = async () => {
const hydrate = await load();
await hydrate();
};
const rawOptions =
typeof options.value === 'object' ? (options.value as ClientVisibleOptions) : undefined;
const ioOptions: IntersectionObserverInit = {
rootMargin: rawOptions?.rootMargin,
};
const io = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
// As soon as we hydrate, disconnect this IntersectionObserver for every `astro-island`
io.disconnect();
cb();
break; // break loop on first match
}
}, ioOptions);
for (const child of el.children) {
io.observe(child);
}
};
export default visibleDirective;
|