Skip to content

Commit

Permalink
fix: Address observer not watch for DOM update (#138)
Browse files Browse the repository at this point in the history
  • Loading branch information
roderickhsiao authored Sep 20, 2024
1 parent b339d6c commit 7ba72f9
Show file tree
Hide file tree
Showing 8 changed files with 2,493 additions and 4,628 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ jobs:
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v2
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- name: Install
Expand Down
8 changes: 4 additions & 4 deletions .github/workflows/codeql-analysis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ jobs:

steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v4

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
Expand All @@ -53,7 +53,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
uses: github/codeql-action/autobuild@v3

# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
Expand All @@ -67,4 +67,4 @@ jobs:
# make release

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
uses: github/codeql-action/analyze@v3
4 changes: 1 addition & 3 deletions .storybook/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ module.exports = {
'@storybook/addon-actions',
'@storybook/addon-webpack5-compiler-babel'
],
docs: {
autodocs: true
},
docs: {},
framework: {
name: '@storybook/react-webpack5',
options: {}
Expand Down
1 change: 1 addition & 0 deletions .storybook/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ if (typeof window !== 'undefined') {
// Polyfills for intersection-observer
require('intersection-observer'); // eslint-disable-line
}
export const tags = ['autodocs'];
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@

<hr>

Library to detect whether or not a component is in the viewport, using the [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API)
Library to detect whether or not a component is in the viewport, using the [Intersection Observer API](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API).

This library also uses [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to detect the change of the target element.

```npm install --save react-in-viewport```

Expand Down
14 changes: 7 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-in-viewport",
"version": "1.0.0-beta.2",
"version": "1.0.0-beta.3",
"description": "Track React component in viewport using Intersection Observer API",
"author": "Roderick Hsiao <[email protected]>",
"license": "MIT",
Expand Down Expand Up @@ -36,12 +36,12 @@
"@babel/preset-env": "^7.3.1",
"@babel/preset-react": "^7.0.0",
"@babel/preset-typescript": "^7.16.7",
"@storybook/addon-actions": "^8.0.9",
"@storybook/addon-docs": "^8.0.9",
"@storybook/addon-essentials": "^8.0.9",
"@storybook/addon-actions": "^8.3.2",
"@storybook/addon-docs": "^8.3.2",
"@storybook/addon-essentials": "^8.3.2",
"@storybook/addon-webpack5-compiler-babel": "^3.0.3",
"@storybook/react": "^8.0.9",
"@storybook/react-webpack5": "^8.0.9",
"@storybook/react": "^8.3.2",
"@storybook/react-webpack5": "^8.3.2",
"@testing-library/react": "^14.0.0",
"@types/hoist-non-react-statics": "^3.3.1",
"@types/jest": "^29.0.0",
Expand Down Expand Up @@ -71,7 +71,7 @@
"react-aspect-ratio": "^1.1.8",
"react-dom": "^18.0.0",
"react-test-renderer": "^18.0.0",
"storybook": "^8.0.9",
"storybook": "^8.3.2",
"typescript": "^5.0.0",
"webpack": "^5.75.0"
},
Expand Down
61 changes: 53 additions & 8 deletions src/lib/useInViewport.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,42 @@
import React, { useEffect, useRef, useState } from 'react';
import React, {
useCallback,
useEffect,
useRef,
useState,
} from 'react';

import { defaultOptions, defaultConfig, defaultProps } from './constants';

import type { Config, CallbackProps, Options } from './types';

const useDOMObserver = (
ref: React.RefObject<HTMLElement>,
onChange: (mutations: MutationRecord[]) => void,
options: MutationObserverInit = {
attributes: true,
childList: true,
subtree: true,
},
) => {
useEffect(() => {
const currentElement = ref.current;
let observer: MutationObserver;
if (currentElement) {
observer = new MutationObserver(onChange);

// Start observing the DOM element for mutations
observer.observe(currentElement, options);
}

// Cleanup function to stop observing when the component unmounts
return () => {
if (observer) {
observer.disconnect();
}
};
}, [ref, onChange, options]);
};

const useInViewport = (
target: React.RefObject<HTMLElement>,
options: Options = defaultOptions,
Expand Down Expand Up @@ -45,7 +78,7 @@ const useInViewport = (
}

const handleIntersection: IntersectionObserverCallback = (entries) => {
const entry = entries[0] || {} as IntersectionObserverEntry;
const entry = entries[0] || ({} as IntersectionObserverEntry);
const { isIntersecting, intersectionRatio } = entry;
const isInViewport = typeof isIntersecting !== 'undefined'
? isIntersecting
Expand Down Expand Up @@ -83,11 +116,7 @@ const useInViewport = (
return observerRef;
}

useEffect(() => {
let observerRef = observer.current;
// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
observerRef = initIntersectionObserver({ observerRef });

const attachObserver = useCallback(({ observerRef }) => {
startObserver({
observerRef,
});
Expand All @@ -97,7 +126,23 @@ const useInViewport = (
observerRef,
});
};
}, [target.current, options, config, onEnterViewport, onLeaveViewport]);
}, []);

const handleMutation = useCallback(() => {
const observerRef = observer.current;
attachObserver({ observerRef });
}, []);

useEffect(() => {
let observerRef = observer.current;
// https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
observerRef = initIntersectionObserver({ observerRef });

attachObserver({ observerRef });
}, [options, config, onEnterViewport, onLeaveViewport]);

// handles when ref changes
useDOMObserver(target, handleMutation);

return {
inViewport: inViewportRef.current,
Expand Down
Loading

0 comments on commit 7ba72f9

Please sign in to comment.