@wordpress/compose 7.6.0 → 7.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/README.md +1 -1
  3. package/build/hooks/use-copy-on-click/index.js +5 -5
  4. package/build/hooks/use-copy-on-click/index.js.map +1 -1
  5. package/build/hooks/use-focus-on-mount/index.js +4 -4
  6. package/build/hooks/use-focus-on-mount/index.js.map +1 -1
  7. package/build/hooks/use-focus-outside/index.js +11 -11
  8. package/build/hooks/use-focus-outside/index.js.map +1 -1
  9. package/build/hooks/use-keyboard-shortcut/index.js +3 -3
  10. package/build/hooks/use-keyboard-shortcut/index.js.map +1 -1
  11. package/build/hooks/use-merge-refs/index.js +12 -12
  12. package/build/hooks/use-merge-refs/index.js.map +1 -1
  13. package/build/hooks/use-ref-effect/index.js +4 -4
  14. package/build/hooks/use-ref-effect/index.js.map +1 -1
  15. package/build/hooks/use-resize-observer/index.js +79 -184
  16. package/build/hooks/use-resize-observer/index.js.map +1 -1
  17. package/build-module/hooks/use-copy-on-click/index.js +5 -5
  18. package/build-module/hooks/use-copy-on-click/index.js.map +1 -1
  19. package/build-module/hooks/use-focus-on-mount/index.js +4 -4
  20. package/build-module/hooks/use-focus-on-mount/index.js.map +1 -1
  21. package/build-module/hooks/use-focus-outside/index.js +11 -11
  22. package/build-module/hooks/use-focus-outside/index.js.map +1 -1
  23. package/build-module/hooks/use-keyboard-shortcut/index.js +3 -3
  24. package/build-module/hooks/use-keyboard-shortcut/index.js.map +1 -1
  25. package/build-module/hooks/use-merge-refs/index.js +12 -12
  26. package/build-module/hooks/use-merge-refs/index.js.map +1 -1
  27. package/build-module/hooks/use-ref-effect/index.js +4 -4
  28. package/build-module/hooks/use-ref-effect/index.js.map +1 -1
  29. package/build-module/hooks/use-resize-observer/index.js +79 -184
  30. package/build-module/hooks/use-resize-observer/index.js.map +1 -1
  31. package/build-types/hooks/use-merge-refs/index.d.ts.map +1 -1
  32. package/build-types/hooks/use-resize-observer/index.d.ts +8 -14
  33. package/build-types/hooks/use-resize-observer/index.d.ts.map +1 -1
  34. package/package.json +9 -9
  35. package/src/hooks/use-copy-on-click/index.js +5 -5
  36. package/src/hooks/use-focus-on-mount/index.js +4 -4
  37. package/src/hooks/use-focus-outside/index.ts +11 -11
  38. package/src/hooks/use-keyboard-shortcut/index.js +3 -3
  39. package/src/hooks/use-merge-refs/index.js +15 -13
  40. package/src/hooks/use-ref-effect/index.ts +4 -4
  41. package/src/hooks/use-resize-observer/index.tsx +85 -288
  42. package/tsconfig.tsbuildinfo +1 -1
@@ -31,7 +31,7 @@ export default function useCopyOnClick( ref, text, timeout = 4000 ) {
31
31
  } );
32
32
 
33
33
  /** @type {import('react').MutableRefObject<Clipboard | undefined>} */
34
- const clipboard = useRef();
34
+ const clipboardRef = useRef();
35
35
  const [ hasCopied, setHasCopied ] = useState( false );
36
36
 
