|
1 | | -import React, { useEffect, useRef } from 'react'; |
2 | | -import { composeRef, supportRef } from 'rc-util/lib/ref'; |
3 | | -import findDOMNode from 'rc-util/lib/Dom/findDOMNode'; |
4 | | -import canUseDom from 'rc-util/lib/Dom/canUseDom'; |
5 | | -import useEvent from 'rc-util/lib/hooks/useEvent'; |
6 | | -import DomWrapper from './wrapper'; |
7 | | -import type { MutationObserverProps } from './interface'; |
| 1 | +import MutateObserver from './MutateObserver'; |
| 2 | +import useMutateObserver from './useMutateObserver'; |
8 | 3 |
|
9 | | -const defOptions: MutationObserverInit = { |
10 | | - subtree: true, |
11 | | - childList: true, |
12 | | - attributeFilter: ['style', 'class'], |
13 | | -}; |
14 | | - |
15 | | -const MutateObserver: React.FC<MutationObserverProps> = props => { |
16 | | - const { children, options = defOptions, onMutate = () => {} } = props; |
17 | | - |
18 | | - const callback = useEvent(onMutate); |
19 | | - |
20 | | - const wrapperRef = useRef<DomWrapper>(null); |
21 | | - |
22 | | - const elementRef = React.useRef<HTMLElement>(null); |
23 | | - |
24 | | - const canRef = React.isValidElement(children) && supportRef(children); |
25 | | - |
26 | | - const originRef: React.Ref<Element> = canRef ? (children as any)?.ref : null; |
27 | | - |
28 | | - const mergedRef = React.useMemo<React.Ref<Element>>( |
29 | | - () => composeRef<Element>(originRef, elementRef), |
30 | | - [originRef, elementRef], |
31 | | - ); |
32 | | - |
33 | | - useEffect(() => { |
34 | | - if (!canUseDom()) { |
35 | | - return; |
36 | | - } |
37 | | - |
38 | | - let instance: MutationObserver; |
39 | | - |
40 | | - const currentElement = |
41 | | - findDOMNode((originRef as any)?.current) || |
42 | | - findDOMNode(wrapperRef?.current); |
43 | | - |
44 | | - if (currentElement && 'MutationObserver' in window) { |
45 | | - instance = new MutationObserver(callback); |
46 | | - instance.observe(currentElement, options); |
47 | | - } |
48 | | - return () => { |
49 | | - instance?.takeRecords(); |
50 | | - instance?.disconnect(); |
51 | | - }; |
52 | | - // eslint-disable-next-line react-hooks/exhaustive-deps |
53 | | - }, [options, originRef]); |
54 | | - |
55 | | - if (!children) { |
56 | | - if (process.env.NODE_ENV !== 'production') { |
57 | | - console.error('MutationObserver need children props'); |
58 | | - } |
59 | | - return null; |
60 | | - } |
61 | | - |
62 | | - return ( |
63 | | - <DomWrapper ref={wrapperRef}> |
64 | | - {canRef |
65 | | - ? React.cloneElement(children as any, { ref: mergedRef }) |
66 | | - : children} |
67 | | - </DomWrapper> |
68 | | - ); |
69 | | -}; |
| 4 | +export { useMutateObserver }; |
70 | 5 |
|
71 | 6 | export default MutateObserver; |
0 commit comments