1 | ;
|
2 |
|
3 | exports.__esModule = true;
|
4 | exports.default = void 0;
|
5 | var _useCustomEffect = _interopRequireDefault(require("./useCustomEffect"));
|
6 | var _dequal = require("dequal");
|
7 | var _useImmediateUpdateEffect = _interopRequireDefault(require("./useImmediateUpdateEffect"));
|
8 | var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
|
9 | var _react = require("react");
|
10 | function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
11 | function isDepsEqual([nextElement, nextConfig], [prevElement, prevConfig]) {
|
12 | return nextElement === prevElement && (0, _dequal.dequal)(nextConfig, prevConfig);
|
13 | }
|
14 |
|
15 | /**
|
16 | * Observe mutations on a DOM node or tree of DOM nodes.
|
17 | * Depends on the `MutationObserver` api.
|
18 | *
|
19 | * ```tsx
|
20 | * const [element, attachRef] = useCallbackRef(null);
|
21 | *
|
22 | * useMutationObserver(element, { subtree: true }, (records) => {
|
23 | *
|
24 | * });
|
25 | *
|
26 | * return (
|
27 | * <div ref={attachRef} />
|
28 | * )
|
29 | * ```
|
30 | *
|
31 | * @param element The DOM element to observe
|
32 | * @param config The observer configuration
|
33 | * @param callback A callback fired when a mutation occurs
|
34 | */
|
35 |
|
36 | /**
|
37 | * Observe mutations on a DOM node or tree of DOM nodes.
|
38 | * use a `MutationObserver` and return records as the are received.
|
39 | *
|
40 | * ```tsx
|
41 | * const [element, attachRef] = useCallbackRef(null);
|
42 | *
|
43 | * const records = useMutationObserver(element, { subtree: true });
|
44 | *
|
45 | * return (
|
46 | * <div ref={attachRef} />
|
47 | * )
|
48 | * ```
|
49 | *
|
50 | * @param element The DOM element to observe
|
51 | * @param config The observer configuration
|
52 | */
|
53 |
|
54 | function useMutationObserver(element, config, callback) {
|
55 | const [records, setRecords] = (0, _react.useState)(null);
|
56 | const handler = (0, _useEventCallback.default)(callback || setRecords);
|
57 | (0, _useCustomEffect.default)(() => {
|
58 | if (!element) return;
|
59 |
|
60 | // The behavior around reusing mutation observers is confusing
|
61 | // observing again _should_ disable the last listener but doesn't
|
62 | // seem to always be the case, maybe just in JSDOM? In any case the cost
|
63 | // to redeclaring it is gonna be fairly low anyway, so make it simple
|
64 | const observer = new MutationObserver(handler);
|
65 | observer.observe(element, config);
|
66 | return () => {
|
67 | observer.disconnect();
|
68 | };
|
69 | }, [element, config], {
|
70 | isEqual: isDepsEqual,
|
71 | // Intentionally done in render, otherwise observer will miss any
|
72 | // changes made to the DOM during this update
|
73 | effectHook: _useImmediateUpdateEffect.default
|
74 | });
|
75 | return callback ? void 0 : records || [];
|
76 | }
|
77 | var _default = useMutationObserver;
|
78 | exports.default = _default; |
\ | No newline at end of file |