37
37
  useEffect( () => {
@@ -43,11 +43,11 @@ export default function useCopyOnClick( ref, text, timeout = 4000 ) {
43
43
  }
44
44
 
45
45
  // Clipboard listens to click events.
46
- clipboard.current = new Clipboard( ref.current, {
46
+ clipboardRef.current = new Clipboard( ref.current, {
47
47
  text: () => ( typeof text === 'function' ? text() : text ),
48
48
  } );
49
49
 
50
- clipboard.current.on( 'success', ( { clearSelection, trigger } ) => {
50
+ clipboardRef.current.on( 'success', ( { clearSelection, trigger } ) => {
51
51
  // Clearing selection will move focus back to the triggering button,
52
52
  // ensuring that it is not reset to the body, and further that it is
53
53
  // kept within the rendered node.
@@ -66,8 +66,8 @@ export default function useCopyOnClick( ref, text, timeout = 4000 ) {
66
66
  } );
67
67
 
68
68
  return () => {
69
- if ( clipboard.current ) {
70
- clipboard.current.destroy();
69
+ if ( clipboardRef.current ) {
70
+ clipboardRef.current.destroy();
71
71
  }
72
72
  clearTimeout( timeoutId );
73
73
  };
@@ -49,7 +49,7 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) {
49
49
  };
50
50
 
51
51
  /** @type {import('react').MutableRefObject<ReturnType<setTimeout> | undefined>} */
52
- const timerId = useRef();
52
+ const timerIdRef = useRef();
53
53
 
54
54
  useEffect( () => {
55
55
  focusOnMountRef.current = focusOnMount;
@@ -65,7 +65,7 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) {
65
65
  }
66
66
 
67
67
  if ( focusOnMountRef.current === 'firstElement' ) {
68
- timerId.current = setTimeout( () => {
68
+ timerIdRef.current = setTimeout( () => {
69
69
  const firstTabbable = focus.tabbable.find( node )[ 0 ];
70
70
 
71
71
  if ( firstTabbable ) {
@@ -79,8 +79,8 @@ export default function useFocusOnMount( focusOnMount = 'firstElement' ) {
79
79
  setFocus( node );
80
80
 
81
81
  return () => {
82
- if ( timerId.current ) {
83
- clearTimeout( timerId.current );
82
+ if ( timerIdRef.current ) {
83
+ clearTimeout( timerIdRef.current );
84
84
  }
85
85
  };
86
86
  }, [] );
@@ -71,20 +71,20 @@ type UseFocusOutsideReturn = {
71
71
  export default function useFocusOutside(
72
72
  onFocusOutside: ( ( event: React.FocusEvent ) => void ) | undefined
73
73
  ): UseFocusOutsideReturn {
74
- const currentOnFocusOutside = useRef( onFocusOutside );
74
+ const currentOnFocusOutsideRef = useRef( onFocusOutside );
75
75
  useEffect( () => {
76
- currentOnFocusOutside.current = onFocusOutside;
76
+ currentOnFocusOutsideRef.current = onFocusOutside;
77
77
  }, [ onFocusOutside ] );
78
78
 
79
- const preventBlurCheck = useRef( false );
79
+ const preventBlurCheckRef = useRef( false );
80
80
 
81
- const blurCheckTimeoutId = useRef< number | undefined >();
81
+ const blurCheckTimeoutIdRef = useRef< number | undefined >();
82
82
 
83
83
  /**
84
84
  * Cancel a blur check timeout.
85
85
  */
86
86
  const cancelBlurCheck = useCallback( () => {
87
- clearTimeout( blurCheckTimeoutId.current );
87
+ clearTimeout( blurCheckTimeoutIdRef.current );
88
88
  }, [] );
89
89
 
90
90
  // Cancel blur checks on unmount.
@@ -116,9 +116,9 @@ export default function useFocusOutside(
116
116
  const isInteractionEnd = [ 'mouseup', 'touchend' ].includes( type );
117
117
 
118
118
  if ( isInteractionEnd ) {
119
- preventBlurCheck.current = false;
119
+ preventBlurCheckRef.current = false;
120
120
  } else if ( isFocusNormalizedButton( target ) ) {
121
- preventBlurCheck.current = true;
121
+ preventBlurCheckRef.current = true;
122
122
  }
123
123
  }, [] );
124
124
 
@@ -135,7 +135,7 @@ export default function useFocusOutside(
135
135
  event.persist();
136
136
 
137
137
  // Skip blur check if clicking button. See `normalizeButtonFocus`.
138
- if ( preventBlurCheck.current ) {
138
+ if ( preventBlurCheckRef.current ) {
139
139
  return;
140
140
  }
141
141
 
@@ -156,7 +156,7 @@ export default function useFocusOutside(
156
156
  return;
157
157
  }
158
158
 
159
- blurCheckTimeoutId.current = setTimeout( () => {
159
+ blurCheckTimeoutIdRef.current = setTimeout( () => {
160
160
  // If document is not focused then focus should remain
161
161
  // inside the wrapped component and therefore we cancel
162
162
  // this blur event thereby leaving focus in place.
@@ -166,8 +166,8 @@ export default function useFocusOutside(
166
166
  return;
167
167
  }
168
168
 
169
- if ( 'function' === typeof currentOnFocusOutside.current ) {
170
- currentOnFocusOutside.current( event );
169
+ if ( 'function' === typeof currentOnFocusOutsideRef.current ) {
170
+ currentOnFocusOutsideRef.current( event );
171
171
  }
172
172
  }, 0 );
173
173
  }, [] );
@@ -42,9 +42,9 @@ function useKeyboardShortcut(
42
42
  target,
43
43
  } = {}
44
44
  ) {
45
- const currentCallback = useRef( callback );
45
+ const currentCallbackRef = useRef( callback );
46
46
  useEffect( () => {
47
- currentCallback.current = callback;
47
+ currentCallbackRef.current = callback;
48
48
  }, [ callback ] );
49
49
 
50
50
  useEffect( () => {
@@ -93,7 +93,7 @@ function useKeyboardShortcut(
93
93
  /** @type {[e: import('mousetrap').ExtendedKeyboardEvent, combo: string]} */ ...args
94
94
  ) =>
95
95
  /* eslint-enable jsdoc/valid-types */
96
- currentCallback.current( ...args ),
96
+ currentCallbackRef.current( ...args ),
97
97
  eventName
98
98
  );
99
99
  } );
@@ -71,28 +71,28 @@ function assignRef( ref, value ) {
71
71
  */
72
72
  export default function useMergeRefs( refs ) {
73
73
  const element = useRef();
74
- const isAttached = useRef( false );
75
- const didElementChange = useRef( false );
74
+ const isAttachedRef = useRef( false );
75
+ const didElementChangeRef = useRef( false );
76
76
  /* eslint-disable jsdoc/no-undefined-types */
77
77
  /** @type {import('react').MutableRefObject<TRef[]>} */
78
78
  /* eslint-enable jsdoc/no-undefined-types */
79
- const previousRefs = useRef( [] );
80
- const currentRefs = useRef( refs );
79
+ const previousRefsRef = useRef( [] );
80
+ const currentRefsRef = useRef( refs );
81
81
 
82
82
  // Update on render before the ref callback is called, so the ref callback
83
83
  // always has access to the current refs.
84
- currentRefs.current = refs;
84
+ currentRefsRef.current = refs;
85
85
 
86
86
  // If any of the refs change, call the previous ref with `null` and the new
87
87
  // ref with the node, except when the element changes in the same cycle, in
88
88
  // which case the ref callbacks will already have been called.
89
89
  useLayoutEffect( () => {
90
90
  if (
91
- didElementChange.current === false &&
92
- isAttached.current === true
91
+ didElementChangeRef.current === false &&
92
+ isAttachedRef.current === true
93
93
  ) {
94
94
  refs.forEach( ( ref, index ) => {
95
- const previousRef = previousRefs.current[ index ];
95
+ const previousRef = previousRefsRef.current[ index ];
96
96
  if ( ref !== previousRef ) {
97
97
  assignRef( previousRef, null );
98
98
  assignRef( ref, element.current );
@@ -100,13 +100,13 @@ export default function useMergeRefs( refs ) {
100
100
  } );
101
101
  }
102
102
 
103
- previousRefs.current = refs;
103
+ previousRefsRef.current = refs;
104
104
  }, refs );
105
105
 
106
106
  // No dependencies, must be reset after every render so ref callbacks are
107
107
  // correctly called after a ref change.
108
108
  useLayoutEffect( () => {
109
- didElementChange.current = false;
109
+ didElementChangeRef.current = false;
110
110
  } );
111
111
 
112
112
  // There should be no dependencies so that `callback` is only called when
@@ -116,12 +116,14 @@ export default function useMergeRefs( refs ) {
116
116
  // dependency change.
117
117
  assignRef( element, value );
118
118
 
119
- didElementChange.current = true;
120
- isAttached.current = value !== null;
119
+ didElementChangeRef.current = true;
120
+ isAttachedRef.current = value !== null;
121
121
 
122
122
  // When an element changes, the current ref callback should be called
123
123
  // with the new element and the previous one with `null`.
124
- const refsToAssign = value ? currentRefs.current : previousRefs.current;
124
+ const refsToAssign = value
125
+ ? currentRefsRef.current
126
+ : previousRefsRef.current;
125
127
 
126
128
  // Update the latest refs.
127
129
  for ( const ref of refsToAssign ) {
@@ -31,12 +31,12 @@ export default function useRefEffect< TElement = Node >(
31
31
  callback: ( node: TElement ) => ( () => void ) | void,
32
32
  dependencies: DependencyList
33
33
  ): RefCallback< TElement | null > {
34
- const cleanup = useRef< ( () => void ) | void >();
34
+ const cleanupRef = useRef< ( () => void ) | void >();
35
35
  return useCallback( ( node: TElement | null ) => {
36
36
  if ( node ) {
37
- cleanup.current = callback( node );
38
- } else if ( cleanup.current ) {
39
- cleanup.current();
37
+ cleanupRef.current = callback( node );
38
+ } else if ( cleanupRef.current ) {
39
+ cleanupRef.current();
40
40
  }
41
41
  }, dependencies );
42
42
  }
@@ -1,116 +1,23 @@
1
1
  /**
2
2
  * External dependencies
3
3
  */
4
- import type { ReactElement, RefCallback, RefObject } from 'react';
4
+ import type { ReactElement } from 'react';
5
5
 
6
6
  /**
7
7
  * WordPress dependencies
8
8
  */
9
9
  import {
10
- useMemo,
11
- useRef,
12
10
  useCallback,
13
- useEffect,
11
+ useLayoutEffect,
12
+ useRef,
14
13
  useState,
15
14
  } from '@wordpress/element';
16
15
 
17
- type SubscriberCleanup = () => void;
18
- type SubscriberResponse = SubscriberCleanup | void;
19
-
20
- // This of course could've been more streamlined with internal state instead of
21
- // refs, but then host hooks / components could not opt out of renders.
22
- // This could've been exported to its own module, but the current build doesn't
23
- // seem to work with module imports and I had no more time to spend on this...
24
- function useResolvedElement< T extends HTMLElement >(
25
- subscriber: ( element: T ) => SubscriberResponse,
26
- refOrElement?: T | RefObject< T > | null
27
- ): RefCallback< T > {
28
- const callbackRefElement = useRef< T | null >( null );
29
- const lastReportRef = useRef< {
30
- reporter: () => void;
31
- element: T | null;
32
- } | null >( null );
33
- const cleanupRef = useRef< SubscriberResponse | null >();
34
-
35
- const callSubscriber = useCallback( () => {
36
- let element = null;
37
- if ( callbackRefElement.current ) {
38
- element = callbackRefElement.current;
39
- } else if ( refOrElement ) {
40
- if ( refOrElement instanceof HTMLElement ) {
41
- element = refOrElement;
42
- } else {
43
- element = refOrElement.current;
44
- }
45
- }
46
-
47
- if (
48
- lastReportRef.current &&
49
- lastReportRef.current.element === element &&
50
- lastReportRef.current.reporter === callSubscriber
51
- ) {
52
- return;
53
- }
54
-
55
- if ( cleanupRef.current ) {
56
- cleanupRef.current();
57
- // Making sure the cleanup is not called accidentally multiple times.
58
- cleanupRef.current = null;
59
- }
60
- lastReportRef.current = {
61
- reporter: callSubscriber,
62
- element,
63
- };
64
-
65
- // Only calling the subscriber, if there's an actual element to report.
66
- if ( element ) {
67
- cleanupRef.current = subscriber( element );
68
- }
69
- }, [ refOrElement, subscriber ] );
70
-
71
- // On each render, we check whether a ref changed, or if we got a new raw
72
- // element.
73
- useEffect( () => {
74
- // With this we're *technically* supporting cases where ref objects' current value changes, but only if there's a
75
- // render accompanying that change as well.
76
- // To guarantee we always have the right element, one must use the ref callback provided instead, but we support
77
- // RefObjects to make the hook API more convenient in certain cases.
78
- callSubscriber();
79
- }, [ callSubscriber ] );
80
-
81
- return useCallback< RefCallback< T > >(
82
- ( element ) => {
83
- callbackRefElement.current = element;
84
- callSubscriber();
85
- },
86
- [ callSubscriber ]
87
- );
88
- }
89
-
90
16
  type ObservedSize = {
91
- width: number | undefined;
92
- height: number | undefined;
17
+ width: number | null;
18
+ height: number | null;
93
19
  };
94
20
 
95
- type ResizeHandler = ( size: ObservedSize ) => void;
96
-
97
- type HookResponse< T extends HTMLElement > = {
98
- ref: RefCallback< T >;
99
- } & ObservedSize;
100
-
101
- // Declaring my own type here instead of using the one provided by TS (available since 4.2.2), because this way I'm not
102
- // forcing consumers to use a specific TS version.
103
- type ResizeObserverBoxOptions =
104
- | 'border-box'
105
- | 'content-box'
106
- | 'device-pixel-content-box';
107
-
108
- declare global {
109
- interface ResizeObserverEntry {
110
- readonly devicePixelContentBoxSize: ReadonlyArray< ResizeObserverSize >;
111
- }
112
- }
113
-
114
21
  // We're only using the first element of the size sequences, until future versions of the spec solidify on how
115
22
  // exactly it'll be used for fragments in multi-column scenarios:
116
23
  // From the spec:
@@ -136,187 +43,88 @@ declare global {
136
43
  // even though it seems we have access to results for all box types.
137
44
  // This also means that we get to keep the current api, being able to return a simple { width, height } pair,
138
45
  // regardless of box option.
139
- const extractSize = (
140
- entry: ResizeObserverEntry,
141
- boxProp: 'borderBoxSize' | 'contentBoxSize' | 'devicePixelContentBoxSize',
142
- sizeType: keyof ResizeObserverSize
143
- ): number | undefined => {
144
- if ( ! entry[ boxProp ] ) {
145
- if ( boxProp === 'contentBoxSize' ) {
146
- // The dimensions in `contentBoxSize` and `contentRect` are equivalent according to the spec.
147
- // See the 6th step in the description for the RO algorithm:
148
- // https://drafts.csswg.org/resize-observer/#create-and-populate-resizeobserverentry-h
149
- // > Set this.contentRect to logical this.contentBoxSize given target and observedBox of "content-box".
150
- // In real browser implementations of course these objects differ, but the width/height values should be equivalent.
151
- return entry.contentRect[
152
- sizeType === 'inlineSize' ? 'width' : 'height'
153
- ];
154
- }
155
-
156
- return undefined;
46
+ const extractSize = ( entry: ResizeObserverEntry ): ObservedSize => {
47
+ let entrySize;
48
+ if ( ! entry.contentBoxSize ) {
49
+ // The dimensions in `contentBoxSize` and `contentRect` are equivalent according to the spec.
50
+ // See the 6th step in the description for the RO algorithm:
51
+ // https://drafts.csswg.org/resize-observer/#create-and-populate-resizeobserverentry-h
52
+ // > Set this.contentRect to logical this.contentBoxSize given target and observedBox of "content-box".
53
+ // In real browser implementations of course these objects differ, but the width/height values should be equivalent.
54
+ entrySize = [ entry.contentRect.width, entry.contentRect.height ];
55
+ } else if ( entry.contentBoxSize[ 0 ] ) {
56
+ const contentBoxSize = entry.contentBoxSize[ 0 ];
57
+ entrySize = [ contentBoxSize.inlineSize, contentBoxSize.blockSize ];
58
+ } else {
59
+ // TS complains about this, because the RO entry type follows the spec and does not reflect Firefox's buggy
60
+ // behaviour of returning objects instead of arrays for `borderBoxSize` and `contentBoxSize`.
61
+ const contentBoxSize =
62
+ entry.contentBoxSize as unknown as ResizeObserverSize;
63
+ entrySize = [ contentBoxSize.inlineSize, contentBoxSize.blockSize ];
157
64
  }
158
65
 
159
- // A couple bytes smaller than calling Array.isArray() and just as effective here.
160
- return entry[ boxProp ][ 0 ]
161
- ? entry[ boxProp ][ 0 ][ sizeType ]
162
- : // TS complains about this, because the RO entry type follows the spec and does not reflect Firefox's current
163
- // behaviour of returning objects instead of arrays for `borderBoxSize` and `contentBoxSize`.
164
- // @ts-ignore
165
- entry[ boxProp ][ sizeType ];
66
+ const [ width, height ] = entrySize.map( ( d ) => Math.round( d ) );
67
+ return { width, height };
68
+ };
69
+
70
+ const RESIZE_ELEMENT_STYLES = {
71
+ position: 'absolute',
72
+ top: 0,
73
+ left: 0,
74
+ right: 0,
75
+ bottom: 0,
76
+ pointerEvents: 'none',
77
+ opacity: 0,
78
+ overflow: 'hidden',
79
+ zIndex: -1,
80
+ } as const;
81
+
82
+ type ResizeElementProps = {
83
+ onResize: ( s: ObservedSize ) => void;
166
84
  };
167
85
 
168
- type RoundingFunction = ( n: number ) => number;
86
+ function ResizeElement( { onResize }: ResizeElementProps ) {
87
+ const resizeElementRef = useRef< HTMLDivElement >( null );
88
+ const resizeCallbackRef = useRef( onResize );
169
89
 
170
- function useResizeObserver< T extends HTMLElement >(
171
- opts: {
172
- ref?: RefObject< T > | T | null | undefined;
173
- onResize?: ResizeHandler;
174
- box?: ResizeObserverBoxOptions;
175
- round?: RoundingFunction;
176
- } = {}
177
- ): HookResponse< T > {
178
- // Saving the callback as a ref. With this, I don't need to put onResize in the
179
- // effect dep array, and just passing in an anonymous function without memoising
180
- // will not reinstantiate the hook's ResizeObserver.
181
- const onResize = opts.onResize;
182
- const onResizeRef = useRef< ResizeHandler | undefined >( undefined );
183
- onResizeRef.current = onResize;
184
- const round = opts.round || Math.round;
90
+ useLayoutEffect( () => {
91
+ resizeCallbackRef.current = onResize;
92
+ }, [ onResize ] );
185
93
 
186
- // Using a single instance throughout the hook's lifetime
187
- const resizeObserverRef = useRef< {
188
- box?: ResizeObserverBoxOptions;
189
- round?: RoundingFunction;
190
- instance: ResizeObserver;
191
- } >();
94
+ useLayoutEffect( () => {
95
+ const resizeElement = resizeElementRef.current as HTMLDivElement;
96
+ const resizeObserver = new ResizeObserver( ( entries ) => {
97
+ for ( const entry of entries ) {
98
+ const newSize = extractSize( entry );
99
+ resizeCallbackRef.current( newSize );
100
+ }
101
+ } );
192
102
 
193
- const [ size, setSize ] = useState< {
194
- width?: number;
195
- height?: number;
196
- } >( {
197
- width: undefined,
198
- height: undefined,
199
- } );
103
+ resizeObserver.observe( resizeElement );
200
104
 
201
- // In certain edge cases the RO might want to report a size change just after
202
- // the component unmounted.
203
- const didUnmount = useRef( false );
204
- useEffect( () => {
205
- didUnmount.current = false;
206
105
  return () => {
207
- didUnmount.current = true;
106
+ resizeObserver.unobserve( resizeElement );
208
107
  };
209
108
  }, [] );
210
109
 
211
- // Using a ref to track the previous width / height to avoid unnecessary renders.
212
- const previous: {
213
- current: {
214
- width?: number;
215
- height?: number;
216
- };
217
- } = useRef( {
218
- width: undefined,
219
- height: undefined,
220
- } );
221
-
222
- // This block is kinda like a useEffect, only it's called whenever a new
223
- // element could be resolved based on the ref option. It also has a cleanup
224
- // function.
225
- const refCallback = useResolvedElement< T >(
226
- useCallback(
227
- ( element ) => {
228
- // We only use a single Resize Observer instance, and we're instantiating it on demand, only once there's something to observe.
229
- // This instance is also recreated when the `box` option changes, so that a new observation is fired if there was a previously observed element with a different box option.
230
- if (
231
- ! resizeObserverRef.current ||
232
- resizeObserverRef.current.box !== opts.box ||
233
- resizeObserverRef.current.round !== round
234
- ) {
235
- resizeObserverRef.current = {
236
- box: opts.box,
237
- round,
238
- instance: new ResizeObserver( ( entries ) => {
239
- const entry = entries[ 0 ];
240
-
241
- let boxProp:
242
- | 'borderBoxSize'
243
- | 'contentBoxSize'
244
- | 'devicePixelContentBoxSize' = 'borderBoxSize';
245
- if ( opts.box === 'border-box' ) {
246
- boxProp = 'borderBoxSize';
247
- } else {
248
- boxProp =
249
- opts.box === 'device-pixel-content-box'
250
- ? 'devicePixelContentBoxSize'
251
- : 'contentBoxSize';
252
- }
253
-
254
- const reportedWidth = extractSize(
255
- entry,
256
- boxProp,
257
- 'inlineSize'
258
- );
259
- const reportedHeight = extractSize(
260
- entry,
261
- boxProp,
262
- 'blockSize'
263
- );
264
-
265
- const newWidth = reportedWidth
266
- ? round( reportedWidth )
267
- : undefined;
268
- const newHeight = reportedHeight
269
- ? round( reportedHeight )
270
- : undefined;
271
-
272
- if (
273
- previous.current.width !== newWidth ||
274
- previous.current.height !== newHeight
275
- ) {
276
- const newSize = {
277
- width: newWidth,
278
- height: newHeight,
279
- };
280
- previous.current.width = newWidth;
281
- previous.current.height = newHeight;
282
- if ( onResizeRef.current ) {
283
- onResizeRef.current( newSize );
284
- } else if ( ! didUnmount.current ) {
285
- setSize( newSize );
286
- }
287
- }
288
- } ),
289
- };
290
- }
291
-
292
- resizeObserverRef.current.instance.observe( element, {
293
- box: opts.box,
294
- } );
295
-
296
- return () => {
297
- if ( resizeObserverRef.current ) {
298
- resizeObserverRef.current.instance.unobserve( element );
299
- }
300
- };
301
- },
302
- [ opts.box, round ]
303
- ),
304
- opts.ref
110
+ return (
111
+ <div
112
+ ref={ resizeElementRef }
113
+ style={ RESIZE_ELEMENT_STYLES }
114
+ aria-hidden="true"
115
+ />
305
116
  );
117
+ }
306
118
 
307
- return useMemo(
308
- () => ( {
309
- ref: refCallback,
310
- width: size.width,
311
- height: size.height,
312
- } ),
313
- [ refCallback, size ? size.width : null, size ? size.height : null ]
314
- );
119
+ function sizeEquals( a: ObservedSize, b: ObservedSize ) {
120
+ return a.width === b.width && a.height === b.height;
315
121
  }
316
122
 
123
+ const NULL_SIZE: ObservedSize = { width: null, height: null };
124
+
317
125
  /**
318
- * Hook which allows to listen the resize event of any target element when it changes sizes.
319
- * _Note: `useResizeObserver` will report `null` until after first render.
126
+ * Hook which allows to listen to the resize event of any target element when it changes size.
127
+ * _Note: `useResizeObserver` will report `null` sizes until after first render.
320
128
  *
321
129
  * @example
322
130
  *
@@ -333,30 +141,19 @@ function useResizeObserver< T extends HTMLElement >(
333
141
  * };
334
142
  * ```
335
143
  */
336
- export default function useResizeAware(): [
337
- ReactElement,
338
- { width: number | null; height: number | null },
339
- ] {
340
- const { ref, width, height } = useResizeObserver();
341
- const sizes = useMemo( () => {
342
- return { width: width ?? null, height: height ?? null };
343
- }, [ width, height ] );
344
- const resizeListener = (
345
- <div
346
- style={ {
347
- position: 'absolute',
348
- top: 0,
349
- left: 0,
350
- right: 0,
351
- bottom: 0,
352
- pointerEvents: 'none',
353
- opacity: 0,
354
- overflow: 'hidden',
355
- zIndex: -1,
356
- } }
357
- aria-hidden="true"
358
- ref={ ref }
359
- />
360
- );
361
- return [ resizeListener, sizes ];
144
+ export default function useResizeObserver(): [ ReactElement, ObservedSize ] {
145
+ const [ size, setSize ] = useState( NULL_SIZE );
146
+
147
+ // Using a ref to track the previous width / height to avoid unnecessary renders.
148
+ const previousSizeRef = useRef( NULL_SIZE );
149
+
150
+ const handleResize = useCallback( ( newSize: ObservedSize ) => {
151
+ if ( ! sizeEquals( previousSizeRef.current, newSize ) ) {
152
+ previousSizeRef.current = newSize;
153
+ setSize( newSize );
154
+ }
155
+ }, [] );
156
+
157
+ const resizeElement = <ResizeElement onResize={ handleResize } />;
158
+ return [ resizeElement, size ];
362
159
  }