39 lines
1.4 KiB
JavaScript
39 lines
1.4 KiB
JavaScript
|
import * as React from 'react';
|
||
|
import { useFluent_unstable as useFluent } from '@fluentui/react-shared-contexts';
|
||
|
const { useRef, useEffect } = React;
|
||
|
export const useMutationObserver = (target, callback, options)=>{
|
||
|
'use no memo';
|
||
|
// TODO: exclude types from this lint rule: https://github.com/microsoft/fluentui/issues/31286
|
||
|
// eslint-disable-next-line no-restricted-globals
|
||
|
const observer = useRef();
|
||
|
const { targetDocument } = useFluent();
|
||
|
const win = targetDocument === null || targetDocument === void 0 ? void 0 : targetDocument.defaultView;
|
||
|
useEffect(()=>{
|
||
|
if (!win) {
|
||
|
return;
|
||
|
}
|
||
|
// Create an observer instance linked to the callback function
|
||
|
observer.current = new win.MutationObserver(callback);
|
||
|
}, [
|
||
|
callback,
|
||
|
win
|
||
|
]);
|
||
|
useEffect(()=>{
|
||
|
if (target) {
|
||
|
var // Start observing the target node for configured mutations
|
||
|
_observer_current;
|
||
|
(_observer_current = observer.current) === null || _observer_current === void 0 ? void 0 : _observer_current.observe(target, options);
|
||
|
}
|
||
|
return ()=>{
|
||
|
var _observer_current;
|
||
|
(_observer_current = observer.current) === null || _observer_current === void 0 ? void 0 : _observer_current.disconnect();
|
||
|
};
|
||
|
}, [
|
||
|
target,
|
||
|
options
|
||
|
]);
|
||
|
return {
|
||
|
observer
|
||
|
};
|
||
|
};
|