Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support setting rootMargin for client:visible #9363

Merged
merged 8 commits into from
Jan 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/stupid-peas-juggle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'astro': minor
---

Extends the `client:visible` directive by adding an optional `rootMargin` property. This allows a component to be hydrated when it is close to the viewport instead of waiting for it to become visible.

```html
<!-- Load component when it's within 200px away from entering the viewport -->
<Component client:visible="200px" />
```
2 changes: 1 addition & 1 deletion packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export interface AstroBuiltinProps {
'client:load'?: boolean;
'client:idle'?: boolean;
'client:media'?: string;
'client:visible'?: boolean;
'client:visible'?: string|boolean;
'client:only'?: boolean | string;
}

Expand Down
8 changes: 6 additions & 2 deletions packages/astro/src/runtime/client/visible.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@ import type { ClientDirective } from '../../@types/astro.js';
* 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 visibleDirective: ClientDirective = (load, options, el) => {
const cb = async () => {
const hydrate = await load();
await hydrate();
};

const ioOptions = {
rootMargin: typeof options.value === 'string' ? options.value : undefined,
};

const io = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
Expand All @@ -19,7 +23,7 @@ const visibleDirective: ClientDirective = (load, _options, el) => {
cb();
break; // break loop on first match
}
});
}, ioOptions);

for (const child of el.children) {
io.observe(child);
Expand Down
Loading