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: enhance IsInViewport and useIntersectionObserver #202

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ export type IsInViewportOptions = ConfigurableWindow & UseIntersectionObserverOp
*/
export class IsInViewport {
#isInViewport = $state(false);
#observer;

constructor(node: MaybeElementGetter, options?: IsInViewportOptions) {
useIntersectionObserver(
this.#observer = useIntersectionObserver(
node,
(intersectionObserverEntries) => {
let isIntersecting = this.#isInViewport;
Expand All @@ -32,8 +33,36 @@ export class IsInViewport {
options
);
}

/** Current viewport intersection state */
get current() {
return this.#isInViewport;
}

/**
* Stop observing the element.
*/
stop() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'll want to bind these methods to the constructor so they can be used like so:

<button onclick={observer.stop}></button>

Similar to the others we have this way!

this.#observer.stop();
}

/**
* Pause the intersection observer.
*/
pause() {
this.#observer.pause();
}

/**
* Resume the intersection observer.
*/
resume() {
this.#observer.resume();
}

/**
* Whether the intersection observer is currently active.
*/
get isActive() {
return this.#observer.isActive;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ export interface UseIntersectionObserverOptions
* The root document/element to use as the bounding box for the intersection.
*/
root?: MaybeElementGetter;

/**
* If true, will automatically stop observing after the first intersection.
* @default false
*/
once?: boolean;
}

/**
Expand All @@ -37,6 +43,7 @@ export function useIntersectionObserver(
threshold = 0.1,
immediate = true,
window = defaultWindow,
once = false,
} = options;

let isActive = $state(immediate);
Expand All @@ -50,11 +57,34 @@ export function useIntersectionObserver(
const stop = $effect.root(() => {
$effect(() => {
if (!targets.size || !isActive || !window) return;
observer = new window.IntersectionObserver(callback, {

const wrappedCallback: IntersectionObserverCallback = (entries, observer) => {
entries.forEach((entry) => {
// Checking for isIntersecting and intersectionRatio >= threshold bc of a firefox bug
// @see https://github.com/w3c/IntersectionObserver/issues/432
const isThresholdMet = Array.isArray(threshold)
? threshold.some((t) => entry.intersectionRatio >= t)
: entry.intersectionRatio >= threshold;

const inView = entry.isIntersecting && isThresholdMet;

callback([entry], observer);

if (once && inView) {
isActive = false;
return () => {
observer?.disconnect();
};
}
});
};

observer = new window.IntersectionObserver(wrappedCallback, {
rootMargin,
root: get(root),
threshold,
});

for (const el of targets) observer.observe(el);

return () => {
Expand Down
41 changes: 41 additions & 0 deletions sites/docs/src/content/utilities/is-in-viewport.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ with the [`useIntersectionObserver`](/docs/utilities/use-intersection-observer)

## Usage

### Basic Usage

```svelte
<script lang="ts">
import { IsInViewport } from "runed";
Expand All @@ -33,6 +35,31 @@ with the [`useIntersectionObserver`](/docs/utilities/use-intersection-observer)
<p>Target node in viewport: {inViewport.current}</p>
```

### One-time Detection

The `once` option automatically stops observing after the first intersection. This is useful for
one-time animations or loading content when it becomes visible:

```svelte
<script lang="ts">
import { IsInViewport } from "runed";

let targetNode = $state<HTMLElement>()!;
const inViewport = new IsInViewport(() => targetNode, {
once: true
});
</script>

<div bind:this={targetNode} class="transition" class="transition-opacity {hasBeenSeen ? 'opacity-100' : 'opacity-0'}">
I'll fade in once when first visible, then stop observing
</div>
```

### Observer Controls

The `IsInViewport` class provides methods to control the underlying intersection observer. See
[`useIntersectionObserver`](/docs/utilities/use-intersection-observer#usage) for more information.

## Type Definition

```ts
Expand All @@ -41,7 +68,21 @@ export type IsInViewportOptions = UseIntersectionObserverOptions;

export declare class IsInViewport {
constructor(node: MaybeGetter<HTMLElement | null | undefined>, options?: IsInViewportOptions);

/** Current viewport intersection state */
get current(): boolean;

/** Stop observing permanently */
stop(): void;

/** Pause observation temporarily */
pause(): void;

/** Resume observation after pausing */
resume(): void;

/** Whether the observer is currently active */
get isActive(): boolean;
}
```

Expand Down
28 changes: 28 additions & 0 deletions sites/docs/src/content/utilities/use-intersection-observer.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,34 @@ intersection changes of the target element.
</div>
```

### One-time Detection

You can use the `once` option to automatically stop observing after the first intersection:

```svelte
<script lang="ts">
import { useIntersectionObserver } from "runed";

let target = $state<HTMLElement | null>(null);
let hasBeenSeen = $state(false);

useIntersectionObserver(
() => target,
(entries) => {
const entry = entries[0];
if (entry?.isIntersecting) {
hasBeenSeen = true;
}
},
{ once: true }
);
</script>

<div bind:this={target} class="transition" class="transition-opacity {hasBeenSeen ? 'opacity-100' : 'opacity-0'}">
I'll fade in once when first visible, then stop observing
</div>
```

### Pause

You can pause the intersection observer at any point by calling the `pause` method.
Expand Down
2 changes: 1 addition & 1 deletion sites/docs/src/routes/api/search.json/search.json

Large diffs are not rendered by default.